reflection_test.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Protocol Buffers - Google's data interchange format
  5. # Copyright 2008 Google Inc. All rights reserved.
  6. # http://code.google.com/p/protobuf/
  7. #
  8. # Redistribution and use in source and binary forms, with or without
  9. # modification, are permitted provided that the following conditions are
  10. # met:
  11. #
  12. # * Redistributions of source code must retain the above copyright
  13. # notice, this list of conditions and the following disclaimer.
  14. # * Redistributions in binary form must reproduce the above
  15. # copyright notice, this list of conditions and the following disclaimer
  16. # in the documentation and/or other materials provided with the
  17. # distribution.
  18. # * Neither the name of Google Inc. nor the names of its
  19. # contributors may be used to endorse or promote products derived from
  20. # this software without specific prior written permission.
  21. #
  22. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. """Unittest for reflection.py, which also indirectly tests the output of the
  34. pure-Python protocol compiler.
  35. """
  36. __author__ = 'robinson@google.com (Will Robinson)'
  37. import operator
  38. import unittest
  39. # TODO(robinson): When we split this test in two, only some of these imports
  40. # will be necessary in each test.
  41. from google.protobuf import unittest_import_pb2
  42. from google.protobuf import unittest_mset_pb2
  43. from google.protobuf import unittest_pb2
  44. from google.protobuf import descriptor_pb2
  45. from google.protobuf import descriptor
  46. from google.protobuf import message
  47. from google.protobuf import reflection
  48. from google.protobuf.internal import more_extensions_pb2
  49. from google.protobuf.internal import more_messages_pb2
  50. from google.protobuf.internal import wire_format
  51. from google.protobuf.internal import test_util
  52. from google.protobuf.internal import decoder
  53. class RefectionTest(unittest.TestCase):
  54. def testSimpleHasBits(self):
  55. # Test a scalar.
  56. proto = unittest_pb2.TestAllTypes()
  57. self.assertTrue(not proto.HasField('optional_int32'))
  58. self.assertEqual(0, proto.optional_int32)
  59. # HasField() shouldn't be true if all we've done is
  60. # read the default value.
  61. self.assertTrue(not proto.HasField('optional_int32'))
  62. proto.optional_int32 = 1
  63. # Setting a value however *should* set the "has" bit.
  64. self.assertTrue(proto.HasField('optional_int32'))
  65. proto.ClearField('optional_int32')
  66. # And clearing that value should unset the "has" bit.
  67. self.assertTrue(not proto.HasField('optional_int32'))
  68. def testHasBitsWithSinglyNestedScalar(self):
  69. # Helper used to test foreign messages and groups.
  70. #
  71. # composite_field_name should be the name of a non-repeated
  72. # composite (i.e., foreign or group) field in TestAllTypes,
  73. # and scalar_field_name should be the name of an integer-valued
  74. # scalar field within that composite.
  75. #
  76. # I never thought I'd miss C++ macros and templates so much. :(
  77. # This helper is semantically just:
  78. #
  79. # assert proto.composite_field.scalar_field == 0
  80. # assert not proto.composite_field.HasField('scalar_field')
  81. # assert not proto.HasField('composite_field')
  82. #
  83. # proto.composite_field.scalar_field = 10
  84. # old_composite_field = proto.composite_field
  85. #
  86. # assert proto.composite_field.scalar_field == 10
  87. # assert proto.composite_field.HasField('scalar_field')
  88. # assert proto.HasField('composite_field')
  89. #
  90. # proto.ClearField('composite_field')
  91. #
  92. # assert not proto.composite_field.HasField('scalar_field')
  93. # assert not proto.HasField('composite_field')
  94. # assert proto.composite_field.scalar_field == 0
  95. #
  96. # # Now ensure that ClearField('composite_field') disconnected
  97. # # the old field object from the object tree...
  98. # assert old_composite_field is not proto.composite_field
  99. # old_composite_field.scalar_field = 20
  100. # assert not proto.composite_field.HasField('scalar_field')
  101. # assert not proto.HasField('composite_field')
  102. def TestCompositeHasBits(composite_field_name, scalar_field_name):
  103. proto = unittest_pb2.TestAllTypes()
  104. # First, check that we can get the scalar value, and see that it's the
  105. # default (0), but that proto.HasField('omposite') and
  106. # proto.composite.HasField('scalar') will still return False.
  107. composite_field = getattr(proto, composite_field_name)
  108. original_scalar_value = getattr(composite_field, scalar_field_name)
  109. self.assertEqual(0, original_scalar_value)
  110. # Assert that the composite object does not "have" the scalar.
  111. self.assertTrue(not composite_field.HasField(scalar_field_name))
  112. # Assert that proto does not "have" the composite field.
  113. self.assertTrue(not proto.HasField(composite_field_name))
  114. # Now set the scalar within the composite field. Ensure that the setting
  115. # is reflected, and that proto.HasField('composite') and
  116. # proto.composite.HasField('scalar') now both return True.
  117. new_val = 20
  118. setattr(composite_field, scalar_field_name, new_val)
  119. self.assertEqual(new_val, getattr(composite_field, scalar_field_name))
  120. # Hold on to a reference to the current composite_field object.
  121. old_composite_field = composite_field
  122. # Assert that the has methods now return true.
  123. self.assertTrue(composite_field.HasField(scalar_field_name))
  124. self.assertTrue(proto.HasField(composite_field_name))
  125. # Now call the clear method...
  126. proto.ClearField(composite_field_name)
  127. # ...and ensure that the "has" bits are all back to False...
  128. composite_field = getattr(proto, composite_field_name)
  129. self.assertTrue(not composite_field.HasField(scalar_field_name))
  130. self.assertTrue(not proto.HasField(composite_field_name))
  131. # ...and ensure that the scalar field has returned to its default.
  132. self.assertEqual(0, getattr(composite_field, scalar_field_name))
  133. # Finally, ensure that modifications to the old composite field object
  134. # don't have any effect on the parent.
  135. #
  136. # (NOTE that when we clear the composite field in the parent, we actually
  137. # don't recursively clear down the tree. Instead, we just disconnect the
  138. # cleared composite from the tree.)
  139. self.assertTrue(old_composite_field is not composite_field)
  140. setattr(old_composite_field, scalar_field_name, new_val)
  141. self.assertTrue(not composite_field.HasField(scalar_field_name))
  142. self.assertTrue(not proto.HasField(composite_field_name))
  143. self.assertEqual(0, getattr(composite_field, scalar_field_name))
  144. # Test simple, single-level nesting when we set a scalar.
  145. TestCompositeHasBits('optionalgroup', 'a')
  146. TestCompositeHasBits('optional_nested_message', 'bb')
  147. TestCompositeHasBits('optional_foreign_message', 'c')
  148. TestCompositeHasBits('optional_import_message', 'd')
  149. def testReferencesToNestedMessage(self):
  150. proto = unittest_pb2.TestAllTypes()
  151. nested = proto.optional_nested_message
  152. del proto
  153. # A previous version had a bug where this would raise an exception when
  154. # hitting a now-dead weak reference.
  155. nested.bb = 23
  156. def testDisconnectingNestedMessageBeforeSettingField(self):
  157. proto = unittest_pb2.TestAllTypes()
  158. nested = proto.optional_nested_message
  159. proto.ClearField('optional_nested_message') # Should disconnect from parent
  160. self.assertTrue(nested is not proto.optional_nested_message)
  161. nested.bb = 23
  162. self.assertTrue(not proto.HasField('optional_nested_message'))
  163. self.assertEqual(0, proto.optional_nested_message.bb)
  164. def testHasBitsWhenModifyingRepeatedFields(self):
  165. # Test nesting when we add an element to a repeated field in a submessage.
  166. proto = unittest_pb2.TestNestedMessageHasBits()
  167. proto.optional_nested_message.nestedmessage_repeated_int32.append(5)
  168. self.assertEqual(
  169. [5], proto.optional_nested_message.nestedmessage_repeated_int32)
  170. self.assertTrue(proto.HasField('optional_nested_message'))
  171. # Do the same test, but with a repeated composite field within the
  172. # submessage.
  173. proto.ClearField('optional_nested_message')
  174. self.assertTrue(not proto.HasField('optional_nested_message'))
  175. proto.optional_nested_message.nestedmessage_repeated_foreignmessage.add()
  176. self.assertTrue(proto.HasField('optional_nested_message'))
  177. def testHasBitsForManyLevelsOfNesting(self):
  178. # Test nesting many levels deep.
  179. recursive_proto = unittest_pb2.TestMutualRecursionA()
  180. self.assertTrue(not recursive_proto.HasField('bb'))
  181. self.assertEqual(0, recursive_proto.bb.a.bb.a.bb.optional_int32)
  182. self.assertTrue(not recursive_proto.HasField('bb'))
  183. recursive_proto.bb.a.bb.a.bb.optional_int32 = 5
  184. self.assertEqual(5, recursive_proto.bb.a.bb.a.bb.optional_int32)
  185. self.assertTrue(recursive_proto.HasField('bb'))
  186. self.assertTrue(recursive_proto.bb.HasField('a'))
  187. self.assertTrue(recursive_proto.bb.a.HasField('bb'))
  188. self.assertTrue(recursive_proto.bb.a.bb.HasField('a'))
  189. self.assertTrue(recursive_proto.bb.a.bb.a.HasField('bb'))
  190. self.assertTrue(not recursive_proto.bb.a.bb.a.bb.HasField('a'))
  191. self.assertTrue(recursive_proto.bb.a.bb.a.bb.HasField('optional_int32'))
  192. def testSingularListFields(self):
  193. proto = unittest_pb2.TestAllTypes()
  194. proto.optional_fixed32 = 1
  195. proto.optional_int32 = 5
  196. proto.optional_string = 'foo'
  197. self.assertEqual(
  198. [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 5),
  199. (proto.DESCRIPTOR.fields_by_name['optional_fixed32'], 1),
  200. (proto.DESCRIPTOR.fields_by_name['optional_string' ], 'foo') ],
  201. proto.ListFields())
  202. def testRepeatedListFields(self):
  203. proto = unittest_pb2.TestAllTypes()
  204. proto.repeated_fixed32.append(1)
  205. proto.repeated_int32.append(5)
  206. proto.repeated_int32.append(11)
  207. proto.repeated_string.append('foo')
  208. proto.repeated_string.append('bar')
  209. proto.repeated_string.append('baz')
  210. proto.optional_int32 = 21
  211. self.assertEqual(
  212. [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 21),
  213. (proto.DESCRIPTOR.fields_by_name['repeated_int32' ], [5, 11]),
  214. (proto.DESCRIPTOR.fields_by_name['repeated_fixed32'], [1]),
  215. (proto.DESCRIPTOR.fields_by_name['repeated_string' ],
  216. ['foo', 'bar', 'baz']) ],
  217. proto.ListFields())
  218. def testSingularListExtensions(self):
  219. proto = unittest_pb2.TestAllExtensions()
  220. proto.Extensions[unittest_pb2.optional_fixed32_extension] = 1
  221. proto.Extensions[unittest_pb2.optional_int32_extension ] = 5
  222. proto.Extensions[unittest_pb2.optional_string_extension ] = 'foo'
  223. self.assertEqual(
  224. [ (unittest_pb2.optional_int32_extension , 5),
  225. (unittest_pb2.optional_fixed32_extension, 1),
  226. (unittest_pb2.optional_string_extension , 'foo') ],
  227. proto.ListFields())
  228. def testRepeatedListExtensions(self):
  229. proto = unittest_pb2.TestAllExtensions()
  230. proto.Extensions[unittest_pb2.repeated_fixed32_extension].append(1)
  231. proto.Extensions[unittest_pb2.repeated_int32_extension ].append(5)
  232. proto.Extensions[unittest_pb2.repeated_int32_extension ].append(11)
  233. proto.Extensions[unittest_pb2.repeated_string_extension ].append('foo')
  234. proto.Extensions[unittest_pb2.repeated_string_extension ].append('bar')
  235. proto.Extensions[unittest_pb2.repeated_string_extension ].append('baz')
  236. proto.Extensions[unittest_pb2.optional_int32_extension ] = 21
  237. self.assertEqual(
  238. [ (unittest_pb2.optional_int32_extension , 21),
  239. (unittest_pb2.repeated_int32_extension , [5, 11]),
  240. (unittest_pb2.repeated_fixed32_extension, [1]),
  241. (unittest_pb2.repeated_string_extension , ['foo', 'bar', 'baz']) ],
  242. proto.ListFields())
  243. def testListFieldsAndExtensions(self):
  244. proto = unittest_pb2.TestFieldOrderings()
  245. test_util.SetAllFieldsAndExtensions(proto)
  246. unittest_pb2.my_extension_int
  247. self.assertEqual(
  248. [ (proto.DESCRIPTOR.fields_by_name['my_int' ], 1),
  249. (unittest_pb2.my_extension_int , 23),
  250. (proto.DESCRIPTOR.fields_by_name['my_string'], 'foo'),
  251. (unittest_pb2.my_extension_string , 'bar'),
  252. (proto.DESCRIPTOR.fields_by_name['my_float' ], 1.0) ],
  253. proto.ListFields())
  254. def testDefaultValues(self):
  255. proto = unittest_pb2.TestAllTypes()
  256. self.assertEqual(0, proto.optional_int32)
  257. self.assertEqual(0, proto.optional_int64)
  258. self.assertEqual(0, proto.optional_uint32)
  259. self.assertEqual(0, proto.optional_uint64)
  260. self.assertEqual(0, proto.optional_sint32)
  261. self.assertEqual(0, proto.optional_sint64)
  262. self.assertEqual(0, proto.optional_fixed32)
  263. self.assertEqual(0, proto.optional_fixed64)
  264. self.assertEqual(0, proto.optional_sfixed32)
  265. self.assertEqual(0, proto.optional_sfixed64)
  266. self.assertEqual(0.0, proto.optional_float)
  267. self.assertEqual(0.0, proto.optional_double)
  268. self.assertEqual(False, proto.optional_bool)
  269. self.assertEqual('', proto.optional_string)
  270. self.assertEqual('', proto.optional_bytes)
  271. self.assertEqual(41, proto.default_int32)
  272. self.assertEqual(42, proto.default_int64)
  273. self.assertEqual(43, proto.default_uint32)
  274. self.assertEqual(44, proto.default_uint64)
  275. self.assertEqual(-45, proto.default_sint32)
  276. self.assertEqual(46, proto.default_sint64)
  277. self.assertEqual(47, proto.default_fixed32)
  278. self.assertEqual(48, proto.default_fixed64)
  279. self.assertEqual(49, proto.default_sfixed32)
  280. self.assertEqual(-50, proto.default_sfixed64)
  281. self.assertEqual(51.5, proto.default_float)
  282. self.assertEqual(52e3, proto.default_double)
  283. self.assertEqual(True, proto.default_bool)
  284. self.assertEqual('hello', proto.default_string)
  285. self.assertEqual('world', proto.default_bytes)
  286. self.assertEqual(unittest_pb2.TestAllTypes.BAR, proto.default_nested_enum)
  287. self.assertEqual(unittest_pb2.FOREIGN_BAR, proto.default_foreign_enum)
  288. self.assertEqual(unittest_import_pb2.IMPORT_BAR,
  289. proto.default_import_enum)
  290. proto = unittest_pb2.TestExtremeDefaultValues()
  291. self.assertEqual(u'\u1234', proto.utf8_string)
  292. def testHasFieldWithUnknownFieldName(self):
  293. proto = unittest_pb2.TestAllTypes()
  294. self.assertRaises(ValueError, proto.HasField, 'nonexistent_field')
  295. def testClearFieldWithUnknownFieldName(self):
  296. proto = unittest_pb2.TestAllTypes()
  297. self.assertRaises(ValueError, proto.ClearField, 'nonexistent_field')
  298. def testDisallowedAssignments(self):
  299. # It's illegal to assign values directly to repeated fields
  300. # or to nonrepeated composite fields. Ensure that this fails.
  301. proto = unittest_pb2.TestAllTypes()
  302. # Repeated fields.
  303. self.assertRaises(AttributeError, setattr, proto, 'repeated_int32', 10)
  304. # Lists shouldn't work, either.
  305. self.assertRaises(AttributeError, setattr, proto, 'repeated_int32', [10])
  306. # Composite fields.
  307. self.assertRaises(AttributeError, setattr, proto,
  308. 'optional_nested_message', 23)
  309. # Assignment to a repeated nested message field without specifying
  310. # the index in the array of nested messages.
  311. self.assertRaises(AttributeError, setattr, proto.repeated_nested_message,
  312. 'bb', 34)
  313. # Assignment to an attribute of a repeated field.
  314. self.assertRaises(AttributeError, setattr, proto.repeated_float,
  315. 'some_attribute', 34)
  316. # proto.nonexistent_field = 23 should fail as well.
  317. self.assertRaises(AttributeError, setattr, proto, 'nonexistent_field', 23)
  318. # TODO(robinson): Add type-safety check for enums.
  319. def testSingleScalarTypeSafety(self):
  320. proto = unittest_pb2.TestAllTypes()
  321. self.assertRaises(TypeError, setattr, proto, 'optional_int32', 1.1)
  322. self.assertRaises(TypeError, setattr, proto, 'optional_int32', 'foo')
  323. self.assertRaises(TypeError, setattr, proto, 'optional_string', 10)
  324. self.assertRaises(TypeError, setattr, proto, 'optional_bytes', 10)
  325. def testSingleScalarBoundsChecking(self):
  326. def TestMinAndMaxIntegers(field_name, expected_min, expected_max):
  327. pb = unittest_pb2.TestAllTypes()
  328. setattr(pb, field_name, expected_min)
  329. setattr(pb, field_name, expected_max)
  330. self.assertRaises(ValueError, setattr, pb, field_name, expected_min - 1)
  331. self.assertRaises(ValueError, setattr, pb, field_name, expected_max + 1)
  332. TestMinAndMaxIntegers('optional_int32', -(1 << 31), (1 << 31) - 1)
  333. TestMinAndMaxIntegers('optional_uint32', 0, 0xffffffff)
  334. TestMinAndMaxIntegers('optional_int64', -(1 << 63), (1 << 63) - 1)
  335. TestMinAndMaxIntegers('optional_uint64', 0, 0xffffffffffffffff)
  336. TestMinAndMaxIntegers('optional_nested_enum', -(1 << 31), (1 << 31) - 1)
  337. def testRepeatedScalarTypeSafety(self):
  338. proto = unittest_pb2.TestAllTypes()
  339. self.assertRaises(TypeError, proto.repeated_int32.append, 1.1)
  340. self.assertRaises(TypeError, proto.repeated_int32.append, 'foo')
  341. self.assertRaises(TypeError, proto.repeated_string, 10)
  342. self.assertRaises(TypeError, proto.repeated_bytes, 10)
  343. proto.repeated_int32.append(10)
  344. proto.repeated_int32[0] = 23
  345. self.assertRaises(IndexError, proto.repeated_int32.__setitem__, 500, 23)
  346. self.assertRaises(TypeError, proto.repeated_int32.__setitem__, 0, 'abc')
  347. def testSingleScalarGettersAndSetters(self):
  348. proto = unittest_pb2.TestAllTypes()
  349. self.assertEqual(0, proto.optional_int32)
  350. proto.optional_int32 = 1
  351. self.assertEqual(1, proto.optional_int32)
  352. # TODO(robinson): Test all other scalar field types.
  353. def testSingleScalarClearField(self):
  354. proto = unittest_pb2.TestAllTypes()
  355. # Should be allowed to clear something that's not there (a no-op).
  356. proto.ClearField('optional_int32')
  357. proto.optional_int32 = 1
  358. self.assertTrue(proto.HasField('optional_int32'))
  359. proto.ClearField('optional_int32')
  360. self.assertEqual(0, proto.optional_int32)
  361. self.assertTrue(not proto.HasField('optional_int32'))
  362. # TODO(robinson): Test all other scalar field types.
  363. def testEnums(self):
  364. proto = unittest_pb2.TestAllTypes()
  365. self.assertEqual(1, proto.FOO)
  366. self.assertEqual(1, unittest_pb2.TestAllTypes.FOO)
  367. self.assertEqual(2, proto.BAR)
  368. self.assertEqual(2, unittest_pb2.TestAllTypes.BAR)
  369. self.assertEqual(3, proto.BAZ)
  370. self.assertEqual(3, unittest_pb2.TestAllTypes.BAZ)
  371. def testRepeatedScalars(self):
  372. proto = unittest_pb2.TestAllTypes()
  373. self.assertTrue(not proto.repeated_int32)
  374. self.assertEqual(0, len(proto.repeated_int32))
  375. proto.repeated_int32.append(5);
  376. proto.repeated_int32.append(10);
  377. self.assertTrue(proto.repeated_int32)
  378. self.assertEqual(2, len(proto.repeated_int32))
  379. self.assertEqual([5, 10], proto.repeated_int32)
  380. self.assertEqual(5, proto.repeated_int32[0])
  381. self.assertEqual(10, proto.repeated_int32[-1])
  382. # Test out-of-bounds indices.
  383. self.assertRaises(IndexError, proto.repeated_int32.__getitem__, 1234)
  384. self.assertRaises(IndexError, proto.repeated_int32.__getitem__, -1234)
  385. # Test incorrect types passed to __getitem__.
  386. self.assertRaises(TypeError, proto.repeated_int32.__getitem__, 'foo')
  387. self.assertRaises(TypeError, proto.repeated_int32.__getitem__, None)
  388. # Test that we can use the field as an iterator.
  389. result = []
  390. for i in proto.repeated_int32:
  391. result.append(i)
  392. self.assertEqual([5, 10], result)
  393. # Test clearing.
  394. proto.ClearField('repeated_int32')
  395. self.assertTrue(not proto.repeated_int32)
  396. self.assertEqual(0, len(proto.repeated_int32))
  397. def testRepeatedScalarsRemove(self):
  398. proto = unittest_pb2.TestAllTypes()
  399. self.assertTrue(not proto.repeated_int32)
  400. self.assertEqual(0, len(proto.repeated_int32))
  401. proto.repeated_int32.append(5)
  402. proto.repeated_int32.append(10)
  403. proto.repeated_int32.append(5)
  404. proto.repeated_int32.append(5)
  405. self.assertEqual(4, len(proto.repeated_int32))
  406. proto.repeated_int32.remove(5)
  407. self.assertEqual(3, len(proto.repeated_int32))
  408. self.assertEqual(10, proto.repeated_int32[0])
  409. self.assertEqual(5, proto.repeated_int32[1])
  410. self.assertEqual(5, proto.repeated_int32[2])
  411. proto.repeated_int32.remove(5)
  412. self.assertEqual(2, len(proto.repeated_int32))
  413. self.assertEqual(10, proto.repeated_int32[0])
  414. self.assertEqual(5, proto.repeated_int32[1])
  415. proto.repeated_int32.remove(10)
  416. self.assertEqual(1, len(proto.repeated_int32))
  417. self.assertEqual(5, proto.repeated_int32[0])
  418. # Remove a non-existent element.
  419. self.assertRaises(ValueError, proto.repeated_int32.remove, 123)
  420. def testRepeatedComposites(self):
  421. proto = unittest_pb2.TestAllTypes()
  422. self.assertTrue(not proto.repeated_nested_message)
  423. self.assertEqual(0, len(proto.repeated_nested_message))
  424. m0 = proto.repeated_nested_message.add()
  425. m1 = proto.repeated_nested_message.add()
  426. self.assertTrue(proto.repeated_nested_message)
  427. self.assertEqual(2, len(proto.repeated_nested_message))
  428. self.assertTrue(m0 is proto.repeated_nested_message[0])
  429. self.assertTrue(m1 is proto.repeated_nested_message[1])
  430. self.assertTrue(isinstance(m0, unittest_pb2.TestAllTypes.NestedMessage))
  431. # Test out-of-bounds indices.
  432. self.assertRaises(IndexError, proto.repeated_nested_message.__getitem__,
  433. 1234)
  434. self.assertRaises(IndexError, proto.repeated_nested_message.__getitem__,
  435. -1234)
  436. # Test incorrect types passed to __getitem__.
  437. self.assertRaises(TypeError, proto.repeated_nested_message.__getitem__,
  438. 'foo')
  439. self.assertRaises(TypeError, proto.repeated_nested_message.__getitem__,
  440. None)
  441. # Test that we can use the field as an iterator.
  442. result = []
  443. for i in proto.repeated_nested_message:
  444. result.append(i)
  445. self.assertEqual(2, len(result))
  446. self.assertTrue(m0 is result[0])
  447. self.assertTrue(m1 is result[1])
  448. # Test item deletion.
  449. del proto.repeated_nested_message[0]
  450. self.assertEqual(1, len(proto.repeated_nested_message))
  451. self.assertTrue(m1 is proto.repeated_nested_message[0])
  452. # Test clearing.
  453. proto.ClearField('repeated_nested_message')
  454. self.assertTrue(not proto.repeated_nested_message)
  455. self.assertEqual(0, len(proto.repeated_nested_message))
  456. def testHandWrittenReflection(self):
  457. # TODO(robinson): We probably need a better way to specify
  458. # protocol types by hand. But then again, this isn't something
  459. # we expect many people to do. Hmm.
  460. FieldDescriptor = descriptor.FieldDescriptor
  461. foo_field_descriptor = FieldDescriptor(
  462. name='foo_field', full_name='MyProto.foo_field',
  463. index=0, number=1, type=FieldDescriptor.TYPE_INT64,
  464. cpp_type=FieldDescriptor.CPPTYPE_INT64,
  465. label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
  466. containing_type=None, message_type=None, enum_type=None,
  467. is_extension=False, extension_scope=None,
  468. options=descriptor_pb2.FieldOptions())
  469. mydescriptor = descriptor.Descriptor(
  470. name='MyProto', full_name='MyProto', filename='ignored',
  471. containing_type=None, nested_types=[], enum_types=[],
  472. fields=[foo_field_descriptor], extensions=[],
  473. options=descriptor_pb2.MessageOptions())
  474. class MyProtoClass(message.Message):
  475. DESCRIPTOR = mydescriptor
  476. __metaclass__ = reflection.GeneratedProtocolMessageType
  477. myproto_instance = MyProtoClass()
  478. self.assertEqual(0, myproto_instance.foo_field)
  479. self.assertTrue(not myproto_instance.HasField('foo_field'))
  480. myproto_instance.foo_field = 23
  481. self.assertEqual(23, myproto_instance.foo_field)
  482. self.assertTrue(myproto_instance.HasField('foo_field'))
  483. def testTopLevelExtensionsForOptionalScalar(self):
  484. extendee_proto = unittest_pb2.TestAllExtensions()
  485. extension = unittest_pb2.optional_int32_extension
  486. self.assertTrue(not extendee_proto.HasExtension(extension))
  487. self.assertEqual(0, extendee_proto.Extensions[extension])
  488. # As with normal scalar fields, just doing a read doesn't actually set the
  489. # "has" bit.
  490. self.assertTrue(not extendee_proto.HasExtension(extension))
  491. # Actually set the thing.
  492. extendee_proto.Extensions[extension] = 23
  493. self.assertEqual(23, extendee_proto.Extensions[extension])
  494. self.assertTrue(extendee_proto.HasExtension(extension))
  495. # Ensure that clearing works as well.
  496. extendee_proto.ClearExtension(extension)
  497. self.assertEqual(0, extendee_proto.Extensions[extension])
  498. self.assertTrue(not extendee_proto.HasExtension(extension))
  499. def testTopLevelExtensionsForRepeatedScalar(self):
  500. extendee_proto = unittest_pb2.TestAllExtensions()
  501. extension = unittest_pb2.repeated_string_extension
  502. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  503. extendee_proto.Extensions[extension].append('foo')
  504. self.assertEqual(['foo'], extendee_proto.Extensions[extension])
  505. string_list = extendee_proto.Extensions[extension]
  506. extendee_proto.ClearExtension(extension)
  507. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  508. self.assertTrue(string_list is not extendee_proto.Extensions[extension])
  509. # Shouldn't be allowed to do Extensions[extension] = 'a'
  510. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  511. extension, 'a')
  512. def testTopLevelExtensionsForOptionalMessage(self):
  513. extendee_proto = unittest_pb2.TestAllExtensions()
  514. extension = unittest_pb2.optional_foreign_message_extension
  515. self.assertTrue(not extendee_proto.HasExtension(extension))
  516. self.assertEqual(0, extendee_proto.Extensions[extension].c)
  517. # As with normal (non-extension) fields, merely reading from the
  518. # thing shouldn't set the "has" bit.
  519. self.assertTrue(not extendee_proto.HasExtension(extension))
  520. extendee_proto.Extensions[extension].c = 23
  521. self.assertEqual(23, extendee_proto.Extensions[extension].c)
  522. self.assertTrue(extendee_proto.HasExtension(extension))
  523. # Save a reference here.
  524. foreign_message = extendee_proto.Extensions[extension]
  525. extendee_proto.ClearExtension(extension)
  526. self.assertTrue(foreign_message is not extendee_proto.Extensions[extension])
  527. # Setting a field on foreign_message now shouldn't set
  528. # any "has" bits on extendee_proto.
  529. foreign_message.c = 42
  530. self.assertEqual(42, foreign_message.c)
  531. self.assertTrue(foreign_message.HasField('c'))
  532. self.assertTrue(not extendee_proto.HasExtension(extension))
  533. # Shouldn't be allowed to do Extensions[extension] = 'a'
  534. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  535. extension, 'a')
  536. def testTopLevelExtensionsForRepeatedMessage(self):
  537. extendee_proto = unittest_pb2.TestAllExtensions()
  538. extension = unittest_pb2.repeatedgroup_extension
  539. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  540. group = extendee_proto.Extensions[extension].add()
  541. group.a = 23
  542. self.assertEqual(23, extendee_proto.Extensions[extension][0].a)
  543. group.a = 42
  544. self.assertEqual(42, extendee_proto.Extensions[extension][0].a)
  545. group_list = extendee_proto.Extensions[extension]
  546. extendee_proto.ClearExtension(extension)
  547. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  548. self.assertTrue(group_list is not extendee_proto.Extensions[extension])
  549. # Shouldn't be allowed to do Extensions[extension] = 'a'
  550. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  551. extension, 'a')
  552. def testNestedExtensions(self):
  553. extendee_proto = unittest_pb2.TestAllExtensions()
  554. extension = unittest_pb2.TestRequired.single
  555. # We just test the non-repeated case.
  556. self.assertTrue(not extendee_proto.HasExtension(extension))
  557. required = extendee_proto.Extensions[extension]
  558. self.assertEqual(0, required.a)
  559. self.assertTrue(not extendee_proto.HasExtension(extension))
  560. required.a = 23
  561. self.assertEqual(23, extendee_proto.Extensions[extension].a)
  562. self.assertTrue(extendee_proto.HasExtension(extension))
  563. extendee_proto.ClearExtension(extension)
  564. self.assertTrue(required is not extendee_proto.Extensions[extension])
  565. self.assertTrue(not extendee_proto.HasExtension(extension))
  566. # If message A directly contains message B, and
  567. # a.HasField('b') is currently False, then mutating any
  568. # extension in B should change a.HasField('b') to True
  569. # (and so on up the object tree).
  570. def testHasBitsForAncestorsOfExtendedMessage(self):
  571. # Optional scalar extension.
  572. toplevel = more_extensions_pb2.TopLevelMessage()
  573. self.assertTrue(not toplevel.HasField('submessage'))
  574. self.assertEqual(0, toplevel.submessage.Extensions[
  575. more_extensions_pb2.optional_int_extension])
  576. self.assertTrue(not toplevel.HasField('submessage'))
  577. toplevel.submessage.Extensions[
  578. more_extensions_pb2.optional_int_extension] = 23
  579. self.assertEqual(23, toplevel.submessage.Extensions[
  580. more_extensions_pb2.optional_int_extension])
  581. self.assertTrue(toplevel.HasField('submessage'))
  582. # Repeated scalar extension.
  583. toplevel = more_extensions_pb2.TopLevelMessage()
  584. self.assertTrue(not toplevel.HasField('submessage'))
  585. self.assertEqual([], toplevel.submessage.Extensions[
  586. more_extensions_pb2.repeated_int_extension])
  587. self.assertTrue(not toplevel.HasField('submessage'))
  588. toplevel.submessage.Extensions[
  589. more_extensions_pb2.repeated_int_extension].append(23)
  590. self.assertEqual([23], toplevel.submessage.Extensions[
  591. more_extensions_pb2.repeated_int_extension])
  592. self.assertTrue(toplevel.HasField('submessage'))
  593. # Optional message extension.
  594. toplevel = more_extensions_pb2.TopLevelMessage()
  595. self.assertTrue(not toplevel.HasField('submessage'))
  596. self.assertEqual(0, toplevel.submessage.Extensions[
  597. more_extensions_pb2.optional_message_extension].foreign_message_int)
  598. self.assertTrue(not toplevel.HasField('submessage'))
  599. toplevel.submessage.Extensions[
  600. more_extensions_pb2.optional_message_extension].foreign_message_int = 23
  601. self.assertEqual(23, toplevel.submessage.Extensions[
  602. more_extensions_pb2.optional_message_extension].foreign_message_int)
  603. self.assertTrue(toplevel.HasField('submessage'))
  604. # Repeated message extension.
  605. toplevel = more_extensions_pb2.TopLevelMessage()
  606. self.assertTrue(not toplevel.HasField('submessage'))
  607. self.assertEqual(0, len(toplevel.submessage.Extensions[
  608. more_extensions_pb2.repeated_message_extension]))
  609. self.assertTrue(not toplevel.HasField('submessage'))
  610. foreign = toplevel.submessage.Extensions[
  611. more_extensions_pb2.repeated_message_extension].add()
  612. self.assertTrue(foreign is toplevel.submessage.Extensions[
  613. more_extensions_pb2.repeated_message_extension][0])
  614. self.assertTrue(toplevel.HasField('submessage'))
  615. def testDisconnectionAfterClearingEmptyMessage(self):
  616. toplevel = more_extensions_pb2.TopLevelMessage()
  617. extendee_proto = toplevel.submessage
  618. extension = more_extensions_pb2.optional_message_extension
  619. extension_proto = extendee_proto.Extensions[extension]
  620. extendee_proto.ClearExtension(extension)
  621. extension_proto.foreign_message_int = 23
  622. self.assertTrue(not toplevel.HasField('submessage'))
  623. self.assertTrue(extension_proto is not extendee_proto.Extensions[extension])
  624. def testExtensionFailureModes(self):
  625. extendee_proto = unittest_pb2.TestAllExtensions()
  626. # Try non-extension-handle arguments to HasExtension,
  627. # ClearExtension(), and Extensions[]...
  628. self.assertRaises(KeyError, extendee_proto.HasExtension, 1234)
  629. self.assertRaises(KeyError, extendee_proto.ClearExtension, 1234)
  630. self.assertRaises(KeyError, extendee_proto.Extensions.__getitem__, 1234)
  631. self.assertRaises(KeyError, extendee_proto.Extensions.__setitem__, 1234, 5)
  632. # Try something that *is* an extension handle, just not for
  633. # this message...
  634. unknown_handle = more_extensions_pb2.optional_int_extension
  635. self.assertRaises(KeyError, extendee_proto.HasExtension,
  636. unknown_handle)
  637. self.assertRaises(KeyError, extendee_proto.ClearExtension,
  638. unknown_handle)
  639. self.assertRaises(KeyError, extendee_proto.Extensions.__getitem__,
  640. unknown_handle)
  641. self.assertRaises(KeyError, extendee_proto.Extensions.__setitem__,
  642. unknown_handle, 5)
  643. # Try call HasExtension() with a valid handle, but for a
  644. # *repeated* field. (Just as with non-extension repeated
  645. # fields, Has*() isn't supported for extension repeated fields).
  646. self.assertRaises(KeyError, extendee_proto.HasExtension,
  647. unittest_pb2.repeated_string_extension)
  648. def testMergeFromSingularField(self):
  649. # Test merge with just a singular field.
  650. proto1 = unittest_pb2.TestAllTypes()
  651. proto1.optional_int32 = 1
  652. proto2 = unittest_pb2.TestAllTypes()
  653. # This shouldn't get overwritten.
  654. proto2.optional_string = 'value'
  655. proto2.MergeFrom(proto1)
  656. self.assertEqual(1, proto2.optional_int32)
  657. self.assertEqual('value', proto2.optional_string)
  658. def testMergeFromRepeatedField(self):
  659. # Test merge with just a repeated field.
  660. proto1 = unittest_pb2.TestAllTypes()
  661. proto1.repeated_int32.append(1)
  662. proto1.repeated_int32.append(2)
  663. proto2 = unittest_pb2.TestAllTypes()
  664. proto2.repeated_int32.append(0)
  665. proto2.MergeFrom(proto1)
  666. self.assertEqual(0, proto2.repeated_int32[0])
  667. self.assertEqual(1, proto2.repeated_int32[1])
  668. self.assertEqual(2, proto2.repeated_int32[2])
  669. def testMergeFromOptionalGroup(self):
  670. # Test merge with an optional group.
  671. proto1 = unittest_pb2.TestAllTypes()
  672. proto1.optionalgroup.a = 12
  673. proto2 = unittest_pb2.TestAllTypes()
  674. proto2.MergeFrom(proto1)
  675. self.assertEqual(12, proto2.optionalgroup.a)
  676. def testMergeFromRepeatedNestedMessage(self):
  677. # Test merge with a repeated nested message.
  678. proto1 = unittest_pb2.TestAllTypes()
  679. m = proto1.repeated_nested_message.add()
  680. m.bb = 123
  681. m = proto1.repeated_nested_message.add()
  682. m.bb = 321
  683. proto2 = unittest_pb2.TestAllTypes()
  684. m = proto2.repeated_nested_message.add()
  685. m.bb = 999
  686. proto2.MergeFrom(proto1)
  687. self.assertEqual(999, proto2.repeated_nested_message[0].bb)
  688. self.assertEqual(123, proto2.repeated_nested_message[1].bb)
  689. self.assertEqual(321, proto2.repeated_nested_message[2].bb)
  690. def testMergeFromAllFields(self):
  691. # With all fields set.
  692. proto1 = unittest_pb2.TestAllTypes()
  693. test_util.SetAllFields(proto1)
  694. proto2 = unittest_pb2.TestAllTypes()
  695. proto2.MergeFrom(proto1)
  696. # Messages should be equal.
  697. self.assertEqual(proto2, proto1)
  698. # Serialized string should be equal too.
  699. string1 = proto1.SerializeToString()
  700. string2 = proto2.SerializeToString()
  701. self.assertEqual(string1, string2)
  702. def testMergeFromExtensionsSingular(self):
  703. proto1 = unittest_pb2.TestAllExtensions()
  704. proto1.Extensions[unittest_pb2.optional_int32_extension] = 1
  705. proto2 = unittest_pb2.TestAllExtensions()
  706. proto2.MergeFrom(proto1)
  707. self.assertEqual(
  708. 1, proto2.Extensions[unittest_pb2.optional_int32_extension])
  709. def testMergeFromExtensionsRepeated(self):
  710. proto1 = unittest_pb2.TestAllExtensions()
  711. proto1.Extensions[unittest_pb2.repeated_int32_extension].append(1)
  712. proto1.Extensions[unittest_pb2.repeated_int32_extension].append(2)
  713. proto2 = unittest_pb2.TestAllExtensions()
  714. proto2.Extensions[unittest_pb2.repeated_int32_extension].append(0)
  715. proto2.MergeFrom(proto1)
  716. self.assertEqual(
  717. 3, len(proto2.Extensions[unittest_pb2.repeated_int32_extension]))
  718. self.assertEqual(
  719. 0, proto2.Extensions[unittest_pb2.repeated_int32_extension][0])
  720. self.assertEqual(
  721. 1, proto2.Extensions[unittest_pb2.repeated_int32_extension][1])
  722. self.assertEqual(
  723. 2, proto2.Extensions[unittest_pb2.repeated_int32_extension][2])
  724. def testMergeFromExtensionsNestedMessage(self):
  725. proto1 = unittest_pb2.TestAllExtensions()
  726. ext1 = proto1.Extensions[
  727. unittest_pb2.repeated_nested_message_extension]
  728. m = ext1.add()
  729. m.bb = 222
  730. m = ext1.add()
  731. m.bb = 333
  732. proto2 = unittest_pb2.TestAllExtensions()
  733. ext2 = proto2.Extensions[
  734. unittest_pb2.repeated_nested_message_extension]
  735. m = ext2.add()
  736. m.bb = 111
  737. proto2.MergeFrom(proto1)
  738. ext2 = proto2.Extensions[
  739. unittest_pb2.repeated_nested_message_extension]
  740. self.assertEqual(3, len(ext2))
  741. self.assertEqual(111, ext2[0].bb)
  742. self.assertEqual(222, ext2[1].bb)
  743. self.assertEqual(333, ext2[2].bb)
  744. def testCopyFromSingularField(self):
  745. # Test copy with just a singular field.
  746. proto1 = unittest_pb2.TestAllTypes()
  747. proto1.optional_int32 = 1
  748. proto1.optional_string = 'important-text'
  749. proto2 = unittest_pb2.TestAllTypes()
  750. proto2.optional_string = 'value'
  751. proto2.CopyFrom(proto1)
  752. self.assertEqual(1, proto2.optional_int32)
  753. self.assertEqual('important-text', proto2.optional_string)
  754. def testCopyFromRepeatedField(self):
  755. # Test copy with a repeated field.
  756. proto1 = unittest_pb2.TestAllTypes()
  757. proto1.repeated_int32.append(1)
  758. proto1.repeated_int32.append(2)
  759. proto2 = unittest_pb2.TestAllTypes()
  760. proto2.repeated_int32.append(0)
  761. proto2.CopyFrom(proto1)
  762. self.assertEqual(1, proto2.repeated_int32[0])
  763. self.assertEqual(2, proto2.repeated_int32[1])
  764. def testCopyFromAllFields(self):
  765. # With all fields set.
  766. proto1 = unittest_pb2.TestAllTypes()
  767. test_util.SetAllFields(proto1)
  768. proto2 = unittest_pb2.TestAllTypes()
  769. proto2.CopyFrom(proto1)
  770. # Messages should be equal.
  771. self.assertEqual(proto2, proto1)
  772. # Serialized string should be equal too.
  773. string1 = proto1.SerializeToString()
  774. string2 = proto2.SerializeToString()
  775. self.assertEqual(string1, string2)
  776. def testCopyFromSelf(self):
  777. proto1 = unittest_pb2.TestAllTypes()
  778. proto1.repeated_int32.append(1)
  779. proto1.optional_int32 = 2
  780. proto1.optional_string = 'important-text'
  781. proto1.CopyFrom(proto1)
  782. self.assertEqual(1, proto1.repeated_int32[0])
  783. self.assertEqual(2, proto1.optional_int32)
  784. self.assertEqual('important-text', proto1.optional_string)
  785. def testClear(self):
  786. proto = unittest_pb2.TestAllTypes()
  787. test_util.SetAllFields(proto)
  788. # Clear the message.
  789. proto.Clear()
  790. self.assertEquals(proto.ByteSize(), 0)
  791. empty_proto = unittest_pb2.TestAllTypes()
  792. self.assertEquals(proto, empty_proto)
  793. # Test if extensions which were set are cleared.
  794. proto = unittest_pb2.TestAllExtensions()
  795. test_util.SetAllExtensions(proto)
  796. # Clear the message.
  797. proto.Clear()
  798. self.assertEquals(proto.ByteSize(), 0)
  799. empty_proto = unittest_pb2.TestAllExtensions()
  800. self.assertEquals(proto, empty_proto)
  801. def testIsInitialized(self):
  802. # Trivial cases - all optional fields and extensions.
  803. proto = unittest_pb2.TestAllTypes()
  804. self.assertTrue(proto.IsInitialized())
  805. proto = unittest_pb2.TestAllExtensions()
  806. self.assertTrue(proto.IsInitialized())
  807. # The case of uninitialized required fields.
  808. proto = unittest_pb2.TestRequired()
  809. self.assertFalse(proto.IsInitialized())
  810. proto.a = proto.b = proto.c = 2
  811. self.assertTrue(proto.IsInitialized())
  812. # The case of uninitialized submessage.
  813. proto = unittest_pb2.TestRequiredForeign()
  814. self.assertTrue(proto.IsInitialized())
  815. proto.optional_message.a = 1
  816. self.assertFalse(proto.IsInitialized())
  817. proto.optional_message.b = 0
  818. proto.optional_message.c = 0
  819. self.assertTrue(proto.IsInitialized())
  820. # Uninitialized repeated submessage.
  821. message1 = proto.repeated_message.add()
  822. self.assertFalse(proto.IsInitialized())
  823. message1.a = message1.b = message1.c = 0
  824. self.assertTrue(proto.IsInitialized())
  825. # Uninitialized repeated group in an extension.
  826. proto = unittest_pb2.TestAllExtensions()
  827. extension = unittest_pb2.TestRequired.multi
  828. message1 = proto.Extensions[extension].add()
  829. message2 = proto.Extensions[extension].add()
  830. self.assertFalse(proto.IsInitialized())
  831. message1.a = 1
  832. message1.b = 1
  833. message1.c = 1
  834. self.assertFalse(proto.IsInitialized())
  835. message2.a = 2
  836. message2.b = 2
  837. message2.c = 2
  838. self.assertTrue(proto.IsInitialized())
  839. # Uninitialized nonrepeated message in an extension.
  840. proto = unittest_pb2.TestAllExtensions()
  841. extension = unittest_pb2.TestRequired.single
  842. proto.Extensions[extension].a = 1
  843. self.assertFalse(proto.IsInitialized())
  844. proto.Extensions[extension].b = 2
  845. proto.Extensions[extension].c = 3
  846. self.assertTrue(proto.IsInitialized())
  847. def testStringUTF8Encoding(self):
  848. proto = unittest_pb2.TestAllTypes()
  849. # Assignment of a unicode object to a field of type 'bytes' is not allowed.
  850. self.assertRaises(TypeError,
  851. setattr, proto, 'optional_bytes', u'unicode object')
  852. # Check that the default value is of python's 'unicode' type.
  853. self.assertEqual(type(proto.optional_string), unicode)
  854. proto.optional_string = unicode('Testing')
  855. self.assertEqual(proto.optional_string, str('Testing'))
  856. # Assign a value of type 'str' which can be encoded in UTF-8.
  857. proto.optional_string = str('Testing')
  858. self.assertEqual(proto.optional_string, unicode('Testing'))
  859. # Values of type 'str' are also accepted as long as they can be encoded in
  860. # UTF-8.
  861. self.assertEqual(type(proto.optional_string), str)
  862. # Try to assign a 'str' value which contains bytes that aren't 7-bit ASCII.
  863. self.assertRaises(ValueError,
  864. setattr, proto, 'optional_string', str('a\x80a'))
  865. # Assign a 'str' object which contains a UTF-8 encoded string.
  866. self.assertRaises(ValueError,
  867. setattr, proto, 'optional_string', 'Тест')
  868. # No exception thrown.
  869. proto.optional_string = 'abc'
  870. def testStringUTF8Serialization(self):
  871. proto = unittest_mset_pb2.TestMessageSet()
  872. extension_message = unittest_mset_pb2.TestMessageSetExtension2
  873. extension = extension_message.message_set_extension
  874. test_utf8 = u'Тест'
  875. test_utf8_bytes = test_utf8.encode('utf-8')
  876. # 'Test' in another language, using UTF-8 charset.
  877. proto.Extensions[extension].str = test_utf8
  878. # Serialize using the MessageSet wire format (this is specified in the
  879. # .proto file).
  880. serialized = proto.SerializeToString()
  881. # Check byte size.
  882. self.assertEqual(proto.ByteSize(), len(serialized))
  883. raw = unittest_mset_pb2.RawMessageSet()
  884. raw.MergeFromString(serialized)
  885. message2 = unittest_mset_pb2.TestMessageSetExtension2()
  886. self.assertEqual(1, len(raw.item))
  887. # Check that the type_id is the same as the tag ID in the .proto file.
  888. self.assertEqual(raw.item[0].type_id, 1547769)
  889. # Check the actually bytes on the wire.
  890. self.assertTrue(
  891. raw.item[0].message.endswith(test_utf8_bytes))
  892. message2.MergeFromString(raw.item[0].message)
  893. self.assertEqual(type(message2.str), unicode)
  894. self.assertEqual(message2.str, test_utf8)
  895. # How about if the bytes on the wire aren't a valid UTF-8 encoded string.
  896. bytes = raw.item[0].message.replace(
  897. test_utf8_bytes, len(test_utf8_bytes) * '\xff')
  898. self.assertRaises(UnicodeDecodeError, message2.MergeFromString, bytes)
  899. # Since we had so many tests for protocol buffer equality, we broke these out
  900. # into separate TestCase classes.
  901. class TestAllTypesEqualityTest(unittest.TestCase):
  902. def setUp(self):
  903. self.first_proto = unittest_pb2.TestAllTypes()
  904. self.second_proto = unittest_pb2.TestAllTypes()
  905. def testSelfEquality(self):
  906. self.assertEqual(self.first_proto, self.first_proto)
  907. def testEmptyProtosEqual(self):
  908. self.assertEqual(self.first_proto, self.second_proto)
  909. class FullProtosEqualityTest(unittest.TestCase):
  910. """Equality tests using completely-full protos as a starting point."""
  911. def setUp(self):
  912. self.first_proto = unittest_pb2.TestAllTypes()
  913. self.second_proto = unittest_pb2.TestAllTypes()
  914. test_util.SetAllFields(self.first_proto)
  915. test_util.SetAllFields(self.second_proto)
  916. def testAllFieldsFilledEquality(self):
  917. self.assertEqual(self.first_proto, self.second_proto)
  918. def testNonRepeatedScalar(self):
  919. # Nonrepeated scalar field change should cause inequality.
  920. self.first_proto.optional_int32 += 1
  921. self.assertNotEqual(self.first_proto, self.second_proto)
  922. # ...as should clearing a field.
  923. self.first_proto.ClearField('optional_int32')
  924. self.assertNotEqual(self.first_proto, self.second_proto)
  925. def testNonRepeatedComposite(self):
  926. # Change a nonrepeated composite field.
  927. self.first_proto.optional_nested_message.bb += 1
  928. self.assertNotEqual(self.first_proto, self.second_proto)
  929. self.first_proto.optional_nested_message.bb -= 1
  930. self.assertEqual(self.first_proto, self.second_proto)
  931. # Clear a field in the nested message.
  932. self.first_proto.optional_nested_message.ClearField('bb')
  933. self.assertNotEqual(self.first_proto, self.second_proto)
  934. self.first_proto.optional_nested_message.bb = (
  935. self.second_proto.optional_nested_message.bb)
  936. self.assertEqual(self.first_proto, self.second_proto)
  937. # Remove the nested message entirely.
  938. self.first_proto.ClearField('optional_nested_message')
  939. self.assertNotEqual(self.first_proto, self.second_proto)
  940. def testRepeatedScalar(self):
  941. # Change a repeated scalar field.
  942. self.first_proto.repeated_int32.append(5)
  943. self.assertNotEqual(self.first_proto, self.second_proto)
  944. self.first_proto.ClearField('repeated_int32')
  945. self.assertNotEqual(self.first_proto, self.second_proto)
  946. def testRepeatedComposite(self):
  947. # Change value within a repeated composite field.
  948. self.first_proto.repeated_nested_message[0].bb += 1
  949. self.assertNotEqual(self.first_proto, self.second_proto)
  950. self.first_proto.repeated_nested_message[0].bb -= 1
  951. self.assertEqual(self.first_proto, self.second_proto)
  952. # Add a value to a repeated composite field.
  953. self.first_proto.repeated_nested_message.add()
  954. self.assertNotEqual(self.first_proto, self.second_proto)
  955. self.second_proto.repeated_nested_message.add()
  956. self.assertEqual(self.first_proto, self.second_proto)
  957. def testNonRepeatedScalarHasBits(self):
  958. # Ensure that we test "has" bits as well as value for
  959. # nonrepeated scalar field.
  960. self.first_proto.ClearField('optional_int32')
  961. self.second_proto.optional_int32 = 0
  962. self.assertNotEqual(self.first_proto, self.second_proto)
  963. def testNonRepeatedCompositeHasBits(self):
  964. # Ensure that we test "has" bits as well as value for
  965. # nonrepeated composite field.
  966. self.first_proto.ClearField('optional_nested_message')
  967. self.second_proto.optional_nested_message.ClearField('bb')
  968. self.assertNotEqual(self.first_proto, self.second_proto)
  969. # TODO(robinson): Replace next two lines with method
  970. # to set the "has" bit without changing the value,
  971. # if/when such a method exists.
  972. self.first_proto.optional_nested_message.bb = 0
  973. self.first_proto.optional_nested_message.ClearField('bb')
  974. self.assertEqual(self.first_proto, self.second_proto)
  975. class ExtensionEqualityTest(unittest.TestCase):
  976. def testExtensionEquality(self):
  977. first_proto = unittest_pb2.TestAllExtensions()
  978. second_proto = unittest_pb2.TestAllExtensions()
  979. self.assertEqual(first_proto, second_proto)
  980. test_util.SetAllExtensions(first_proto)
  981. self.assertNotEqual(first_proto, second_proto)
  982. test_util.SetAllExtensions(second_proto)
  983. self.assertEqual(first_proto, second_proto)
  984. # Ensure that we check value equality.
  985. first_proto.Extensions[unittest_pb2.optional_int32_extension] += 1
  986. self.assertNotEqual(first_proto, second_proto)
  987. first_proto.Extensions[unittest_pb2.optional_int32_extension] -= 1
  988. self.assertEqual(first_proto, second_proto)
  989. # Ensure that we also look at "has" bits.
  990. first_proto.ClearExtension(unittest_pb2.optional_int32_extension)
  991. second_proto.Extensions[unittest_pb2.optional_int32_extension] = 0
  992. self.assertNotEqual(first_proto, second_proto)
  993. first_proto.Extensions[unittest_pb2.optional_int32_extension] = 0
  994. self.assertEqual(first_proto, second_proto)
  995. # Ensure that differences in cached values
  996. # don't matter if "has" bits are both false.
  997. first_proto = unittest_pb2.TestAllExtensions()
  998. second_proto = unittest_pb2.TestAllExtensions()
  999. self.assertEqual(
  1000. 0, first_proto.Extensions[unittest_pb2.optional_int32_extension])
  1001. self.assertEqual(first_proto, second_proto)
  1002. class MutualRecursionEqualityTest(unittest.TestCase):
  1003. def testEqualityWithMutualRecursion(self):
  1004. first_proto = unittest_pb2.TestMutualRecursionA()
  1005. second_proto = unittest_pb2.TestMutualRecursionA()
  1006. self.assertEqual(first_proto, second_proto)
  1007. first_proto.bb.a.bb.optional_int32 = 23
  1008. self.assertNotEqual(first_proto, second_proto)
  1009. second_proto.bb.a.bb.optional_int32 = 23
  1010. self.assertEqual(first_proto, second_proto)
  1011. class ByteSizeTest(unittest.TestCase):
  1012. def setUp(self):
  1013. self.proto = unittest_pb2.TestAllTypes()
  1014. self.extended_proto = more_extensions_pb2.ExtendedMessage()
  1015. def Size(self):
  1016. return self.proto.ByteSize()
  1017. def testEmptyMessage(self):
  1018. self.assertEqual(0, self.proto.ByteSize())
  1019. def testVarints(self):
  1020. def Test(i, expected_varint_size):
  1021. self.proto.Clear()
  1022. self.proto.optional_int64 = i
  1023. # Add one to the varint size for the tag info
  1024. # for tag 1.
  1025. self.assertEqual(expected_varint_size + 1, self.Size())
  1026. Test(0, 1)
  1027. Test(1, 1)
  1028. for i, num_bytes in zip(range(7, 63, 7), range(1, 10000)):
  1029. Test((1 << i) - 1, num_bytes)
  1030. Test(-1, 10)
  1031. Test(-2, 10)
  1032. Test(-(1 << 63), 10)
  1033. def testStrings(self):
  1034. self.proto.optional_string = ''
  1035. # Need one byte for tag info (tag #14), and one byte for length.
  1036. self.assertEqual(2, self.Size())
  1037. self.proto.optional_string = 'abc'
  1038. # Need one byte for tag info (tag #14), and one byte for length.
  1039. self.assertEqual(2 + len(self.proto.optional_string), self.Size())
  1040. self.proto.optional_string = 'x' * 128
  1041. # Need one byte for tag info (tag #14), and TWO bytes for length.
  1042. self.assertEqual(3 + len(self.proto.optional_string), self.Size())
  1043. def testOtherNumerics(self):
  1044. self.proto.optional_fixed32 = 1234
  1045. # One byte for tag and 4 bytes for fixed32.
  1046. self.assertEqual(5, self.Size())
  1047. self.proto = unittest_pb2.TestAllTypes()
  1048. self.proto.optional_fixed64 = 1234
  1049. # One byte for tag and 8 bytes for fixed64.
  1050. self.assertEqual(9, self.Size())
  1051. self.proto = unittest_pb2.TestAllTypes()
  1052. self.proto.optional_float = 1.234
  1053. # One byte for tag and 4 bytes for float.
  1054. self.assertEqual(5, self.Size())
  1055. self.proto = unittest_pb2.TestAllTypes()
  1056. self.proto.optional_double = 1.234
  1057. # One byte for tag and 8 bytes for float.
  1058. self.assertEqual(9, self.Size())
  1059. self.proto = unittest_pb2.TestAllTypes()
  1060. self.proto.optional_sint32 = 64
  1061. # One byte for tag and 2 bytes for zig-zag-encoded 64.
  1062. self.assertEqual(3, self.Size())
  1063. self.proto = unittest_pb2.TestAllTypes()
  1064. def testComposites(self):
  1065. # 3 bytes.
  1066. self.proto.optional_nested_message.bb = (1 << 14)
  1067. # Plus one byte for bb tag.
  1068. # Plus 1 byte for optional_nested_message serialized size.
  1069. # Plus two bytes for optional_nested_message tag.
  1070. self.assertEqual(3 + 1 + 1 + 2, self.Size())
  1071. def testGroups(self):
  1072. # 4 bytes.
  1073. self.proto.optionalgroup.a = (1 << 21)
  1074. # Plus two bytes for |a| tag.
  1075. # Plus 2 * two bytes for START_GROUP and END_GROUP tags.
  1076. self.assertEqual(4 + 2 + 2*2, self.Size())
  1077. def testRepeatedScalars(self):
  1078. self.proto.repeated_int32.append(10) # 1 byte.
  1079. self.proto.repeated_int32.append(128) # 2 bytes.
  1080. # Also need 2 bytes for each entry for tag.
  1081. self.assertEqual(1 + 2 + 2*2, self.Size())
  1082. def testRepeatedScalarsRemove(self):
  1083. self.proto.repeated_int32.append(10) # 1 byte.
  1084. self.proto.repeated_int32.append(128) # 2 bytes.
  1085. # Also need 2 bytes for each entry for tag.
  1086. self.assertEqual(1 + 2 + 2*2, self.Size())
  1087. self.proto.repeated_int32.remove(128)
  1088. self.assertEqual(1 + 2, self.Size())
  1089. def testRepeatedComposites(self):
  1090. # Empty message. 2 bytes tag plus 1 byte length.
  1091. foreign_message_0 = self.proto.repeated_nested_message.add()
  1092. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1093. foreign_message_1 = self.proto.repeated_nested_message.add()
  1094. foreign_message_1.bb = 7
  1095. self.assertEqual(2 + 1 + 2 + 1 + 1 + 1, self.Size())
  1096. def testRepeatedCompositesDelete(self):
  1097. # Empty message. 2 bytes tag plus 1 byte length.
  1098. foreign_message_0 = self.proto.repeated_nested_message.add()
  1099. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1100. foreign_message_1 = self.proto.repeated_nested_message.add()
  1101. foreign_message_1.bb = 9
  1102. self.assertEqual(2 + 1 + 2 + 1 + 1 + 1, self.Size())
  1103. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1104. del self.proto.repeated_nested_message[0]
  1105. self.assertEqual(2 + 1 + 1 + 1, self.Size())
  1106. # Now add a new message.
  1107. foreign_message_2 = self.proto.repeated_nested_message.add()
  1108. foreign_message_2.bb = 12
  1109. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1110. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1111. self.assertEqual(2 + 1 + 1 + 1 + 2 + 1 + 1 + 1, self.Size())
  1112. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1113. del self.proto.repeated_nested_message[1]
  1114. self.assertEqual(2 + 1 + 1 + 1, self.Size())
  1115. del self.proto.repeated_nested_message[0]
  1116. self.assertEqual(0, self.Size())
  1117. def testRepeatedGroups(self):
  1118. # 2-byte START_GROUP plus 2-byte END_GROUP.
  1119. group_0 = self.proto.repeatedgroup.add()
  1120. # 2-byte START_GROUP plus 2-byte |a| tag + 1-byte |a|
  1121. # plus 2-byte END_GROUP.
  1122. group_1 = self.proto.repeatedgroup.add()
  1123. group_1.a = 7
  1124. self.assertEqual(2 + 2 + 2 + 2 + 1 + 2, self.Size())
  1125. def testExtensions(self):
  1126. proto = unittest_pb2.TestAllExtensions()
  1127. self.assertEqual(0, proto.ByteSize())
  1128. extension = unittest_pb2.optional_int32_extension # Field #1, 1 byte.
  1129. proto.Extensions[extension] = 23
  1130. # 1 byte for tag, 1 byte for value.
  1131. self.assertEqual(2, proto.ByteSize())
  1132. def testCacheInvalidationForNonrepeatedScalar(self):
  1133. # Test non-extension.
  1134. self.proto.optional_int32 = 1
  1135. self.assertEqual(2, self.proto.ByteSize())
  1136. self.proto.optional_int32 = 128
  1137. self.assertEqual(3, self.proto.ByteSize())
  1138. self.proto.ClearField('optional_int32')
  1139. self.assertEqual(0, self.proto.ByteSize())
  1140. # Test within extension.
  1141. extension = more_extensions_pb2.optional_int_extension
  1142. self.extended_proto.Extensions[extension] = 1
  1143. self.assertEqual(2, self.extended_proto.ByteSize())
  1144. self.extended_proto.Extensions[extension] = 128
  1145. self.assertEqual(3, self.extended_proto.ByteSize())
  1146. self.extended_proto.ClearExtension(extension)
  1147. self.assertEqual(0, self.extended_proto.ByteSize())
  1148. def testCacheInvalidationForRepeatedScalar(self):
  1149. # Test non-extension.
  1150. self.proto.repeated_int32.append(1)
  1151. self.assertEqual(3, self.proto.ByteSize())
  1152. self.proto.repeated_int32.append(1)
  1153. self.assertEqual(6, self.proto.ByteSize())
  1154. self.proto.repeated_int32[1] = 128
  1155. self.assertEqual(7, self.proto.ByteSize())
  1156. self.proto.ClearField('repeated_int32')
  1157. self.assertEqual(0, self.proto.ByteSize())
  1158. # Test within extension.
  1159. extension = more_extensions_pb2.repeated_int_extension
  1160. repeated = self.extended_proto.Extensions[extension]
  1161. repeated.append(1)
  1162. self.assertEqual(2, self.extended_proto.ByteSize())
  1163. repeated.append(1)
  1164. self.assertEqual(4, self.extended_proto.ByteSize())
  1165. repeated[1] = 128
  1166. self.assertEqual(5, self.extended_proto.ByteSize())
  1167. self.extended_proto.ClearExtension(extension)
  1168. self.assertEqual(0, self.extended_proto.ByteSize())
  1169. def testCacheInvalidationForNonrepeatedMessage(self):
  1170. # Test non-extension.
  1171. self.proto.optional_foreign_message.c = 1
  1172. self.assertEqual(5, self.proto.ByteSize())
  1173. self.proto.optional_foreign_message.c = 128
  1174. self.assertEqual(6, self.proto.ByteSize())
  1175. self.proto.optional_foreign_message.ClearField('c')
  1176. self.assertEqual(3, self.proto.ByteSize())
  1177. self.proto.ClearField('optional_foreign_message')
  1178. self.assertEqual(0, self.proto.ByteSize())
  1179. child = self.proto.optional_foreign_message
  1180. self.proto.ClearField('optional_foreign_message')
  1181. child.c = 128
  1182. self.assertEqual(0, self.proto.ByteSize())
  1183. # Test within extension.
  1184. extension = more_extensions_pb2.optional_message_extension
  1185. child = self.extended_proto.Extensions[extension]
  1186. self.assertEqual(0, self.extended_proto.ByteSize())
  1187. child.foreign_message_int = 1
  1188. self.assertEqual(4, self.extended_proto.ByteSize())
  1189. child.foreign_message_int = 128
  1190. self.assertEqual(5, self.extended_proto.ByteSize())
  1191. self.extended_proto.ClearExtension(extension)
  1192. self.assertEqual(0, self.extended_proto.ByteSize())
  1193. def testCacheInvalidationForRepeatedMessage(self):
  1194. # Test non-extension.
  1195. child0 = self.proto.repeated_foreign_message.add()
  1196. self.assertEqual(3, self.proto.ByteSize())
  1197. self.proto.repeated_foreign_message.add()
  1198. self.assertEqual(6, self.proto.ByteSize())
  1199. child0.c = 1
  1200. self.assertEqual(8, self.proto.ByteSize())
  1201. self.proto.ClearField('repeated_foreign_message')
  1202. self.assertEqual(0, self.proto.ByteSize())
  1203. # Test within extension.
  1204. extension = more_extensions_pb2.repeated_message_extension
  1205. child_list = self.extended_proto.Extensions[extension]
  1206. child0 = child_list.add()
  1207. self.assertEqual(2, self.extended_proto.ByteSize())
  1208. child_list.add()
  1209. self.assertEqual(4, self.extended_proto.ByteSize())
  1210. child0.foreign_message_int = 1
  1211. self.assertEqual(6, self.extended_proto.ByteSize())
  1212. child0.ClearField('foreign_message_int')
  1213. self.assertEqual(4, self.extended_proto.ByteSize())
  1214. self.extended_proto.ClearExtension(extension)
  1215. self.assertEqual(0, self.extended_proto.ByteSize())
  1216. # TODO(robinson): We need cross-language serialization consistency tests.
  1217. # Issues to be sure to cover include:
  1218. # * Handling of unrecognized tags ("uninterpreted_bytes").
  1219. # * Handling of MessageSets.
  1220. # * Consistent ordering of tags in the wire format,
  1221. # including ordering between extensions and non-extension
  1222. # fields.
  1223. # * Consistent serialization of negative numbers, especially
  1224. # negative int32s.
  1225. # * Handling of empty submessages (with and without "has"
  1226. # bits set).
  1227. class SerializationTest(unittest.TestCase):
  1228. def testSerializeEmtpyMessage(self):
  1229. first_proto = unittest_pb2.TestAllTypes()
  1230. second_proto = unittest_pb2.TestAllTypes()
  1231. serialized = first_proto.SerializeToString()
  1232. self.assertEqual(first_proto.ByteSize(), len(serialized))
  1233. second_proto.MergeFromString(serialized)
  1234. self.assertEqual(first_proto, second_proto)
  1235. def testSerializeAllFields(self):
  1236. first_proto = unittest_pb2.TestAllTypes()
  1237. second_proto = unittest_pb2.TestAllTypes()
  1238. test_util.SetAllFields(first_proto)
  1239. serialized = first_proto.SerializeToString()
  1240. self.assertEqual(first_proto.ByteSize(), len(serialized))
  1241. second_proto.MergeFromString(serialized)
  1242. self.assertEqual(first_proto, second_proto)
  1243. def testSerializeAllExtensions(self):
  1244. first_proto = unittest_pb2.TestAllExtensions()
  1245. second_proto = unittest_pb2.TestAllExtensions()
  1246. test_util.SetAllExtensions(first_proto)
  1247. serialized = first_proto.SerializeToString()
  1248. second_proto.MergeFromString(serialized)
  1249. self.assertEqual(first_proto, second_proto)
  1250. def testCanonicalSerializationOrder(self):
  1251. proto = more_messages_pb2.OutOfOrderFields()
  1252. # These are also their tag numbers. Even though we're setting these in
  1253. # reverse-tag order AND they're listed in reverse tag-order in the .proto
  1254. # file, they should nonetheless be serialized in tag order.
  1255. proto.optional_sint32 = 5
  1256. proto.Extensions[more_messages_pb2.optional_uint64] = 4
  1257. proto.optional_uint32 = 3
  1258. proto.Extensions[more_messages_pb2.optional_int64] = 2
  1259. proto.optional_int32 = 1
  1260. serialized = proto.SerializeToString()
  1261. self.assertEqual(proto.ByteSize(), len(serialized))
  1262. d = decoder.Decoder(serialized)
  1263. ReadTag = d.ReadFieldNumberAndWireType
  1264. self.assertEqual((1, wire_format.WIRETYPE_VARINT), ReadTag())
  1265. self.assertEqual(1, d.ReadInt32())
  1266. self.assertEqual((2, wire_format.WIRETYPE_VARINT), ReadTag())
  1267. self.assertEqual(2, d.ReadInt64())
  1268. self.assertEqual((3, wire_format.WIRETYPE_VARINT), ReadTag())
  1269. self.assertEqual(3, d.ReadUInt32())
  1270. self.assertEqual((4, wire_format.WIRETYPE_VARINT), ReadTag())
  1271. self.assertEqual(4, d.ReadUInt64())
  1272. self.assertEqual((5, wire_format.WIRETYPE_VARINT), ReadTag())
  1273. self.assertEqual(5, d.ReadSInt32())
  1274. def testCanonicalSerializationOrderSameAsCpp(self):
  1275. # Copy of the same test we use for C++.
  1276. proto = unittest_pb2.TestFieldOrderings()
  1277. test_util.SetAllFieldsAndExtensions(proto)
  1278. serialized = proto.SerializeToString()
  1279. test_util.ExpectAllFieldsAndExtensionsInOrder(serialized)
  1280. def testMergeFromStringWhenFieldsAlreadySet(self):
  1281. first_proto = unittest_pb2.TestAllTypes()
  1282. first_proto.repeated_string.append('foobar')
  1283. first_proto.optional_int32 = 23
  1284. first_proto.optional_nested_message.bb = 42
  1285. serialized = first_proto.SerializeToString()
  1286. second_proto = unittest_pb2.TestAllTypes()
  1287. second_proto.repeated_string.append('baz')
  1288. second_proto.optional_int32 = 100
  1289. second_proto.optional_nested_message.bb = 999
  1290. second_proto.MergeFromString(serialized)
  1291. # Ensure that we append to repeated fields.
  1292. self.assertEqual(['baz', 'foobar'], list(second_proto.repeated_string))
  1293. # Ensure that we overwrite nonrepeatd scalars.
  1294. self.assertEqual(23, second_proto.optional_int32)
  1295. # Ensure that we recursively call MergeFromString() on
  1296. # submessages.
  1297. self.assertEqual(42, second_proto.optional_nested_message.bb)
  1298. def testMessageSetWireFormat(self):
  1299. proto = unittest_mset_pb2.TestMessageSet()
  1300. extension_message1 = unittest_mset_pb2.TestMessageSetExtension1
  1301. extension_message2 = unittest_mset_pb2.TestMessageSetExtension2
  1302. extension1 = extension_message1.message_set_extension
  1303. extension2 = extension_message2.message_set_extension
  1304. proto.Extensions[extension1].i = 123
  1305. proto.Extensions[extension2].str = 'foo'
  1306. # Serialize using the MessageSet wire format (this is specified in the
  1307. # .proto file).
  1308. serialized = proto.SerializeToString()
  1309. raw = unittest_mset_pb2.RawMessageSet()
  1310. self.assertEqual(False,
  1311. raw.DESCRIPTOR.GetOptions().message_set_wire_format)
  1312. raw.MergeFromString(serialized)
  1313. self.assertEqual(2, len(raw.item))
  1314. message1 = unittest_mset_pb2.TestMessageSetExtension1()
  1315. message1.MergeFromString(raw.item[0].message)
  1316. self.assertEqual(123, message1.i)
  1317. message2 = unittest_mset_pb2.TestMessageSetExtension2()
  1318. message2.MergeFromString(raw.item[1].message)
  1319. self.assertEqual('foo', message2.str)
  1320. # Deserialize using the MessageSet wire format.
  1321. proto2 = unittest_mset_pb2.TestMessageSet()
  1322. proto2.MergeFromString(serialized)
  1323. self.assertEqual(123, proto2.Extensions[extension1].i)
  1324. self.assertEqual('foo', proto2.Extensions[extension2].str)
  1325. # Check byte size.
  1326. self.assertEqual(proto2.ByteSize(), len(serialized))
  1327. self.assertEqual(proto.ByteSize(), len(serialized))
  1328. def testMessageSetWireFormatUnknownExtension(self):
  1329. # Create a message using the message set wire format with an unknown
  1330. # message.
  1331. raw = unittest_mset_pb2.RawMessageSet()
  1332. # Add an item.
  1333. item = raw.item.add()
  1334. item.type_id = 1545008
  1335. extension_message1 = unittest_mset_pb2.TestMessageSetExtension1
  1336. message1 = unittest_mset_pb2.TestMessageSetExtension1()
  1337. message1.i = 12345
  1338. item.message = message1.SerializeToString()
  1339. # Add a second, unknown extension.
  1340. item = raw.item.add()
  1341. item.type_id = 1545009
  1342. extension_message1 = unittest_mset_pb2.TestMessageSetExtension1
  1343. message1 = unittest_mset_pb2.TestMessageSetExtension1()
  1344. message1.i = 12346
  1345. item.message = message1.SerializeToString()
  1346. # Add another unknown extension.
  1347. item = raw.item.add()
  1348. item.type_id = 1545010
  1349. message1 = unittest_mset_pb2.TestMessageSetExtension2()
  1350. message1.str = 'foo'
  1351. item.message = message1.SerializeToString()
  1352. serialized = raw.SerializeToString()
  1353. # Parse message using the message set wire format.
  1354. proto = unittest_mset_pb2.TestMessageSet()
  1355. proto.MergeFromString(serialized)
  1356. # Check that the message parsed well.
  1357. extension_message1 = unittest_mset_pb2.TestMessageSetExtension1
  1358. extension1 = extension_message1.message_set_extension
  1359. self.assertEquals(12345, proto.Extensions[extension1].i)
  1360. def testUnknownFields(self):
  1361. proto = unittest_pb2.TestAllTypes()
  1362. test_util.SetAllFields(proto)
  1363. serialized = proto.SerializeToString()
  1364. # The empty message should be parsable with all of the fields
  1365. # unknown.
  1366. proto2 = unittest_pb2.TestEmptyMessage()
  1367. # Parsing this message should succeed.
  1368. proto2.MergeFromString(serialized)
  1369. # Now test with a int64 field set.
  1370. proto = unittest_pb2.TestAllTypes()
  1371. proto.optional_int64 = 0x0fffffffffffffff
  1372. serialized = proto.SerializeToString()
  1373. # The empty message should be parsable with all of the fields
  1374. # unknown.
  1375. proto2 = unittest_pb2.TestEmptyMessage()
  1376. # Parsing this message should succeed.
  1377. proto2.MergeFromString(serialized)
  1378. def _CheckRaises(self, exc_class, callable_obj, exception):
  1379. """This method checks if the excpetion type and message are as expected."""
  1380. try:
  1381. callable_obj()
  1382. except exc_class, ex:
  1383. # Check if the exception message is the right one.
  1384. self.assertEqual(exception, str(ex))
  1385. return
  1386. else:
  1387. raise self.failureException('%s not raised' % str(exc_class))
  1388. def testSerializeUninitialized(self):
  1389. proto = unittest_pb2.TestRequired()
  1390. self._CheckRaises(
  1391. message.EncodeError,
  1392. proto.SerializeToString,
  1393. 'Required field protobuf_unittest.TestRequired.a is not set.')
  1394. # Shouldn't raise exceptions.
  1395. partial = proto.SerializePartialToString()
  1396. proto.a = 1
  1397. self._CheckRaises(
  1398. message.EncodeError,
  1399. proto.SerializeToString,
  1400. 'Required field protobuf_unittest.TestRequired.b is not set.')
  1401. # Shouldn't raise exceptions.
  1402. partial = proto.SerializePartialToString()
  1403. proto.b = 2
  1404. self._CheckRaises(
  1405. message.EncodeError,
  1406. proto.SerializeToString,
  1407. 'Required field protobuf_unittest.TestRequired.c is not set.')
  1408. # Shouldn't raise exceptions.
  1409. partial = proto.SerializePartialToString()
  1410. proto.c = 3
  1411. serialized = proto.SerializeToString()
  1412. # Shouldn't raise exceptions.
  1413. partial = proto.SerializePartialToString()
  1414. proto2 = unittest_pb2.TestRequired()
  1415. proto2.MergeFromString(serialized)
  1416. self.assertEqual(1, proto2.a)
  1417. self.assertEqual(2, proto2.b)
  1418. self.assertEqual(3, proto2.c)
  1419. proto2.ParseFromString(partial)
  1420. self.assertEqual(1, proto2.a)
  1421. self.assertEqual(2, proto2.b)
  1422. self.assertEqual(3, proto2.c)
  1423. class OptionsTest(unittest.TestCase):
  1424. def testMessageOptions(self):
  1425. proto = unittest_mset_pb2.TestMessageSet()
  1426. self.assertEqual(True,
  1427. proto.DESCRIPTOR.GetOptions().message_set_wire_format)
  1428. proto = unittest_pb2.TestAllTypes()
  1429. self.assertEqual(False,
  1430. proto.DESCRIPTOR.GetOptions().message_set_wire_format)
  1431. class UtilityTest(unittest.TestCase):
  1432. def testImergeSorted(self):
  1433. ImergeSorted = reflection._ImergeSorted
  1434. # Various types of emptiness.
  1435. self.assertEqual([], list(ImergeSorted()))
  1436. self.assertEqual([], list(ImergeSorted([])))
  1437. self.assertEqual([], list(ImergeSorted([], [])))
  1438. # One nonempty list.
  1439. self.assertEqual([1, 2, 3], list(ImergeSorted([1, 2, 3])))
  1440. self.assertEqual([1, 2, 3], list(ImergeSorted([1, 2, 3], [])))
  1441. self.assertEqual([1, 2, 3], list(ImergeSorted([], [1, 2, 3])))
  1442. # Merging some nonempty lists together.
  1443. self.assertEqual([1, 2, 3], list(ImergeSorted([1, 3], [2])))
  1444. self.assertEqual([1, 2, 3], list(ImergeSorted([1], [3], [2])))
  1445. self.assertEqual([1, 2, 3], list(ImergeSorted([1], [3], [2], [])))
  1446. # Elements repeated across component iterators.
  1447. self.assertEqual([1, 2, 2, 3, 3],
  1448. list(ImergeSorted([1, 2], [3], [2, 3])))
  1449. # Elements repeated within an iterator.
  1450. self.assertEqual([1, 2, 2, 3, 3],
  1451. list(ImergeSorted([1, 2, 2], [3], [3])))
  1452. if __name__ == '__main__':
  1453. unittest.main()