Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(5)

Side by Side Diff: third_party/protobuf/python/google/protobuf/internal/message_test.py

Issue 2495533002: third_party/protobuf: Update to HEAD (83d681ee2c) (Closed)
Patch Set: Make chrome settings proto generated file a component Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 #! /usr/bin/env python 1 #! /usr/bin/env python
2 # 2 #
3 # Protocol Buffers - Google's data interchange format 3 # Protocol Buffers - Google's data interchange format
4 # Copyright 2008 Google Inc. All rights reserved. 4 # Copyright 2008 Google Inc. All rights reserved.
5 # https://developers.google.com/protocol-buffers/ 5 # https://developers.google.com/protocol-buffers/
6 # 6 #
7 # Redistribution and use in source and binary forms, with or without 7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions are 8 # modification, are permitted provided that the following conditions are
9 # met: 9 # met:
10 # 10 #
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
60 from google.protobuf import map_unittest_pb2 60 from google.protobuf import map_unittest_pb2
61 from google.protobuf import unittest_pb2 61 from google.protobuf import unittest_pb2
62 from google.protobuf import unittest_proto3_arena_pb2 62 from google.protobuf import unittest_proto3_arena_pb2
63 from google.protobuf import descriptor_pb2 63 from google.protobuf import descriptor_pb2
64 from google.protobuf import descriptor_pool 64 from google.protobuf import descriptor_pool
65 from google.protobuf import message_factory 65 from google.protobuf import message_factory
66 from google.protobuf import text_format 66 from google.protobuf import text_format
67 from google.protobuf.internal import api_implementation 67 from google.protobuf.internal import api_implementation
68 from google.protobuf.internal import packed_field_test_pb2 68 from google.protobuf.internal import packed_field_test_pb2
69 from google.protobuf.internal import test_util 69 from google.protobuf.internal import test_util
70 from google.protobuf.internal import testing_refleaks
70 from google.protobuf import message 71 from google.protobuf import message
71 from google.protobuf.internal import _parameterized 72 from google.protobuf.internal import _parameterized
72 73
73 if six.PY3: 74 if six.PY3:
74 long = int 75 long = int
75 76
76 77
77 # Python pre-2.6 does not have isinf() or isnan() functions, so we have 78 # Python pre-2.6 does not have isinf() or isnan() functions, so we have
78 # to provide our own. 79 # to provide our own.
79 def isnan(val): 80 def isnan(val):
80 # NaN is never equal to itself. 81 # NaN is never equal to itself.
81 return val != val 82 return val != val
82 def isinf(val): 83 def isinf(val):
83 # Infinity times zero equals NaN. 84 # Infinity times zero equals NaN.
84 return not isnan(val) and isnan(val * 0) 85 return not isnan(val) and isnan(val * 0)
85 def IsPosInf(val): 86 def IsPosInf(val):
86 return isinf(val) and (val > 0) 87 return isinf(val) and (val > 0)
87 def IsNegInf(val): 88 def IsNegInf(val):
88 return isinf(val) and (val < 0) 89 return isinf(val) and (val < 0)
89 90
90 91
91 @_parameterized.Parameters( 92 BaseTestCase = testing_refleaks.BaseTestCase
92 (unittest_pb2), 93
93 (unittest_proto3_arena_pb2)) 94
94 class MessageTest(unittest.TestCase): 95 @_parameterized.NamedParameters(
96 ('_proto2', unittest_pb2),
97 ('_proto3', unittest_proto3_arena_pb2))
98 class MessageTest(BaseTestCase):
95 99
96 def testBadUtf8String(self, message_module): 100 def testBadUtf8String(self, message_module):
97 if api_implementation.Type() != 'python': 101 if api_implementation.Type() != 'python':
98 self.skipTest("Skipping testBadUtf8String, currently only the python " 102 self.skipTest("Skipping testBadUtf8String, currently only the python "
99 "api implementation raises UnicodeDecodeError when a " 103 "api implementation raises UnicodeDecodeError when a "
100 "string field contains bad utf-8.") 104 "string field contains bad utf-8.")
101 bad_utf8_data = test_util.GoldenFileData('bad_utf8_string') 105 bad_utf8_data = test_util.GoldenFileData('bad_utf8_string')
102 with self.assertRaises(UnicodeDecodeError) as context: 106 with self.assertRaises(UnicodeDecodeError) as context:
103 message_module.TestAllTypes.FromString(bad_utf8_data) 107 message_module.TestAllTypes.FromString(bad_utf8_data)
104 self.assertIn('TestAllTypes.optional_string', str(context.exception)) 108 self.assertIn('TestAllTypes.optional_string', str(context.exception))
(...skipping 845 matching lines...) Expand 10 before | Expand all | Expand 10 after
950 for i in range(5): 954 for i in range(5):
951 n = m.repeated_nested_message.add() 955 n = m.repeated_nested_message.add()
952 n.bb = i 956 n.bb = i
953 self.assertEqual(4, m.repeated_nested_message.pop().bb) 957 self.assertEqual(4, m.repeated_nested_message.pop().bb)
954 self.assertEqual(0, m.repeated_nested_message.pop(0).bb) 958 self.assertEqual(0, m.repeated_nested_message.pop(0).bb)
955 self.assertEqual(2, m.repeated_nested_message.pop(1).bb) 959 self.assertEqual(2, m.repeated_nested_message.pop(1).bb)
956 self.assertEqual([1, 3], [n.bb for n in m.repeated_nested_message]) 960 self.assertEqual([1, 3], [n.bb for n in m.repeated_nested_message])
957 961
958 962
959 # Class to test proto2-only features (required, extensions, etc.) 963 # Class to test proto2-only features (required, extensions, etc.)
960 class Proto2Test(unittest.TestCase): 964 class Proto2Test(BaseTestCase):
961 965
962 def testFieldPresence(self): 966 def testFieldPresence(self):
963 message = unittest_pb2.TestAllTypes() 967 message = unittest_pb2.TestAllTypes()
964 968
965 self.assertFalse(message.HasField("optional_int32")) 969 self.assertFalse(message.HasField("optional_int32"))
966 self.assertFalse(message.HasField("optional_bool")) 970 self.assertFalse(message.HasField("optional_bool"))
967 self.assertFalse(message.HasField("optional_nested_message")) 971 self.assertFalse(message.HasField("optional_nested_message"))
968 972
969 with self.assertRaises(ValueError): 973 with self.assertRaises(ValueError):
970 message.HasField("field_doesnt_exist") 974 message.HasField("field_doesnt_exist")
(...skipping 135 matching lines...) Expand 10 before | Expand all | Expand 10 after
1106 unittest_pb2.TestParsingMerge.repeated_ext]), 3) 1110 unittest_pb2.TestParsingMerge.repeated_ext]), 3)
1107 1111
1108 def testPythonicInit(self): 1112 def testPythonicInit(self):
1109 message = unittest_pb2.TestAllTypes( 1113 message = unittest_pb2.TestAllTypes(
1110 optional_int32=100, 1114 optional_int32=100,
1111 optional_fixed32=200, 1115 optional_fixed32=200,
1112 optional_float=300.5, 1116 optional_float=300.5,
1113 optional_bytes=b'x', 1117 optional_bytes=b'x',
1114 optionalgroup={'a': 400}, 1118 optionalgroup={'a': 400},
1115 optional_nested_message={'bb': 500}, 1119 optional_nested_message={'bb': 500},
1120 optional_foreign_message={},
1116 optional_nested_enum='BAZ', 1121 optional_nested_enum='BAZ',
1117 repeatedgroup=[{'a': 600}, 1122 repeatedgroup=[{'a': 600},
1118 {'a': 700}], 1123 {'a': 700}],
1119 repeated_nested_enum=['FOO', unittest_pb2.TestAllTypes.BAR], 1124 repeated_nested_enum=['FOO', unittest_pb2.TestAllTypes.BAR],
1120 default_int32=800, 1125 default_int32=800,
1121 oneof_string='y') 1126 oneof_string='y')
1122 self.assertIsInstance(message, unittest_pb2.TestAllTypes) 1127 self.assertIsInstance(message, unittest_pb2.TestAllTypes)
1123 self.assertEqual(100, message.optional_int32) 1128 self.assertEqual(100, message.optional_int32)
1124 self.assertEqual(200, message.optional_fixed32) 1129 self.assertEqual(200, message.optional_fixed32)
1125 self.assertEqual(300.5, message.optional_float) 1130 self.assertEqual(300.5, message.optional_float)
1126 self.assertEqual(b'x', message.optional_bytes) 1131 self.assertEqual(b'x', message.optional_bytes)
1127 self.assertEqual(400, message.optionalgroup.a) 1132 self.assertEqual(400, message.optionalgroup.a)
1128 self.assertIsInstance(message.optional_nested_message, unittest_pb2.TestAllT ypes.NestedMessage) 1133 self.assertIsInstance(message.optional_nested_message,
1134 unittest_pb2.TestAllTypes.NestedMessage)
1129 self.assertEqual(500, message.optional_nested_message.bb) 1135 self.assertEqual(500, message.optional_nested_message.bb)
1136 self.assertTrue(message.HasField('optional_foreign_message'))
1137 self.assertEqual(message.optional_foreign_message,
1138 unittest_pb2.ForeignMessage())
1130 self.assertEqual(unittest_pb2.TestAllTypes.BAZ, 1139 self.assertEqual(unittest_pb2.TestAllTypes.BAZ,
1131 message.optional_nested_enum) 1140 message.optional_nested_enum)
1132 self.assertEqual(2, len(message.repeatedgroup)) 1141 self.assertEqual(2, len(message.repeatedgroup))
1133 self.assertEqual(600, message.repeatedgroup[0].a) 1142 self.assertEqual(600, message.repeatedgroup[0].a)
1134 self.assertEqual(700, message.repeatedgroup[1].a) 1143 self.assertEqual(700, message.repeatedgroup[1].a)
1135 self.assertEqual(2, len(message.repeated_nested_enum)) 1144 self.assertEqual(2, len(message.repeated_nested_enum))
1136 self.assertEqual(unittest_pb2.TestAllTypes.FOO, 1145 self.assertEqual(unittest_pb2.TestAllTypes.FOO,
1137 message.repeated_nested_enum[0]) 1146 message.repeated_nested_enum[0])
1138 self.assertEqual(unittest_pb2.TestAllTypes.BAR, 1147 self.assertEqual(unittest_pb2.TestAllTypes.BAR,
1139 message.repeated_nested_enum[1]) 1148 message.repeated_nested_enum[1])
(...skipping 17 matching lines...) Expand all
1157 1166
1158 with self.assertRaises(ValueError): 1167 with self.assertRaises(ValueError):
1159 unittest_pb2.TestAllTypes(optional_nested_enum='INVALID_LABEL') 1168 unittest_pb2.TestAllTypes(optional_nested_enum='INVALID_LABEL')
1160 1169
1161 with self.assertRaises(ValueError): 1170 with self.assertRaises(ValueError):
1162 unittest_pb2.TestAllTypes(repeated_nested_enum='FOO') 1171 unittest_pb2.TestAllTypes(repeated_nested_enum='FOO')
1163 1172
1164 1173
1165 1174
1166 # Class to test proto3-only features/behavior (updated field presence & enums) 1175 # Class to test proto3-only features/behavior (updated field presence & enums)
1167 class Proto3Test(unittest.TestCase): 1176 class Proto3Test(BaseTestCase):
1168 1177
1169 # Utility method for comparing equality with a map. 1178 # Utility method for comparing equality with a map.
1170 def assertMapIterEquals(self, map_iter, dict_value): 1179 def assertMapIterEquals(self, map_iter, dict_value):
1171 # Avoid mutating caller's copy. 1180 # Avoid mutating caller's copy.
1172 dict_value = dict(dict_value) 1181 dict_value = dict(dict_value)
1173 1182
1174 for k, v in map_iter: 1183 for k, v in map_iter:
1175 self.assertEqual(v, dict_value[k]) 1184 self.assertEqual(v, dict_value[k])
1176 del dict_value[k] 1185 del dict_value[k]
1177 1186
(...skipping 250 matching lines...) Expand 10 before | Expand all | Expand 10 after
1428 msg.map_int32_int32[12] = 34 1437 msg.map_int32_int32[12] = 34
1429 msg.map_int32_int32[56] = 78 1438 msg.map_int32_int32[56] = 78
1430 msg.map_int64_int64[22] = 33 1439 msg.map_int64_int64[22] = 33
1431 msg.map_int32_foreign_message[111].c = 5 1440 msg.map_int32_foreign_message[111].c = 5
1432 msg.map_int32_foreign_message[222].c = 10 1441 msg.map_int32_foreign_message[222].c = 10
1433 1442
1434 msg2 = map_unittest_pb2.TestMap() 1443 msg2 = map_unittest_pb2.TestMap()
1435 msg2.map_int32_int32[12] = 55 1444 msg2.map_int32_int32[12] = 55
1436 msg2.map_int64_int64[88] = 99 1445 msg2.map_int64_int64[88] = 99
1437 msg2.map_int32_foreign_message[222].c = 15 1446 msg2.map_int32_foreign_message[222].c = 15
1447 msg2.map_int32_foreign_message[222].d = 20
1448 old_map_value = msg2.map_int32_foreign_message[222]
1438 1449
1439 msg2.MergeFrom(msg) 1450 msg2.MergeFrom(msg)
1440 1451
1441 self.assertEqual(34, msg2.map_int32_int32[12]) 1452 self.assertEqual(34, msg2.map_int32_int32[12])
1442 self.assertEqual(78, msg2.map_int32_int32[56]) 1453 self.assertEqual(78, msg2.map_int32_int32[56])
1443 self.assertEqual(33, msg2.map_int64_int64[22]) 1454 self.assertEqual(33, msg2.map_int64_int64[22])
1444 self.assertEqual(99, msg2.map_int64_int64[88]) 1455 self.assertEqual(99, msg2.map_int64_int64[88])
1445 self.assertEqual(5, msg2.map_int32_foreign_message[111].c) 1456 self.assertEqual(5, msg2.map_int32_foreign_message[111].c)
1446 self.assertEqual(10, msg2.map_int32_foreign_message[222].c) 1457 self.assertEqual(10, msg2.map_int32_foreign_message[222].c)
1458 self.assertFalse(msg2.map_int32_foreign_message[222].HasField('d'))
1459 self.assertEqual(15, old_map_value.c)
1447 1460
1448 # Verify that there is only one entry per key, even though the MergeFrom 1461 # Verify that there is only one entry per key, even though the MergeFrom
1449 # may have internally created multiple entries for a single key in the 1462 # may have internally created multiple entries for a single key in the
1450 # list representation. 1463 # list representation.
1451 as_dict = {} 1464 as_dict = {}
1452 for key in msg2.map_int32_foreign_message: 1465 for key in msg2.map_int32_foreign_message:
1453 self.assertFalse(key in as_dict) 1466 self.assertFalse(key in as_dict)
1454 as_dict[key] = msg2.map_int32_foreign_message[key].c 1467 as_dict[key] = msg2.map_int32_foreign_message[key].c
1455 1468
1456 self.assertEqual({111: 5, 222: 10}, as_dict) 1469 self.assertEqual({111: 5, 222: 10}, as_dict)
(...skipping 252 matching lines...) Expand 10 before | Expand all | Expand 10 after
1709 1722
1710 def testMapFindInitializationErrorsSmokeTest(self): 1723 def testMapFindInitializationErrorsSmokeTest(self):
1711 msg = map_unittest_pb2.TestMap() 1724 msg = map_unittest_pb2.TestMap()
1712 msg.map_string_string['abc'] = '123' 1725 msg.map_string_string['abc'] = '123'
1713 msg.map_int32_int32[35] = 64 1726 msg.map_int32_int32[35] = 64
1714 msg.map_string_foreign_message['foo'].c = 5 1727 msg.map_string_foreign_message['foo'].c = 5
1715 self.assertEqual(0, len(msg.FindInitializationErrors())) 1728 self.assertEqual(0, len(msg.FindInitializationErrors()))
1716 1729
1717 1730
1718 1731
1719 class ValidTypeNamesTest(unittest.TestCase): 1732 class ValidTypeNamesTest(BaseTestCase):
1720 1733
1721 def assertImportFromName(self, msg, base_name): 1734 def assertImportFromName(self, msg, base_name):
1722 # Parse <type 'module.class_name'> to extra 'some.name' as a string. 1735 # Parse <type 'module.class_name'> to extra 'some.name' as a string.
1723 tp_name = str(type(msg)).split("'")[1] 1736 tp_name = str(type(msg)).split("'")[1]
1724 valid_names = ('Repeated%sContainer' % base_name, 1737 valid_names = ('Repeated%sContainer' % base_name,
1725 'Repeated%sFieldContainer' % base_name) 1738 'Repeated%sFieldContainer' % base_name)
1726 self.assertTrue(any(tp_name.endswith(v) for v in valid_names), 1739 self.assertTrue(any(tp_name.endswith(v) for v in valid_names),
1727 '%r does end with any of %r' % (tp_name, valid_names)) 1740 '%r does end with any of %r' % (tp_name, valid_names))
1728 1741
1729 parts = tp_name.split('.') 1742 parts = tp_name.split('.')
1730 class_name = parts[-1] 1743 class_name = parts[-1]
1731 module_name = '.'.join(parts[:-1]) 1744 module_name = '.'.join(parts[:-1])
1732 __import__(module_name, fromlist=[class_name]) 1745 __import__(module_name, fromlist=[class_name])
1733 1746
1734 def testTypeNamesCanBeImported(self): 1747 def testTypeNamesCanBeImported(self):
1735 # If import doesn't work, pickling won't work either. 1748 # If import doesn't work, pickling won't work either.
1736 pb = unittest_pb2.TestAllTypes() 1749 pb = unittest_pb2.TestAllTypes()
1737 self.assertImportFromName(pb.repeated_int32, 'Scalar') 1750 self.assertImportFromName(pb.repeated_int32, 'Scalar')
1738 self.assertImportFromName(pb.repeated_nested_message, 'Composite') 1751 self.assertImportFromName(pb.repeated_nested_message, 'Composite')
1739 1752
1740 class PackedFieldTest(unittest.TestCase): 1753 class PackedFieldTest(BaseTestCase):
1741 1754
1742 def setMessage(self, message): 1755 def setMessage(self, message):
1743 message.repeated_int32.append(1) 1756 message.repeated_int32.append(1)
1744 message.repeated_int64.append(1) 1757 message.repeated_int64.append(1)
1745 message.repeated_uint32.append(1) 1758 message.repeated_uint32.append(1)
1746 message.repeated_uint64.append(1) 1759 message.repeated_uint64.append(1)
1747 message.repeated_sint32.append(1) 1760 message.repeated_sint32.append(1)
1748 message.repeated_sint64.append(1) 1761 message.repeated_sint64.append(1)
1749 message.repeated_fixed32.append(1) 1762 message.repeated_fixed32.append(1)
1750 message.repeated_fixed64.append(1) 1763 message.repeated_fixed64.append(1)
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
1789 b'\x51\x01\x00\x00\x00\x00\x00\x00\x00' 1802 b'\x51\x01\x00\x00\x00\x00\x00\x00\x00'
1790 b'\x5D\x00\x00\x80\x3f' 1803 b'\x5D\x00\x00\x80\x3f'
1791 b'\x61\x00\x00\x00\x00\x00\x00\xf0\x3f' 1804 b'\x61\x00\x00\x00\x00\x00\x00\xf0\x3f'
1792 b'\x68\x01' 1805 b'\x68\x01'
1793 b'\x70\x01') 1806 b'\x70\x01')
1794 self.assertEqual(golden_data, message.SerializeToString()) 1807 self.assertEqual(golden_data, message.SerializeToString())
1795 1808
1796 1809
1797 @unittest.skipIf(api_implementation.Type() != 'cpp', 1810 @unittest.skipIf(api_implementation.Type() != 'cpp',
1798 'explicit tests of the C++ implementation') 1811 'explicit tests of the C++ implementation')
1799 class OversizeProtosTest(unittest.TestCase): 1812 class OversizeProtosTest(BaseTestCase):
1800 1813
1801 def setUp(self): 1814 @classmethod
1802 self.file_desc = """ 1815 def setUpClass(cls):
1816 # At the moment, reference cycles between DescriptorPool and Message classes
1817 # are not detected and these objects are never freed.
1818 # To avoid errors with ReferenceLeakChecker, we create the class only once.
1819 file_desc = """
1803 name: "f/f.msg2" 1820 name: "f/f.msg2"
1804 package: "f" 1821 package: "f"
1805 message_type { 1822 message_type {
1806 name: "msg1" 1823 name: "msg1"
1807 field { 1824 field {
1808 name: "payload" 1825 name: "payload"
1809 number: 1 1826 number: 1
1810 label: LABEL_OPTIONAL 1827 label: LABEL_OPTIONAL
1811 type: TYPE_STRING 1828 type: TYPE_STRING
1812 } 1829 }
1813 } 1830 }
1814 message_type { 1831 message_type {
1815 name: "msg2" 1832 name: "msg2"
1816 field { 1833 field {
1817 name: "field" 1834 name: "field"
1818 number: 1 1835 number: 1
1819 label: LABEL_OPTIONAL 1836 label: LABEL_OPTIONAL
1820 type: TYPE_MESSAGE 1837 type: TYPE_MESSAGE
1821 type_name: "msg1" 1838 type_name: "msg1"
1822 } 1839 }
1823 } 1840 }
1824 """ 1841 """
1825 pool = descriptor_pool.DescriptorPool() 1842 pool = descriptor_pool.DescriptorPool()
1826 desc = descriptor_pb2.FileDescriptorProto() 1843 desc = descriptor_pb2.FileDescriptorProto()
1827 text_format.Parse(self.file_desc, desc) 1844 text_format.Parse(file_desc, desc)
1828 pool.Add(desc) 1845 pool.Add(desc)
1829 self.proto_cls = message_factory.MessageFactory(pool).GetPrototype( 1846 cls.proto_cls = message_factory.MessageFactory(pool).GetPrototype(
1830 pool.FindMessageTypeByName('f.msg2')) 1847 pool.FindMessageTypeByName('f.msg2'))
1848
1849 def setUp(self):
1831 self.p = self.proto_cls() 1850 self.p = self.proto_cls()
1832 self.p.field.payload = 'c' * (1024 * 1024 * 64 + 1) 1851 self.p.field.payload = 'c' * (1024 * 1024 * 64 + 1)
1833 self.p_serialized = self.p.SerializeToString() 1852 self.p_serialized = self.p.SerializeToString()
1834 1853
1835 def testAssertOversizeProto(self): 1854 def testAssertOversizeProto(self):
1836 from google.protobuf.pyext._message import SetAllowOversizeProtos 1855 from google.protobuf.pyext._message import SetAllowOversizeProtos
1837 SetAllowOversizeProtos(False) 1856 SetAllowOversizeProtos(False)
1838 q = self.proto_cls() 1857 q = self.proto_cls()
1839 try: 1858 try:
1840 q.ParseFromString(self.p_serialized) 1859 q.ParseFromString(self.p_serialized)
1841 except message.DecodeError as e: 1860 except message.DecodeError as e:
1842 self.assertEqual(str(e), 'Error parsing message') 1861 self.assertEqual(str(e), 'Error parsing message')
1843 1862
1844 def testSucceedOversizeProto(self): 1863 def testSucceedOversizeProto(self):
1845 from google.protobuf.pyext._message import SetAllowOversizeProtos 1864 from google.protobuf.pyext._message import SetAllowOversizeProtos
1846 SetAllowOversizeProtos(True) 1865 SetAllowOversizeProtos(True)
1847 q = self.proto_cls() 1866 q = self.proto_cls()
1848 q.ParseFromString(self.p_serialized) 1867 q.ParseFromString(self.p_serialized)
1849 self.assertEqual(self.p.field.payload, q.field.payload) 1868 self.assertEqual(self.p.field.payload, q.field.payload)
1850 1869
1851 if __name__ == '__main__': 1870 if __name__ == '__main__':
1852 unittest.main() 1871 unittest.main()
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698