reflection_test.py 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968
  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. # https://developers.google.com/protocol-buffers/
  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. import copy
  37. import gc
  38. import operator
  39. import struct
  40. import unittest
  41. try:
  42. from unittest import skipIf
  43. except ImportError:
  44. def skipIf(predicate, message):
  45. def decorator(wrapped):
  46. if predicate:
  47. def _noop(*args, **kw):
  48. pass
  49. return _noop
  50. return wrapped
  51. return decorator
  52. import six
  53. from google.protobuf import unittest_import_pb2
  54. from google.protobuf import unittest_mset_pb2
  55. from google.protobuf import unittest_pb2
  56. from google.protobuf import descriptor_pb2
  57. from google.protobuf import descriptor
  58. from google.protobuf import message
  59. from google.protobuf import reflection
  60. from google.protobuf import text_format
  61. from google.protobuf.internal import api_implementation
  62. from google.protobuf.internal import more_extensions_pb2
  63. from google.protobuf.internal import more_messages_pb2
  64. from google.protobuf.internal import wire_format
  65. from google.protobuf.internal import test_util
  66. from google.protobuf.internal import decoder
  67. class _MiniDecoder(object):
  68. """Decodes a stream of values from a string.
  69. Once upon a time we actually had a class called decoder.Decoder. Then we
  70. got rid of it during a redesign that made decoding much, much faster overall.
  71. But a couple tests in this file used it to check that the serialized form of
  72. a message was correct. So, this class implements just the methods that were
  73. used by said tests, so that we don't have to rewrite the tests.
  74. """
  75. def __init__(self, bytes):
  76. self._bytes = bytes
  77. self._pos = 0
  78. def ReadVarint(self):
  79. result, self._pos = decoder._DecodeVarint(self._bytes, self._pos)
  80. return result
  81. ReadInt32 = ReadVarint
  82. ReadInt64 = ReadVarint
  83. ReadUInt32 = ReadVarint
  84. ReadUInt64 = ReadVarint
  85. def ReadSInt64(self):
  86. return wire_format.ZigZagDecode(self.ReadVarint())
  87. ReadSInt32 = ReadSInt64
  88. def ReadFieldNumberAndWireType(self):
  89. return wire_format.UnpackTag(self.ReadVarint())
  90. def ReadFloat(self):
  91. result = struct.unpack("<f", self._bytes[self._pos:self._pos+4])[0]
  92. self._pos += 4
  93. return result
  94. def ReadDouble(self):
  95. result = struct.unpack("<d", self._bytes[self._pos:self._pos+8])[0]
  96. self._pos += 8
  97. return result
  98. def EndOfStream(self):
  99. return self._pos == len(self._bytes)
  100. class ReflectionTest(unittest.TestCase):
  101. def assertListsEqual(self, values, others):
  102. self.assertEqual(len(values), len(others))
  103. for i in range(len(values)):
  104. self.assertEqual(values[i], others[i])
  105. def testScalarConstructor(self):
  106. # Constructor with only scalar types should succeed.
  107. proto = unittest_pb2.TestAllTypes(
  108. optional_int32=24,
  109. optional_double=54.321,
  110. optional_string='optional_string')
  111. self.assertEqual(24, proto.optional_int32)
  112. self.assertEqual(54.321, proto.optional_double)
  113. self.assertEqual('optional_string', proto.optional_string)
  114. def testRepeatedScalarConstructor(self):
  115. # Constructor with only repeated scalar types should succeed.
  116. proto = unittest_pb2.TestAllTypes(
  117. repeated_int32=[1, 2, 3, 4],
  118. repeated_double=[1.23, 54.321],
  119. repeated_bool=[True, False, False],
  120. repeated_string=["optional_string"])
  121. self.assertEqual([1, 2, 3, 4], list(proto.repeated_int32))
  122. self.assertEqual([1.23, 54.321], list(proto.repeated_double))
  123. self.assertEqual([True, False, False], list(proto.repeated_bool))
  124. self.assertEqual(["optional_string"], list(proto.repeated_string))
  125. def testRepeatedCompositeConstructor(self):
  126. # Constructor with only repeated composite types should succeed.
  127. proto = unittest_pb2.TestAllTypes(
  128. repeated_nested_message=[
  129. unittest_pb2.TestAllTypes.NestedMessage(
  130. bb=unittest_pb2.TestAllTypes.FOO),
  131. unittest_pb2.TestAllTypes.NestedMessage(
  132. bb=unittest_pb2.TestAllTypes.BAR)],
  133. repeated_foreign_message=[
  134. unittest_pb2.ForeignMessage(c=-43),
  135. unittest_pb2.ForeignMessage(c=45324),
  136. unittest_pb2.ForeignMessage(c=12)],
  137. repeatedgroup=[
  138. unittest_pb2.TestAllTypes.RepeatedGroup(),
  139. unittest_pb2.TestAllTypes.RepeatedGroup(a=1),
  140. unittest_pb2.TestAllTypes.RepeatedGroup(a=2)])
  141. self.assertEqual(
  142. [unittest_pb2.TestAllTypes.NestedMessage(
  143. bb=unittest_pb2.TestAllTypes.FOO),
  144. unittest_pb2.TestAllTypes.NestedMessage(
  145. bb=unittest_pb2.TestAllTypes.BAR)],
  146. list(proto.repeated_nested_message))
  147. self.assertEqual(
  148. [unittest_pb2.ForeignMessage(c=-43),
  149. unittest_pb2.ForeignMessage(c=45324),
  150. unittest_pb2.ForeignMessage(c=12)],
  151. list(proto.repeated_foreign_message))
  152. self.assertEqual(
  153. [unittest_pb2.TestAllTypes.RepeatedGroup(),
  154. unittest_pb2.TestAllTypes.RepeatedGroup(a=1),
  155. unittest_pb2.TestAllTypes.RepeatedGroup(a=2)],
  156. list(proto.repeatedgroup))
  157. def testMixedConstructor(self):
  158. # Constructor with only mixed types should succeed.
  159. proto = unittest_pb2.TestAllTypes(
  160. optional_int32=24,
  161. optional_string='optional_string',
  162. repeated_double=[1.23, 54.321],
  163. repeated_bool=[True, False, False],
  164. repeated_nested_message=[
  165. unittest_pb2.TestAllTypes.NestedMessage(
  166. bb=unittest_pb2.TestAllTypes.FOO),
  167. unittest_pb2.TestAllTypes.NestedMessage(
  168. bb=unittest_pb2.TestAllTypes.BAR)],
  169. repeated_foreign_message=[
  170. unittest_pb2.ForeignMessage(c=-43),
  171. unittest_pb2.ForeignMessage(c=45324),
  172. unittest_pb2.ForeignMessage(c=12)])
  173. self.assertEqual(24, proto.optional_int32)
  174. self.assertEqual('optional_string', proto.optional_string)
  175. self.assertEqual([1.23, 54.321], list(proto.repeated_double))
  176. self.assertEqual([True, False, False], list(proto.repeated_bool))
  177. self.assertEqual(
  178. [unittest_pb2.TestAllTypes.NestedMessage(
  179. bb=unittest_pb2.TestAllTypes.FOO),
  180. unittest_pb2.TestAllTypes.NestedMessage(
  181. bb=unittest_pb2.TestAllTypes.BAR)],
  182. list(proto.repeated_nested_message))
  183. self.assertEqual(
  184. [unittest_pb2.ForeignMessage(c=-43),
  185. unittest_pb2.ForeignMessage(c=45324),
  186. unittest_pb2.ForeignMessage(c=12)],
  187. list(proto.repeated_foreign_message))
  188. def testConstructorTypeError(self):
  189. self.assertRaises(
  190. TypeError, unittest_pb2.TestAllTypes, optional_int32="foo")
  191. self.assertRaises(
  192. TypeError, unittest_pb2.TestAllTypes, optional_string=1234)
  193. self.assertRaises(
  194. TypeError, unittest_pb2.TestAllTypes, optional_nested_message=1234)
  195. self.assertRaises(
  196. TypeError, unittest_pb2.TestAllTypes, repeated_int32=1234)
  197. self.assertRaises(
  198. TypeError, unittest_pb2.TestAllTypes, repeated_int32=["foo"])
  199. self.assertRaises(
  200. TypeError, unittest_pb2.TestAllTypes, repeated_string=1234)
  201. self.assertRaises(
  202. TypeError, unittest_pb2.TestAllTypes, repeated_string=[1234])
  203. self.assertRaises(
  204. TypeError, unittest_pb2.TestAllTypes, repeated_nested_message=1234)
  205. self.assertRaises(
  206. TypeError, unittest_pb2.TestAllTypes, repeated_nested_message=[1234])
  207. def testConstructorInvalidatesCachedByteSize(self):
  208. message = unittest_pb2.TestAllTypes(optional_int32 = 12)
  209. self.assertEqual(2, message.ByteSize())
  210. message = unittest_pb2.TestAllTypes(
  211. optional_nested_message = unittest_pb2.TestAllTypes.NestedMessage())
  212. self.assertEqual(3, message.ByteSize())
  213. message = unittest_pb2.TestAllTypes(repeated_int32 = [12])
  214. self.assertEqual(3, message.ByteSize())
  215. message = unittest_pb2.TestAllTypes(
  216. repeated_nested_message = [unittest_pb2.TestAllTypes.NestedMessage()])
  217. self.assertEqual(3, message.ByteSize())
  218. def testSimpleHasBits(self):
  219. # Test a scalar.
  220. proto = unittest_pb2.TestAllTypes()
  221. self.assertTrue(not proto.HasField('optional_int32'))
  222. self.assertEqual(0, proto.optional_int32)
  223. # HasField() shouldn't be true if all we've done is
  224. # read the default value.
  225. self.assertTrue(not proto.HasField('optional_int32'))
  226. proto.optional_int32 = 1
  227. # Setting a value however *should* set the "has" bit.
  228. self.assertTrue(proto.HasField('optional_int32'))
  229. proto.ClearField('optional_int32')
  230. # And clearing that value should unset the "has" bit.
  231. self.assertTrue(not proto.HasField('optional_int32'))
  232. def testHasBitsWithSinglyNestedScalar(self):
  233. # Helper used to test foreign messages and groups.
  234. #
  235. # composite_field_name should be the name of a non-repeated
  236. # composite (i.e., foreign or group) field in TestAllTypes,
  237. # and scalar_field_name should be the name of an integer-valued
  238. # scalar field within that composite.
  239. #
  240. # I never thought I'd miss C++ macros and templates so much. :(
  241. # This helper is semantically just:
  242. #
  243. # assert proto.composite_field.scalar_field == 0
  244. # assert not proto.composite_field.HasField('scalar_field')
  245. # assert not proto.HasField('composite_field')
  246. #
  247. # proto.composite_field.scalar_field = 10
  248. # old_composite_field = proto.composite_field
  249. #
  250. # assert proto.composite_field.scalar_field == 10
  251. # assert proto.composite_field.HasField('scalar_field')
  252. # assert proto.HasField('composite_field')
  253. #
  254. # proto.ClearField('composite_field')
  255. #
  256. # assert not proto.composite_field.HasField('scalar_field')
  257. # assert not proto.HasField('composite_field')
  258. # assert proto.composite_field.scalar_field == 0
  259. #
  260. # # Now ensure that ClearField('composite_field') disconnected
  261. # # the old field object from the object tree...
  262. # assert old_composite_field is not proto.composite_field
  263. # old_composite_field.scalar_field = 20
  264. # assert not proto.composite_field.HasField('scalar_field')
  265. # assert not proto.HasField('composite_field')
  266. def TestCompositeHasBits(composite_field_name, scalar_field_name):
  267. proto = unittest_pb2.TestAllTypes()
  268. # First, check that we can get the scalar value, and see that it's the
  269. # default (0), but that proto.HasField('omposite') and
  270. # proto.composite.HasField('scalar') will still return False.
  271. composite_field = getattr(proto, composite_field_name)
  272. original_scalar_value = getattr(composite_field, scalar_field_name)
  273. self.assertEqual(0, original_scalar_value)
  274. # Assert that the composite object does not "have" the scalar.
  275. self.assertTrue(not composite_field.HasField(scalar_field_name))
  276. # Assert that proto does not "have" the composite field.
  277. self.assertTrue(not proto.HasField(composite_field_name))
  278. # Now set the scalar within the composite field. Ensure that the setting
  279. # is reflected, and that proto.HasField('composite') and
  280. # proto.composite.HasField('scalar') now both return True.
  281. new_val = 20
  282. setattr(composite_field, scalar_field_name, new_val)
  283. self.assertEqual(new_val, getattr(composite_field, scalar_field_name))
  284. # Hold on to a reference to the current composite_field object.
  285. old_composite_field = composite_field
  286. # Assert that the has methods now return true.
  287. self.assertTrue(composite_field.HasField(scalar_field_name))
  288. self.assertTrue(proto.HasField(composite_field_name))
  289. # Now call the clear method...
  290. proto.ClearField(composite_field_name)
  291. # ...and ensure that the "has" bits are all back to False...
  292. composite_field = getattr(proto, composite_field_name)
  293. self.assertTrue(not composite_field.HasField(scalar_field_name))
  294. self.assertTrue(not proto.HasField(composite_field_name))
  295. # ...and ensure that the scalar field has returned to its default.
  296. self.assertEqual(0, getattr(composite_field, scalar_field_name))
  297. self.assertTrue(old_composite_field is not composite_field)
  298. setattr(old_composite_field, scalar_field_name, new_val)
  299. self.assertTrue(not composite_field.HasField(scalar_field_name))
  300. self.assertTrue(not proto.HasField(composite_field_name))
  301. self.assertEqual(0, getattr(composite_field, scalar_field_name))
  302. # Test simple, single-level nesting when we set a scalar.
  303. TestCompositeHasBits('optionalgroup', 'a')
  304. TestCompositeHasBits('optional_nested_message', 'bb')
  305. TestCompositeHasBits('optional_foreign_message', 'c')
  306. TestCompositeHasBits('optional_import_message', 'd')
  307. def testReferencesToNestedMessage(self):
  308. proto = unittest_pb2.TestAllTypes()
  309. nested = proto.optional_nested_message
  310. del proto
  311. # A previous version had a bug where this would raise an exception when
  312. # hitting a now-dead weak reference.
  313. nested.bb = 23
  314. def testDisconnectingNestedMessageBeforeSettingField(self):
  315. proto = unittest_pb2.TestAllTypes()
  316. nested = proto.optional_nested_message
  317. proto.ClearField('optional_nested_message') # Should disconnect from parent
  318. self.assertTrue(nested is not proto.optional_nested_message)
  319. nested.bb = 23
  320. self.assertTrue(not proto.HasField('optional_nested_message'))
  321. self.assertEqual(0, proto.optional_nested_message.bb)
  322. def testGetDefaultMessageAfterDisconnectingDefaultMessage(self):
  323. proto = unittest_pb2.TestAllTypes()
  324. nested = proto.optional_nested_message
  325. proto.ClearField('optional_nested_message')
  326. del proto
  327. del nested
  328. # Force a garbage collect so that the underlying CMessages are freed along
  329. # with the Messages they point to. This is to make sure we're not deleting
  330. # default message instances.
  331. gc.collect()
  332. proto = unittest_pb2.TestAllTypes()
  333. nested = proto.optional_nested_message
  334. def testDisconnectingNestedMessageAfterSettingField(self):
  335. proto = unittest_pb2.TestAllTypes()
  336. nested = proto.optional_nested_message
  337. nested.bb = 5
  338. self.assertTrue(proto.HasField('optional_nested_message'))
  339. proto.ClearField('optional_nested_message') # Should disconnect from parent
  340. self.assertEqual(5, nested.bb)
  341. self.assertEqual(0, proto.optional_nested_message.bb)
  342. self.assertTrue(nested is not proto.optional_nested_message)
  343. nested.bb = 23
  344. self.assertTrue(not proto.HasField('optional_nested_message'))
  345. self.assertEqual(0, proto.optional_nested_message.bb)
  346. def testDisconnectingNestedMessageBeforeGettingField(self):
  347. proto = unittest_pb2.TestAllTypes()
  348. self.assertTrue(not proto.HasField('optional_nested_message'))
  349. proto.ClearField('optional_nested_message')
  350. self.assertTrue(not proto.HasField('optional_nested_message'))
  351. def testDisconnectingNestedMessageAfterMerge(self):
  352. # This test exercises the code path that does not use ReleaseMessage().
  353. # The underlying fear is that if we use ReleaseMessage() incorrectly,
  354. # we will have memory leaks. It's hard to check that that doesn't happen,
  355. # but at least we can exercise that code path to make sure it works.
  356. proto1 = unittest_pb2.TestAllTypes()
  357. proto2 = unittest_pb2.TestAllTypes()
  358. proto2.optional_nested_message.bb = 5
  359. proto1.MergeFrom(proto2)
  360. self.assertTrue(proto1.HasField('optional_nested_message'))
  361. proto1.ClearField('optional_nested_message')
  362. self.assertTrue(not proto1.HasField('optional_nested_message'))
  363. def testDisconnectingLazyNestedMessage(self):
  364. # This test exercises releasing a nested message that is lazy. This test
  365. # only exercises real code in the C++ implementation as Python does not
  366. # support lazy parsing, but the current C++ implementation results in
  367. # memory corruption and a crash.
  368. if api_implementation.Type() != 'python':
  369. return
  370. proto = unittest_pb2.TestAllTypes()
  371. proto.optional_lazy_message.bb = 5
  372. proto.ClearField('optional_lazy_message')
  373. del proto
  374. gc.collect()
  375. def testHasBitsWhenModifyingRepeatedFields(self):
  376. # Test nesting when we add an element to a repeated field in a submessage.
  377. proto = unittest_pb2.TestNestedMessageHasBits()
  378. proto.optional_nested_message.nestedmessage_repeated_int32.append(5)
  379. self.assertEqual(
  380. [5], proto.optional_nested_message.nestedmessage_repeated_int32)
  381. self.assertTrue(proto.HasField('optional_nested_message'))
  382. # Do the same test, but with a repeated composite field within the
  383. # submessage.
  384. proto.ClearField('optional_nested_message')
  385. self.assertTrue(not proto.HasField('optional_nested_message'))
  386. proto.optional_nested_message.nestedmessage_repeated_foreignmessage.add()
  387. self.assertTrue(proto.HasField('optional_nested_message'))
  388. def testHasBitsForManyLevelsOfNesting(self):
  389. # Test nesting many levels deep.
  390. recursive_proto = unittest_pb2.TestMutualRecursionA()
  391. self.assertTrue(not recursive_proto.HasField('bb'))
  392. self.assertEqual(0, recursive_proto.bb.a.bb.a.bb.optional_int32)
  393. self.assertTrue(not recursive_proto.HasField('bb'))
  394. recursive_proto.bb.a.bb.a.bb.optional_int32 = 5
  395. self.assertEqual(5, recursive_proto.bb.a.bb.a.bb.optional_int32)
  396. self.assertTrue(recursive_proto.HasField('bb'))
  397. self.assertTrue(recursive_proto.bb.HasField('a'))
  398. self.assertTrue(recursive_proto.bb.a.HasField('bb'))
  399. self.assertTrue(recursive_proto.bb.a.bb.HasField('a'))
  400. self.assertTrue(recursive_proto.bb.a.bb.a.HasField('bb'))
  401. self.assertTrue(not recursive_proto.bb.a.bb.a.bb.HasField('a'))
  402. self.assertTrue(recursive_proto.bb.a.bb.a.bb.HasField('optional_int32'))
  403. def testSingularListFields(self):
  404. proto = unittest_pb2.TestAllTypes()
  405. proto.optional_fixed32 = 1
  406. proto.optional_int32 = 5
  407. proto.optional_string = 'foo'
  408. # Access sub-message but don't set it yet.
  409. nested_message = proto.optional_nested_message
  410. self.assertEqual(
  411. [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 5),
  412. (proto.DESCRIPTOR.fields_by_name['optional_fixed32'], 1),
  413. (proto.DESCRIPTOR.fields_by_name['optional_string' ], 'foo') ],
  414. proto.ListFields())
  415. proto.optional_nested_message.bb = 123
  416. self.assertEqual(
  417. [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 5),
  418. (proto.DESCRIPTOR.fields_by_name['optional_fixed32'], 1),
  419. (proto.DESCRIPTOR.fields_by_name['optional_string' ], 'foo'),
  420. (proto.DESCRIPTOR.fields_by_name['optional_nested_message' ],
  421. nested_message) ],
  422. proto.ListFields())
  423. def testRepeatedListFields(self):
  424. proto = unittest_pb2.TestAllTypes()
  425. proto.repeated_fixed32.append(1)
  426. proto.repeated_int32.append(5)
  427. proto.repeated_int32.append(11)
  428. proto.repeated_string.extend(['foo', 'bar'])
  429. proto.repeated_string.extend([])
  430. proto.repeated_string.append('baz')
  431. proto.repeated_string.extend(str(x) for x in range(2))
  432. proto.optional_int32 = 21
  433. proto.repeated_bool # Access but don't set anything; should not be listed.
  434. self.assertEqual(
  435. [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 21),
  436. (proto.DESCRIPTOR.fields_by_name['repeated_int32' ], [5, 11]),
  437. (proto.DESCRIPTOR.fields_by_name['repeated_fixed32'], [1]),
  438. (proto.DESCRIPTOR.fields_by_name['repeated_string' ],
  439. ['foo', 'bar', 'baz', '0', '1']) ],
  440. proto.ListFields())
  441. def testSingularListExtensions(self):
  442. proto = unittest_pb2.TestAllExtensions()
  443. proto.Extensions[unittest_pb2.optional_fixed32_extension] = 1
  444. proto.Extensions[unittest_pb2.optional_int32_extension ] = 5
  445. proto.Extensions[unittest_pb2.optional_string_extension ] = 'foo'
  446. self.assertEqual(
  447. [ (unittest_pb2.optional_int32_extension , 5),
  448. (unittest_pb2.optional_fixed32_extension, 1),
  449. (unittest_pb2.optional_string_extension , 'foo') ],
  450. proto.ListFields())
  451. def testRepeatedListExtensions(self):
  452. proto = unittest_pb2.TestAllExtensions()
  453. proto.Extensions[unittest_pb2.repeated_fixed32_extension].append(1)
  454. proto.Extensions[unittest_pb2.repeated_int32_extension ].append(5)
  455. proto.Extensions[unittest_pb2.repeated_int32_extension ].append(11)
  456. proto.Extensions[unittest_pb2.repeated_string_extension ].append('foo')
  457. proto.Extensions[unittest_pb2.repeated_string_extension ].append('bar')
  458. proto.Extensions[unittest_pb2.repeated_string_extension ].append('baz')
  459. proto.Extensions[unittest_pb2.optional_int32_extension ] = 21
  460. self.assertEqual(
  461. [ (unittest_pb2.optional_int32_extension , 21),
  462. (unittest_pb2.repeated_int32_extension , [5, 11]),
  463. (unittest_pb2.repeated_fixed32_extension, [1]),
  464. (unittest_pb2.repeated_string_extension , ['foo', 'bar', 'baz']) ],
  465. proto.ListFields())
  466. def testListFieldsAndExtensions(self):
  467. proto = unittest_pb2.TestFieldOrderings()
  468. test_util.SetAllFieldsAndExtensions(proto)
  469. unittest_pb2.my_extension_int
  470. self.assertEqual(
  471. [ (proto.DESCRIPTOR.fields_by_name['my_int' ], 1),
  472. (unittest_pb2.my_extension_int , 23),
  473. (proto.DESCRIPTOR.fields_by_name['my_string'], 'foo'),
  474. (unittest_pb2.my_extension_string , 'bar'),
  475. (proto.DESCRIPTOR.fields_by_name['my_float' ], 1.0) ],
  476. proto.ListFields())
  477. def testDefaultValues(self):
  478. proto = unittest_pb2.TestAllTypes()
  479. self.assertEqual(0, proto.optional_int32)
  480. self.assertEqual(0, proto.optional_int64)
  481. self.assertEqual(0, proto.optional_uint32)
  482. self.assertEqual(0, proto.optional_uint64)
  483. self.assertEqual(0, proto.optional_sint32)
  484. self.assertEqual(0, proto.optional_sint64)
  485. self.assertEqual(0, proto.optional_fixed32)
  486. self.assertEqual(0, proto.optional_fixed64)
  487. self.assertEqual(0, proto.optional_sfixed32)
  488. self.assertEqual(0, proto.optional_sfixed64)
  489. self.assertEqual(0.0, proto.optional_float)
  490. self.assertEqual(0.0, proto.optional_double)
  491. self.assertEqual(False, proto.optional_bool)
  492. self.assertEqual('', proto.optional_string)
  493. self.assertEqual(b'', proto.optional_bytes)
  494. self.assertEqual(41, proto.default_int32)
  495. self.assertEqual(42, proto.default_int64)
  496. self.assertEqual(43, proto.default_uint32)
  497. self.assertEqual(44, proto.default_uint64)
  498. self.assertEqual(-45, proto.default_sint32)
  499. self.assertEqual(46, proto.default_sint64)
  500. self.assertEqual(47, proto.default_fixed32)
  501. self.assertEqual(48, proto.default_fixed64)
  502. self.assertEqual(49, proto.default_sfixed32)
  503. self.assertEqual(-50, proto.default_sfixed64)
  504. self.assertEqual(51.5, proto.default_float)
  505. self.assertEqual(52e3, proto.default_double)
  506. self.assertEqual(True, proto.default_bool)
  507. self.assertEqual('hello', proto.default_string)
  508. self.assertEqual(b'world', proto.default_bytes)
  509. self.assertEqual(unittest_pb2.TestAllTypes.BAR, proto.default_nested_enum)
  510. self.assertEqual(unittest_pb2.FOREIGN_BAR, proto.default_foreign_enum)
  511. self.assertEqual(unittest_import_pb2.IMPORT_BAR,
  512. proto.default_import_enum)
  513. proto = unittest_pb2.TestExtremeDefaultValues()
  514. self.assertEqual(u'\u1234', proto.utf8_string)
  515. def testHasFieldWithUnknownFieldName(self):
  516. proto = unittest_pb2.TestAllTypes()
  517. self.assertRaises(ValueError, proto.HasField, 'nonexistent_field')
  518. def testClearFieldWithUnknownFieldName(self):
  519. proto = unittest_pb2.TestAllTypes()
  520. self.assertRaises(ValueError, proto.ClearField, 'nonexistent_field')
  521. def testClearRemovesChildren(self):
  522. # Make sure there aren't any implementation bugs that are only partially
  523. # clearing the message (which can happen in the more complex C++
  524. # implementation which has parallel message lists).
  525. proto = unittest_pb2.TestRequiredForeign()
  526. for i in range(10):
  527. proto.repeated_message.add()
  528. proto2 = unittest_pb2.TestRequiredForeign()
  529. proto.CopyFrom(proto2)
  530. self.assertRaises(IndexError, lambda: proto.repeated_message[5])
  531. def testDisallowedAssignments(self):
  532. # It's illegal to assign values directly to repeated fields
  533. # or to nonrepeated composite fields. Ensure that this fails.
  534. proto = unittest_pb2.TestAllTypes()
  535. # Repeated fields.
  536. self.assertRaises(AttributeError, setattr, proto, 'repeated_int32', 10)
  537. # Lists shouldn't work, either.
  538. self.assertRaises(AttributeError, setattr, proto, 'repeated_int32', [10])
  539. # Composite fields.
  540. self.assertRaises(AttributeError, setattr, proto,
  541. 'optional_nested_message', 23)
  542. # Assignment to a repeated nested message field without specifying
  543. # the index in the array of nested messages.
  544. self.assertRaises(AttributeError, setattr, proto.repeated_nested_message,
  545. 'bb', 34)
  546. # Assignment to an attribute of a repeated field.
  547. self.assertRaises(AttributeError, setattr, proto.repeated_float,
  548. 'some_attribute', 34)
  549. # proto.nonexistent_field = 23 should fail as well.
  550. self.assertRaises(AttributeError, setattr, proto, 'nonexistent_field', 23)
  551. def testSingleScalarTypeSafety(self):
  552. proto = unittest_pb2.TestAllTypes()
  553. self.assertRaises(TypeError, setattr, proto, 'optional_int32', 1.1)
  554. self.assertRaises(TypeError, setattr, proto, 'optional_int32', 'foo')
  555. self.assertRaises(TypeError, setattr, proto, 'optional_string', 10)
  556. self.assertRaises(TypeError, setattr, proto, 'optional_bytes', 10)
  557. def testIntegerTypes(self):
  558. def TestGetAndDeserialize(field_name, value, expected_type):
  559. proto = unittest_pb2.TestAllTypes()
  560. setattr(proto, field_name, value)
  561. self.assertTrue(isinstance(getattr(proto, field_name), expected_type))
  562. proto2 = unittest_pb2.TestAllTypes()
  563. proto2.ParseFromString(proto.SerializeToString())
  564. self.assertTrue(isinstance(getattr(proto2, field_name), expected_type))
  565. TestGetAndDeserialize('optional_int32', 1, int)
  566. TestGetAndDeserialize('optional_int32', 1 << 30, int)
  567. TestGetAndDeserialize('optional_uint32', 1 << 30, int)
  568. if struct.calcsize('L') == 4:
  569. # Python only has signed ints, so 32-bit python can't fit an uint32
  570. # in an int.
  571. TestGetAndDeserialize('optional_uint32', 1 << 31, int)
  572. else:
  573. # 64-bit python can fit uint32 inside an int
  574. TestGetAndDeserialize('optional_uint32', 1 << 31, int)
  575. try:
  576. integer_64 = long
  577. except NameError: # Python3
  578. integer_64 = int
  579. TestGetAndDeserialize('optional_int64', 1 << 30, integer_64)
  580. TestGetAndDeserialize('optional_int64', 1 << 60, integer_64)
  581. TestGetAndDeserialize('optional_uint64', 1 << 30, integer_64)
  582. TestGetAndDeserialize('optional_uint64', 1 << 60, integer_64)
  583. def testSingleScalarBoundsChecking(self):
  584. def TestMinAndMaxIntegers(field_name, expected_min, expected_max):
  585. pb = unittest_pb2.TestAllTypes()
  586. setattr(pb, field_name, expected_min)
  587. self.assertEqual(expected_min, getattr(pb, field_name))
  588. setattr(pb, field_name, expected_max)
  589. self.assertEqual(expected_max, getattr(pb, field_name))
  590. self.assertRaises(ValueError, setattr, pb, field_name, expected_min - 1)
  591. self.assertRaises(ValueError, setattr, pb, field_name, expected_max + 1)
  592. TestMinAndMaxIntegers('optional_int32', -(1 << 31), (1 << 31) - 1)
  593. TestMinAndMaxIntegers('optional_uint32', 0, 0xffffffff)
  594. TestMinAndMaxIntegers('optional_int64', -(1 << 63), (1 << 63) - 1)
  595. TestMinAndMaxIntegers('optional_uint64', 0, 0xffffffffffffffff)
  596. pb = unittest_pb2.TestAllTypes()
  597. pb.optional_nested_enum = 1
  598. self.assertEqual(1, pb.optional_nested_enum)
  599. def testRepeatedScalarTypeSafety(self):
  600. proto = unittest_pb2.TestAllTypes()
  601. self.assertRaises(TypeError, proto.repeated_int32.append, 1.1)
  602. self.assertRaises(TypeError, proto.repeated_int32.append, 'foo')
  603. self.assertRaises(TypeError, proto.repeated_string, 10)
  604. self.assertRaises(TypeError, proto.repeated_bytes, 10)
  605. proto.repeated_int32.append(10)
  606. proto.repeated_int32[0] = 23
  607. self.assertRaises(IndexError, proto.repeated_int32.__setitem__, 500, 23)
  608. self.assertRaises(TypeError, proto.repeated_int32.__setitem__, 0, 'abc')
  609. # Repeated enums tests.
  610. #proto.repeated_nested_enum.append(0)
  611. def testSingleScalarGettersAndSetters(self):
  612. proto = unittest_pb2.TestAllTypes()
  613. self.assertEqual(0, proto.optional_int32)
  614. proto.optional_int32 = 1
  615. self.assertEqual(1, proto.optional_int32)
  616. proto.optional_uint64 = 0xffffffffffff
  617. self.assertEqual(0xffffffffffff, proto.optional_uint64)
  618. proto.optional_uint64 = 0xffffffffffffffff
  619. self.assertEqual(0xffffffffffffffff, proto.optional_uint64)
  620. # TODO(robinson): Test all other scalar field types.
  621. def testSingleScalarClearField(self):
  622. proto = unittest_pb2.TestAllTypes()
  623. # Should be allowed to clear something that's not there (a no-op).
  624. proto.ClearField('optional_int32')
  625. proto.optional_int32 = 1
  626. self.assertTrue(proto.HasField('optional_int32'))
  627. proto.ClearField('optional_int32')
  628. self.assertEqual(0, proto.optional_int32)
  629. self.assertTrue(not proto.HasField('optional_int32'))
  630. # TODO(robinson): Test all other scalar field types.
  631. def testEnums(self):
  632. proto = unittest_pb2.TestAllTypes()
  633. self.assertEqual(1, proto.FOO)
  634. self.assertEqual(1, unittest_pb2.TestAllTypes.FOO)
  635. self.assertEqual(2, proto.BAR)
  636. self.assertEqual(2, unittest_pb2.TestAllTypes.BAR)
  637. self.assertEqual(3, proto.BAZ)
  638. self.assertEqual(3, unittest_pb2.TestAllTypes.BAZ)
  639. def testEnum_Name(self):
  640. self.assertEqual('FOREIGN_FOO',
  641. unittest_pb2.ForeignEnum.Name(unittest_pb2.FOREIGN_FOO))
  642. self.assertEqual('FOREIGN_BAR',
  643. unittest_pb2.ForeignEnum.Name(unittest_pb2.FOREIGN_BAR))
  644. self.assertEqual('FOREIGN_BAZ',
  645. unittest_pb2.ForeignEnum.Name(unittest_pb2.FOREIGN_BAZ))
  646. self.assertRaises(ValueError,
  647. unittest_pb2.ForeignEnum.Name, 11312)
  648. proto = unittest_pb2.TestAllTypes()
  649. self.assertEqual('FOO',
  650. proto.NestedEnum.Name(proto.FOO))
  651. self.assertEqual('FOO',
  652. unittest_pb2.TestAllTypes.NestedEnum.Name(proto.FOO))
  653. self.assertEqual('BAR',
  654. proto.NestedEnum.Name(proto.BAR))
  655. self.assertEqual('BAR',
  656. unittest_pb2.TestAllTypes.NestedEnum.Name(proto.BAR))
  657. self.assertEqual('BAZ',
  658. proto.NestedEnum.Name(proto.BAZ))
  659. self.assertEqual('BAZ',
  660. unittest_pb2.TestAllTypes.NestedEnum.Name(proto.BAZ))
  661. self.assertRaises(ValueError,
  662. proto.NestedEnum.Name, 11312)
  663. self.assertRaises(ValueError,
  664. unittest_pb2.TestAllTypes.NestedEnum.Name, 11312)
  665. def testEnum_Value(self):
  666. self.assertEqual(unittest_pb2.FOREIGN_FOO,
  667. unittest_pb2.ForeignEnum.Value('FOREIGN_FOO'))
  668. self.assertEqual(unittest_pb2.FOREIGN_BAR,
  669. unittest_pb2.ForeignEnum.Value('FOREIGN_BAR'))
  670. self.assertEqual(unittest_pb2.FOREIGN_BAZ,
  671. unittest_pb2.ForeignEnum.Value('FOREIGN_BAZ'))
  672. self.assertRaises(ValueError,
  673. unittest_pb2.ForeignEnum.Value, 'FO')
  674. proto = unittest_pb2.TestAllTypes()
  675. self.assertEqual(proto.FOO,
  676. proto.NestedEnum.Value('FOO'))
  677. self.assertEqual(proto.FOO,
  678. unittest_pb2.TestAllTypes.NestedEnum.Value('FOO'))
  679. self.assertEqual(proto.BAR,
  680. proto.NestedEnum.Value('BAR'))
  681. self.assertEqual(proto.BAR,
  682. unittest_pb2.TestAllTypes.NestedEnum.Value('BAR'))
  683. self.assertEqual(proto.BAZ,
  684. proto.NestedEnum.Value('BAZ'))
  685. self.assertEqual(proto.BAZ,
  686. unittest_pb2.TestAllTypes.NestedEnum.Value('BAZ'))
  687. self.assertRaises(ValueError,
  688. proto.NestedEnum.Value, 'Foo')
  689. self.assertRaises(ValueError,
  690. unittest_pb2.TestAllTypes.NestedEnum.Value, 'Foo')
  691. def testEnum_KeysAndValues(self):
  692. self.assertEqual(['FOREIGN_FOO', 'FOREIGN_BAR', 'FOREIGN_BAZ'],
  693. list(unittest_pb2.ForeignEnum.keys()))
  694. self.assertEqual([4, 5, 6],
  695. list(unittest_pb2.ForeignEnum.values()))
  696. self.assertEqual([('FOREIGN_FOO', 4), ('FOREIGN_BAR', 5),
  697. ('FOREIGN_BAZ', 6)],
  698. list(unittest_pb2.ForeignEnum.items()))
  699. proto = unittest_pb2.TestAllTypes()
  700. self.assertEqual(['FOO', 'BAR', 'BAZ', 'NEG'], list(proto.NestedEnum.keys()))
  701. self.assertEqual([1, 2, 3, -1], list(proto.NestedEnum.values()))
  702. self.assertEqual([('FOO', 1), ('BAR', 2), ('BAZ', 3), ('NEG', -1)],
  703. list(proto.NestedEnum.items()))
  704. def testRepeatedScalars(self):
  705. proto = unittest_pb2.TestAllTypes()
  706. self.assertTrue(not proto.repeated_int32)
  707. self.assertEqual(0, len(proto.repeated_int32))
  708. proto.repeated_int32.append(5)
  709. proto.repeated_int32.append(10)
  710. proto.repeated_int32.append(15)
  711. self.assertTrue(proto.repeated_int32)
  712. self.assertEqual(3, len(proto.repeated_int32))
  713. self.assertEqual([5, 10, 15], proto.repeated_int32)
  714. # Test single retrieval.
  715. self.assertEqual(5, proto.repeated_int32[0])
  716. self.assertEqual(15, proto.repeated_int32[-1])
  717. # Test out-of-bounds indices.
  718. self.assertRaises(IndexError, proto.repeated_int32.__getitem__, 1234)
  719. self.assertRaises(IndexError, proto.repeated_int32.__getitem__, -1234)
  720. # Test incorrect types passed to __getitem__.
  721. self.assertRaises(TypeError, proto.repeated_int32.__getitem__, 'foo')
  722. self.assertRaises(TypeError, proto.repeated_int32.__getitem__, None)
  723. # Test single assignment.
  724. proto.repeated_int32[1] = 20
  725. self.assertEqual([5, 20, 15], proto.repeated_int32)
  726. # Test insertion.
  727. proto.repeated_int32.insert(1, 25)
  728. self.assertEqual([5, 25, 20, 15], proto.repeated_int32)
  729. # Test slice retrieval.
  730. proto.repeated_int32.append(30)
  731. self.assertEqual([25, 20, 15], proto.repeated_int32[1:4])
  732. self.assertEqual([5, 25, 20, 15, 30], proto.repeated_int32[:])
  733. # Test slice assignment with an iterator
  734. proto.repeated_int32[1:4] = (i for i in range(3))
  735. self.assertEqual([5, 0, 1, 2, 30], proto.repeated_int32)
  736. # Test slice assignment.
  737. proto.repeated_int32[1:4] = [35, 40, 45]
  738. self.assertEqual([5, 35, 40, 45, 30], proto.repeated_int32)
  739. # Test that we can use the field as an iterator.
  740. result = []
  741. for i in proto.repeated_int32:
  742. result.append(i)
  743. self.assertEqual([5, 35, 40, 45, 30], result)
  744. # Test single deletion.
  745. del proto.repeated_int32[2]
  746. self.assertEqual([5, 35, 45, 30], proto.repeated_int32)
  747. # Test slice deletion.
  748. del proto.repeated_int32[2:]
  749. self.assertEqual([5, 35], proto.repeated_int32)
  750. # Test extending.
  751. proto.repeated_int32.extend([3, 13])
  752. self.assertEqual([5, 35, 3, 13], proto.repeated_int32)
  753. # Test clearing.
  754. proto.ClearField('repeated_int32')
  755. self.assertTrue(not proto.repeated_int32)
  756. self.assertEqual(0, len(proto.repeated_int32))
  757. proto.repeated_int32.append(1)
  758. self.assertEqual(1, proto.repeated_int32[-1])
  759. # Test assignment to a negative index.
  760. proto.repeated_int32[-1] = 2
  761. self.assertEqual(2, proto.repeated_int32[-1])
  762. # Test deletion at negative indices.
  763. proto.repeated_int32[:] = [0, 1, 2, 3]
  764. del proto.repeated_int32[-1]
  765. self.assertEqual([0, 1, 2], proto.repeated_int32)
  766. del proto.repeated_int32[-2]
  767. self.assertEqual([0, 2], proto.repeated_int32)
  768. self.assertRaises(IndexError, proto.repeated_int32.__delitem__, -3)
  769. self.assertRaises(IndexError, proto.repeated_int32.__delitem__, 300)
  770. del proto.repeated_int32[-2:-1]
  771. self.assertEqual([2], proto.repeated_int32)
  772. del proto.repeated_int32[100:10000]
  773. self.assertEqual([2], proto.repeated_int32)
  774. def testRepeatedScalarsRemove(self):
  775. proto = unittest_pb2.TestAllTypes()
  776. self.assertTrue(not proto.repeated_int32)
  777. self.assertEqual(0, len(proto.repeated_int32))
  778. proto.repeated_int32.append(5)
  779. proto.repeated_int32.append(10)
  780. proto.repeated_int32.append(5)
  781. proto.repeated_int32.append(5)
  782. self.assertEqual(4, len(proto.repeated_int32))
  783. proto.repeated_int32.remove(5)
  784. self.assertEqual(3, len(proto.repeated_int32))
  785. self.assertEqual(10, proto.repeated_int32[0])
  786. self.assertEqual(5, proto.repeated_int32[1])
  787. self.assertEqual(5, proto.repeated_int32[2])
  788. proto.repeated_int32.remove(5)
  789. self.assertEqual(2, len(proto.repeated_int32))
  790. self.assertEqual(10, proto.repeated_int32[0])
  791. self.assertEqual(5, proto.repeated_int32[1])
  792. proto.repeated_int32.remove(10)
  793. self.assertEqual(1, len(proto.repeated_int32))
  794. self.assertEqual(5, proto.repeated_int32[0])
  795. # Remove a non-existent element.
  796. self.assertRaises(ValueError, proto.repeated_int32.remove, 123)
  797. def testRepeatedComposites(self):
  798. proto = unittest_pb2.TestAllTypes()
  799. self.assertTrue(not proto.repeated_nested_message)
  800. self.assertEqual(0, len(proto.repeated_nested_message))
  801. m0 = proto.repeated_nested_message.add()
  802. m1 = proto.repeated_nested_message.add()
  803. self.assertTrue(proto.repeated_nested_message)
  804. self.assertEqual(2, len(proto.repeated_nested_message))
  805. self.assertListsEqual([m0, m1], proto.repeated_nested_message)
  806. self.assertTrue(isinstance(m0, unittest_pb2.TestAllTypes.NestedMessage))
  807. # Test out-of-bounds indices.
  808. self.assertRaises(IndexError, proto.repeated_nested_message.__getitem__,
  809. 1234)
  810. self.assertRaises(IndexError, proto.repeated_nested_message.__getitem__,
  811. -1234)
  812. # Test incorrect types passed to __getitem__.
  813. self.assertRaises(TypeError, proto.repeated_nested_message.__getitem__,
  814. 'foo')
  815. self.assertRaises(TypeError, proto.repeated_nested_message.__getitem__,
  816. None)
  817. # Test slice retrieval.
  818. m2 = proto.repeated_nested_message.add()
  819. m3 = proto.repeated_nested_message.add()
  820. m4 = proto.repeated_nested_message.add()
  821. self.assertListsEqual(
  822. [m1, m2, m3], proto.repeated_nested_message[1:4])
  823. self.assertListsEqual(
  824. [m0, m1, m2, m3, m4], proto.repeated_nested_message[:])
  825. self.assertListsEqual(
  826. [m0, m1], proto.repeated_nested_message[:2])
  827. self.assertListsEqual(
  828. [m2, m3, m4], proto.repeated_nested_message[2:])
  829. self.assertEqual(
  830. m0, proto.repeated_nested_message[0])
  831. self.assertListsEqual(
  832. [m0], proto.repeated_nested_message[:1])
  833. # Test that we can use the field as an iterator.
  834. result = []
  835. for i in proto.repeated_nested_message:
  836. result.append(i)
  837. self.assertListsEqual([m0, m1, m2, m3, m4], result)
  838. # Test single deletion.
  839. del proto.repeated_nested_message[2]
  840. self.assertListsEqual([m0, m1, m3, m4], proto.repeated_nested_message)
  841. # Test slice deletion.
  842. del proto.repeated_nested_message[2:]
  843. self.assertListsEqual([m0, m1], proto.repeated_nested_message)
  844. # Test extending.
  845. n1 = unittest_pb2.TestAllTypes.NestedMessage(bb=1)
  846. n2 = unittest_pb2.TestAllTypes.NestedMessage(bb=2)
  847. proto.repeated_nested_message.extend([n1,n2])
  848. self.assertEqual(4, len(proto.repeated_nested_message))
  849. self.assertEqual(n1, proto.repeated_nested_message[2])
  850. self.assertEqual(n2, proto.repeated_nested_message[3])
  851. # Test clearing.
  852. proto.ClearField('repeated_nested_message')
  853. self.assertTrue(not proto.repeated_nested_message)
  854. self.assertEqual(0, len(proto.repeated_nested_message))
  855. # Test constructing an element while adding it.
  856. proto.repeated_nested_message.add(bb=23)
  857. self.assertEqual(1, len(proto.repeated_nested_message))
  858. self.assertEqual(23, proto.repeated_nested_message[0].bb)
  859. def testRepeatedCompositeRemove(self):
  860. proto = unittest_pb2.TestAllTypes()
  861. self.assertEqual(0, len(proto.repeated_nested_message))
  862. m0 = proto.repeated_nested_message.add()
  863. # Need to set some differentiating variable so m0 != m1 != m2:
  864. m0.bb = len(proto.repeated_nested_message)
  865. m1 = proto.repeated_nested_message.add()
  866. m1.bb = len(proto.repeated_nested_message)
  867. self.assertTrue(m0 != m1)
  868. m2 = proto.repeated_nested_message.add()
  869. m2.bb = len(proto.repeated_nested_message)
  870. self.assertListsEqual([m0, m1, m2], proto.repeated_nested_message)
  871. self.assertEqual(3, len(proto.repeated_nested_message))
  872. proto.repeated_nested_message.remove(m0)
  873. self.assertEqual(2, len(proto.repeated_nested_message))
  874. self.assertEqual(m1, proto.repeated_nested_message[0])
  875. self.assertEqual(m2, proto.repeated_nested_message[1])
  876. # Removing m0 again or removing None should raise error
  877. self.assertRaises(ValueError, proto.repeated_nested_message.remove, m0)
  878. self.assertRaises(ValueError, proto.repeated_nested_message.remove, None)
  879. self.assertEqual(2, len(proto.repeated_nested_message))
  880. proto.repeated_nested_message.remove(m2)
  881. self.assertEqual(1, len(proto.repeated_nested_message))
  882. self.assertEqual(m1, proto.repeated_nested_message[0])
  883. def testHandWrittenReflection(self):
  884. # Hand written extensions are only supported by the pure-Python
  885. # implementation of the API.
  886. if api_implementation.Type() != 'python':
  887. return
  888. FieldDescriptor = descriptor.FieldDescriptor
  889. foo_field_descriptor = FieldDescriptor(
  890. name='foo_field', full_name='MyProto.foo_field',
  891. index=0, number=1, type=FieldDescriptor.TYPE_INT64,
  892. cpp_type=FieldDescriptor.CPPTYPE_INT64,
  893. label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
  894. containing_type=None, message_type=None, enum_type=None,
  895. is_extension=False, extension_scope=None,
  896. options=descriptor_pb2.FieldOptions())
  897. mydescriptor = descriptor.Descriptor(
  898. name='MyProto', full_name='MyProto', filename='ignored',
  899. containing_type=None, nested_types=[], enum_types=[],
  900. fields=[foo_field_descriptor], extensions=[],
  901. options=descriptor_pb2.MessageOptions())
  902. class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
  903. DESCRIPTOR = mydescriptor
  904. myproto_instance = MyProtoClass()
  905. self.assertEqual(0, myproto_instance.foo_field)
  906. self.assertTrue(not myproto_instance.HasField('foo_field'))
  907. myproto_instance.foo_field = 23
  908. self.assertEqual(23, myproto_instance.foo_field)
  909. self.assertTrue(myproto_instance.HasField('foo_field'))
  910. def testDescriptorProtoSupport(self):
  911. # Hand written descriptors/reflection are only supported by the pure-Python
  912. # implementation of the API.
  913. if api_implementation.Type() != 'python':
  914. return
  915. def AddDescriptorField(proto, field_name, field_type):
  916. AddDescriptorField.field_index += 1
  917. new_field = proto.field.add()
  918. new_field.name = field_name
  919. new_field.type = field_type
  920. new_field.number = AddDescriptorField.field_index
  921. new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL
  922. AddDescriptorField.field_index = 0
  923. desc_proto = descriptor_pb2.DescriptorProto()
  924. desc_proto.name = 'Car'
  925. fdp = descriptor_pb2.FieldDescriptorProto
  926. AddDescriptorField(desc_proto, 'name', fdp.TYPE_STRING)
  927. AddDescriptorField(desc_proto, 'year', fdp.TYPE_INT64)
  928. AddDescriptorField(desc_proto, 'automatic', fdp.TYPE_BOOL)
  929. AddDescriptorField(desc_proto, 'price', fdp.TYPE_DOUBLE)
  930. # Add a repeated field
  931. AddDescriptorField.field_index += 1
  932. new_field = desc_proto.field.add()
  933. new_field.name = 'owners'
  934. new_field.type = fdp.TYPE_STRING
  935. new_field.number = AddDescriptorField.field_index
  936. new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_REPEATED
  937. desc = descriptor.MakeDescriptor(desc_proto)
  938. self.assertTrue('name' in desc.fields_by_name)
  939. self.assertTrue('year' in desc.fields_by_name)
  940. self.assertTrue('automatic' in desc.fields_by_name)
  941. self.assertTrue('price' in desc.fields_by_name)
  942. self.assertTrue('owners' in desc.fields_by_name)
  943. class CarMessage(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
  944. DESCRIPTOR = desc
  945. prius = CarMessage()
  946. prius.name = 'prius'
  947. prius.year = 2010
  948. prius.automatic = True
  949. prius.price = 25134.75
  950. prius.owners.extend(['bob', 'susan'])
  951. serialized_prius = prius.SerializeToString()
  952. new_prius = reflection.ParseMessage(desc, serialized_prius)
  953. self.assertTrue(new_prius is not prius)
  954. self.assertEqual(prius, new_prius)
  955. # these are unnecessary assuming message equality works as advertised but
  956. # explicitly check to be safe since we're mucking about in metaclass foo
  957. self.assertEqual(prius.name, new_prius.name)
  958. self.assertEqual(prius.year, new_prius.year)
  959. self.assertEqual(prius.automatic, new_prius.automatic)
  960. self.assertEqual(prius.price, new_prius.price)
  961. self.assertEqual(prius.owners, new_prius.owners)
  962. def testTopLevelExtensionsForOptionalScalar(self):
  963. extendee_proto = unittest_pb2.TestAllExtensions()
  964. extension = unittest_pb2.optional_int32_extension
  965. self.assertTrue(not extendee_proto.HasExtension(extension))
  966. self.assertEqual(0, extendee_proto.Extensions[extension])
  967. # As with normal scalar fields, just doing a read doesn't actually set the
  968. # "has" bit.
  969. self.assertTrue(not extendee_proto.HasExtension(extension))
  970. # Actually set the thing.
  971. extendee_proto.Extensions[extension] = 23
  972. self.assertEqual(23, extendee_proto.Extensions[extension])
  973. self.assertTrue(extendee_proto.HasExtension(extension))
  974. # Ensure that clearing works as well.
  975. extendee_proto.ClearExtension(extension)
  976. self.assertEqual(0, extendee_proto.Extensions[extension])
  977. self.assertTrue(not extendee_proto.HasExtension(extension))
  978. def testTopLevelExtensionsForRepeatedScalar(self):
  979. extendee_proto = unittest_pb2.TestAllExtensions()
  980. extension = unittest_pb2.repeated_string_extension
  981. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  982. extendee_proto.Extensions[extension].append('foo')
  983. self.assertEqual(['foo'], extendee_proto.Extensions[extension])
  984. string_list = extendee_proto.Extensions[extension]
  985. extendee_proto.ClearExtension(extension)
  986. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  987. self.assertTrue(string_list is not extendee_proto.Extensions[extension])
  988. # Shouldn't be allowed to do Extensions[extension] = 'a'
  989. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  990. extension, 'a')
  991. def testTopLevelExtensionsForOptionalMessage(self):
  992. extendee_proto = unittest_pb2.TestAllExtensions()
  993. extension = unittest_pb2.optional_foreign_message_extension
  994. self.assertTrue(not extendee_proto.HasExtension(extension))
  995. self.assertEqual(0, extendee_proto.Extensions[extension].c)
  996. # As with normal (non-extension) fields, merely reading from the
  997. # thing shouldn't set the "has" bit.
  998. self.assertTrue(not extendee_proto.HasExtension(extension))
  999. extendee_proto.Extensions[extension].c = 23
  1000. self.assertEqual(23, extendee_proto.Extensions[extension].c)
  1001. self.assertTrue(extendee_proto.HasExtension(extension))
  1002. # Save a reference here.
  1003. foreign_message = extendee_proto.Extensions[extension]
  1004. extendee_proto.ClearExtension(extension)
  1005. self.assertTrue(foreign_message is not extendee_proto.Extensions[extension])
  1006. # Setting a field on foreign_message now shouldn't set
  1007. # any "has" bits on extendee_proto.
  1008. foreign_message.c = 42
  1009. self.assertEqual(42, foreign_message.c)
  1010. self.assertTrue(foreign_message.HasField('c'))
  1011. self.assertTrue(not extendee_proto.HasExtension(extension))
  1012. # Shouldn't be allowed to do Extensions[extension] = 'a'
  1013. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  1014. extension, 'a')
  1015. def testTopLevelExtensionsForRepeatedMessage(self):
  1016. extendee_proto = unittest_pb2.TestAllExtensions()
  1017. extension = unittest_pb2.repeatedgroup_extension
  1018. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  1019. group = extendee_proto.Extensions[extension].add()
  1020. group.a = 23
  1021. self.assertEqual(23, extendee_proto.Extensions[extension][0].a)
  1022. group.a = 42
  1023. self.assertEqual(42, extendee_proto.Extensions[extension][0].a)
  1024. group_list = extendee_proto.Extensions[extension]
  1025. extendee_proto.ClearExtension(extension)
  1026. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  1027. self.assertTrue(group_list is not extendee_proto.Extensions[extension])
  1028. # Shouldn't be allowed to do Extensions[extension] = 'a'
  1029. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  1030. extension, 'a')
  1031. def testNestedExtensions(self):
  1032. extendee_proto = unittest_pb2.TestAllExtensions()
  1033. extension = unittest_pb2.TestRequired.single
  1034. # We just test the non-repeated case.
  1035. self.assertTrue(not extendee_proto.HasExtension(extension))
  1036. required = extendee_proto.Extensions[extension]
  1037. self.assertEqual(0, required.a)
  1038. self.assertTrue(not extendee_proto.HasExtension(extension))
  1039. required.a = 23
  1040. self.assertEqual(23, extendee_proto.Extensions[extension].a)
  1041. self.assertTrue(extendee_proto.HasExtension(extension))
  1042. extendee_proto.ClearExtension(extension)
  1043. self.assertTrue(required is not extendee_proto.Extensions[extension])
  1044. self.assertTrue(not extendee_proto.HasExtension(extension))
  1045. def testRegisteredExtensions(self):
  1046. self.assertTrue('protobuf_unittest.optional_int32_extension' in
  1047. unittest_pb2.TestAllExtensions._extensions_by_name)
  1048. self.assertTrue(1 in unittest_pb2.TestAllExtensions._extensions_by_number)
  1049. # Make sure extensions haven't been registered into types that shouldn't
  1050. # have any.
  1051. self.assertEqual(0, len(unittest_pb2.TestAllTypes._extensions_by_name))
  1052. # If message A directly contains message B, and
  1053. # a.HasField('b') is currently False, then mutating any
  1054. # extension in B should change a.HasField('b') to True
  1055. # (and so on up the object tree).
  1056. def testHasBitsForAncestorsOfExtendedMessage(self):
  1057. # Optional scalar extension.
  1058. toplevel = more_extensions_pb2.TopLevelMessage()
  1059. self.assertTrue(not toplevel.HasField('submessage'))
  1060. self.assertEqual(0, toplevel.submessage.Extensions[
  1061. more_extensions_pb2.optional_int_extension])
  1062. self.assertTrue(not toplevel.HasField('submessage'))
  1063. toplevel.submessage.Extensions[
  1064. more_extensions_pb2.optional_int_extension] = 23
  1065. self.assertEqual(23, toplevel.submessage.Extensions[
  1066. more_extensions_pb2.optional_int_extension])
  1067. self.assertTrue(toplevel.HasField('submessage'))
  1068. # Repeated scalar extension.
  1069. toplevel = more_extensions_pb2.TopLevelMessage()
  1070. self.assertTrue(not toplevel.HasField('submessage'))
  1071. self.assertEqual([], toplevel.submessage.Extensions[
  1072. more_extensions_pb2.repeated_int_extension])
  1073. self.assertTrue(not toplevel.HasField('submessage'))
  1074. toplevel.submessage.Extensions[
  1075. more_extensions_pb2.repeated_int_extension].append(23)
  1076. self.assertEqual([23], toplevel.submessage.Extensions[
  1077. more_extensions_pb2.repeated_int_extension])
  1078. self.assertTrue(toplevel.HasField('submessage'))
  1079. # Optional message extension.
  1080. toplevel = more_extensions_pb2.TopLevelMessage()
  1081. self.assertTrue(not toplevel.HasField('submessage'))
  1082. self.assertEqual(0, toplevel.submessage.Extensions[
  1083. more_extensions_pb2.optional_message_extension].foreign_message_int)
  1084. self.assertTrue(not toplevel.HasField('submessage'))
  1085. toplevel.submessage.Extensions[
  1086. more_extensions_pb2.optional_message_extension].foreign_message_int = 23
  1087. self.assertEqual(23, toplevel.submessage.Extensions[
  1088. more_extensions_pb2.optional_message_extension].foreign_message_int)
  1089. self.assertTrue(toplevel.HasField('submessage'))
  1090. # Repeated message extension.
  1091. toplevel = more_extensions_pb2.TopLevelMessage()
  1092. self.assertTrue(not toplevel.HasField('submessage'))
  1093. self.assertEqual(0, len(toplevel.submessage.Extensions[
  1094. more_extensions_pb2.repeated_message_extension]))
  1095. self.assertTrue(not toplevel.HasField('submessage'))
  1096. foreign = toplevel.submessage.Extensions[
  1097. more_extensions_pb2.repeated_message_extension].add()
  1098. self.assertEqual(foreign, toplevel.submessage.Extensions[
  1099. more_extensions_pb2.repeated_message_extension][0])
  1100. self.assertTrue(toplevel.HasField('submessage'))
  1101. def testDisconnectionAfterClearingEmptyMessage(self):
  1102. toplevel = more_extensions_pb2.TopLevelMessage()
  1103. extendee_proto = toplevel.submessage
  1104. extension = more_extensions_pb2.optional_message_extension
  1105. extension_proto = extendee_proto.Extensions[extension]
  1106. extendee_proto.ClearExtension(extension)
  1107. extension_proto.foreign_message_int = 23
  1108. self.assertTrue(extension_proto is not extendee_proto.Extensions[extension])
  1109. def testExtensionFailureModes(self):
  1110. extendee_proto = unittest_pb2.TestAllExtensions()
  1111. # Try non-extension-handle arguments to HasExtension,
  1112. # ClearExtension(), and Extensions[]...
  1113. self.assertRaises(KeyError, extendee_proto.HasExtension, 1234)
  1114. self.assertRaises(KeyError, extendee_proto.ClearExtension, 1234)
  1115. self.assertRaises(KeyError, extendee_proto.Extensions.__getitem__, 1234)
  1116. self.assertRaises(KeyError, extendee_proto.Extensions.__setitem__, 1234, 5)
  1117. # Try something that *is* an extension handle, just not for
  1118. # this message...
  1119. for unknown_handle in (more_extensions_pb2.optional_int_extension,
  1120. more_extensions_pb2.optional_message_extension,
  1121. more_extensions_pb2.repeated_int_extension,
  1122. more_extensions_pb2.repeated_message_extension):
  1123. self.assertRaises(KeyError, extendee_proto.HasExtension,
  1124. unknown_handle)
  1125. self.assertRaises(KeyError, extendee_proto.ClearExtension,
  1126. unknown_handle)
  1127. self.assertRaises(KeyError, extendee_proto.Extensions.__getitem__,
  1128. unknown_handle)
  1129. self.assertRaises(KeyError, extendee_proto.Extensions.__setitem__,
  1130. unknown_handle, 5)
  1131. # Try call HasExtension() with a valid handle, but for a
  1132. # *repeated* field. (Just as with non-extension repeated
  1133. # fields, Has*() isn't supported for extension repeated fields).
  1134. self.assertRaises(KeyError, extendee_proto.HasExtension,
  1135. unittest_pb2.repeated_string_extension)
  1136. def testStaticParseFrom(self):
  1137. proto1 = unittest_pb2.TestAllTypes()
  1138. test_util.SetAllFields(proto1)
  1139. string1 = proto1.SerializeToString()
  1140. proto2 = unittest_pb2.TestAllTypes.FromString(string1)
  1141. # Messages should be equal.
  1142. self.assertEqual(proto2, proto1)
  1143. def testMergeFromSingularField(self):
  1144. # Test merge with just a singular field.
  1145. proto1 = unittest_pb2.TestAllTypes()
  1146. proto1.optional_int32 = 1
  1147. proto2 = unittest_pb2.TestAllTypes()
  1148. # This shouldn't get overwritten.
  1149. proto2.optional_string = 'value'
  1150. proto2.MergeFrom(proto1)
  1151. self.assertEqual(1, proto2.optional_int32)
  1152. self.assertEqual('value', proto2.optional_string)
  1153. def testMergeFromRepeatedField(self):
  1154. # Test merge with just a repeated field.
  1155. proto1 = unittest_pb2.TestAllTypes()
  1156. proto1.repeated_int32.append(1)
  1157. proto1.repeated_int32.append(2)
  1158. proto2 = unittest_pb2.TestAllTypes()
  1159. proto2.repeated_int32.append(0)
  1160. proto2.MergeFrom(proto1)
  1161. self.assertEqual(0, proto2.repeated_int32[0])
  1162. self.assertEqual(1, proto2.repeated_int32[1])
  1163. self.assertEqual(2, proto2.repeated_int32[2])
  1164. def testMergeFromOptionalGroup(self):
  1165. # Test merge with an optional group.
  1166. proto1 = unittest_pb2.TestAllTypes()
  1167. proto1.optionalgroup.a = 12
  1168. proto2 = unittest_pb2.TestAllTypes()
  1169. proto2.MergeFrom(proto1)
  1170. self.assertEqual(12, proto2.optionalgroup.a)
  1171. def testMergeFromRepeatedNestedMessage(self):
  1172. # Test merge with a repeated nested message.
  1173. proto1 = unittest_pb2.TestAllTypes()
  1174. m = proto1.repeated_nested_message.add()
  1175. m.bb = 123
  1176. m = proto1.repeated_nested_message.add()
  1177. m.bb = 321
  1178. proto2 = unittest_pb2.TestAllTypes()
  1179. m = proto2.repeated_nested_message.add()
  1180. m.bb = 999
  1181. proto2.MergeFrom(proto1)
  1182. self.assertEqual(999, proto2.repeated_nested_message[0].bb)
  1183. self.assertEqual(123, proto2.repeated_nested_message[1].bb)
  1184. self.assertEqual(321, proto2.repeated_nested_message[2].bb)
  1185. proto3 = unittest_pb2.TestAllTypes()
  1186. proto3.repeated_nested_message.MergeFrom(proto2.repeated_nested_message)
  1187. self.assertEqual(999, proto3.repeated_nested_message[0].bb)
  1188. self.assertEqual(123, proto3.repeated_nested_message[1].bb)
  1189. self.assertEqual(321, proto3.repeated_nested_message[2].bb)
  1190. def testMergeFromAllFields(self):
  1191. # With all fields set.
  1192. proto1 = unittest_pb2.TestAllTypes()
  1193. test_util.SetAllFields(proto1)
  1194. proto2 = unittest_pb2.TestAllTypes()
  1195. proto2.MergeFrom(proto1)
  1196. # Messages should be equal.
  1197. self.assertEqual(proto2, proto1)
  1198. # Serialized string should be equal too.
  1199. string1 = proto1.SerializeToString()
  1200. string2 = proto2.SerializeToString()
  1201. self.assertEqual(string1, string2)
  1202. def testMergeFromExtensionsSingular(self):
  1203. proto1 = unittest_pb2.TestAllExtensions()
  1204. proto1.Extensions[unittest_pb2.optional_int32_extension] = 1
  1205. proto2 = unittest_pb2.TestAllExtensions()
  1206. proto2.MergeFrom(proto1)
  1207. self.assertEqual(
  1208. 1, proto2.Extensions[unittest_pb2.optional_int32_extension])
  1209. def testMergeFromExtensionsRepeated(self):
  1210. proto1 = unittest_pb2.TestAllExtensions()
  1211. proto1.Extensions[unittest_pb2.repeated_int32_extension].append(1)
  1212. proto1.Extensions[unittest_pb2.repeated_int32_extension].append(2)
  1213. proto2 = unittest_pb2.TestAllExtensions()
  1214. proto2.Extensions[unittest_pb2.repeated_int32_extension].append(0)
  1215. proto2.MergeFrom(proto1)
  1216. self.assertEqual(
  1217. 3, len(proto2.Extensions[unittest_pb2.repeated_int32_extension]))
  1218. self.assertEqual(
  1219. 0, proto2.Extensions[unittest_pb2.repeated_int32_extension][0])
  1220. self.assertEqual(
  1221. 1, proto2.Extensions[unittest_pb2.repeated_int32_extension][1])
  1222. self.assertEqual(
  1223. 2, proto2.Extensions[unittest_pb2.repeated_int32_extension][2])
  1224. def testMergeFromExtensionsNestedMessage(self):
  1225. proto1 = unittest_pb2.TestAllExtensions()
  1226. ext1 = proto1.Extensions[
  1227. unittest_pb2.repeated_nested_message_extension]
  1228. m = ext1.add()
  1229. m.bb = 222
  1230. m = ext1.add()
  1231. m.bb = 333
  1232. proto2 = unittest_pb2.TestAllExtensions()
  1233. ext2 = proto2.Extensions[
  1234. unittest_pb2.repeated_nested_message_extension]
  1235. m = ext2.add()
  1236. m.bb = 111
  1237. proto2.MergeFrom(proto1)
  1238. ext2 = proto2.Extensions[
  1239. unittest_pb2.repeated_nested_message_extension]
  1240. self.assertEqual(3, len(ext2))
  1241. self.assertEqual(111, ext2[0].bb)
  1242. self.assertEqual(222, ext2[1].bb)
  1243. self.assertEqual(333, ext2[2].bb)
  1244. def testMergeFromBug(self):
  1245. message1 = unittest_pb2.TestAllTypes()
  1246. message2 = unittest_pb2.TestAllTypes()
  1247. # Cause optional_nested_message to be instantiated within message1, even
  1248. # though it is not considered to be "present".
  1249. message1.optional_nested_message
  1250. self.assertFalse(message1.HasField('optional_nested_message'))
  1251. # Merge into message2. This should not instantiate the field is message2.
  1252. message2.MergeFrom(message1)
  1253. self.assertFalse(message2.HasField('optional_nested_message'))
  1254. def testCopyFromSingularField(self):
  1255. # Test copy with just a singular field.
  1256. proto1 = unittest_pb2.TestAllTypes()
  1257. proto1.optional_int32 = 1
  1258. proto1.optional_string = 'important-text'
  1259. proto2 = unittest_pb2.TestAllTypes()
  1260. proto2.optional_string = 'value'
  1261. proto2.CopyFrom(proto1)
  1262. self.assertEqual(1, proto2.optional_int32)
  1263. self.assertEqual('important-text', proto2.optional_string)
  1264. def testCopyFromRepeatedField(self):
  1265. # Test copy with a repeated field.
  1266. proto1 = unittest_pb2.TestAllTypes()
  1267. proto1.repeated_int32.append(1)
  1268. proto1.repeated_int32.append(2)
  1269. proto2 = unittest_pb2.TestAllTypes()
  1270. proto2.repeated_int32.append(0)
  1271. proto2.CopyFrom(proto1)
  1272. self.assertEqual(1, proto2.repeated_int32[0])
  1273. self.assertEqual(2, proto2.repeated_int32[1])
  1274. def testCopyFromAllFields(self):
  1275. # With all fields set.
  1276. proto1 = unittest_pb2.TestAllTypes()
  1277. test_util.SetAllFields(proto1)
  1278. proto2 = unittest_pb2.TestAllTypes()
  1279. proto2.CopyFrom(proto1)
  1280. # Messages should be equal.
  1281. self.assertEqual(proto2, proto1)
  1282. # Serialized string should be equal too.
  1283. string1 = proto1.SerializeToString()
  1284. string2 = proto2.SerializeToString()
  1285. self.assertEqual(string1, string2)
  1286. def testCopyFromSelf(self):
  1287. proto1 = unittest_pb2.TestAllTypes()
  1288. proto1.repeated_int32.append(1)
  1289. proto1.optional_int32 = 2
  1290. proto1.optional_string = 'important-text'
  1291. proto1.CopyFrom(proto1)
  1292. self.assertEqual(1, proto1.repeated_int32[0])
  1293. self.assertEqual(2, proto1.optional_int32)
  1294. self.assertEqual('important-text', proto1.optional_string)
  1295. def testCopyFromBadType(self):
  1296. # The python implementation doesn't raise an exception in this
  1297. # case. In theory it should.
  1298. if api_implementation.Type() == 'python':
  1299. return
  1300. proto1 = unittest_pb2.TestAllTypes()
  1301. proto2 = unittest_pb2.TestAllExtensions()
  1302. self.assertRaises(TypeError, proto1.CopyFrom, proto2)
  1303. def testDeepCopy(self):
  1304. proto1 = unittest_pb2.TestAllTypes()
  1305. proto1.optional_int32 = 1
  1306. proto2 = copy.deepcopy(proto1)
  1307. self.assertEqual(1, proto2.optional_int32)
  1308. proto1.repeated_int32.append(2)
  1309. proto1.repeated_int32.append(3)
  1310. container = copy.deepcopy(proto1.repeated_int32)
  1311. self.assertEqual([2, 3], container)
  1312. # TODO(anuraag): Implement deepcopy for repeated composite / extension dict
  1313. def testClear(self):
  1314. proto = unittest_pb2.TestAllTypes()
  1315. # C++ implementation does not support lazy fields right now so leave it
  1316. # out for now.
  1317. if api_implementation.Type() == 'python':
  1318. test_util.SetAllFields(proto)
  1319. else:
  1320. test_util.SetAllNonLazyFields(proto)
  1321. # Clear the message.
  1322. proto.Clear()
  1323. self.assertEqual(proto.ByteSize(), 0)
  1324. empty_proto = unittest_pb2.TestAllTypes()
  1325. self.assertEqual(proto, empty_proto)
  1326. # Test if extensions which were set are cleared.
  1327. proto = unittest_pb2.TestAllExtensions()
  1328. test_util.SetAllExtensions(proto)
  1329. # Clear the message.
  1330. proto.Clear()
  1331. self.assertEqual(proto.ByteSize(), 0)
  1332. empty_proto = unittest_pb2.TestAllExtensions()
  1333. self.assertEqual(proto, empty_proto)
  1334. def testDisconnectingBeforeClear(self):
  1335. proto = unittest_pb2.TestAllTypes()
  1336. nested = proto.optional_nested_message
  1337. proto.Clear()
  1338. self.assertTrue(nested is not proto.optional_nested_message)
  1339. nested.bb = 23
  1340. self.assertTrue(not proto.HasField('optional_nested_message'))
  1341. self.assertEqual(0, proto.optional_nested_message.bb)
  1342. proto = unittest_pb2.TestAllTypes()
  1343. nested = proto.optional_nested_message
  1344. nested.bb = 5
  1345. foreign = proto.optional_foreign_message
  1346. foreign.c = 6
  1347. proto.Clear()
  1348. self.assertTrue(nested is not proto.optional_nested_message)
  1349. self.assertTrue(foreign is not proto.optional_foreign_message)
  1350. self.assertEqual(5, nested.bb)
  1351. self.assertEqual(6, foreign.c)
  1352. nested.bb = 15
  1353. foreign.c = 16
  1354. self.assertFalse(proto.HasField('optional_nested_message'))
  1355. self.assertEqual(0, proto.optional_nested_message.bb)
  1356. self.assertFalse(proto.HasField('optional_foreign_message'))
  1357. self.assertEqual(0, proto.optional_foreign_message.c)
  1358. def testOneOf(self):
  1359. proto = unittest_pb2.TestAllTypes()
  1360. proto.oneof_uint32 = 10
  1361. proto.oneof_nested_message.bb = 11
  1362. self.assertEqual(11, proto.oneof_nested_message.bb)
  1363. self.assertFalse(proto.HasField('oneof_uint32'))
  1364. nested = proto.oneof_nested_message
  1365. proto.oneof_string = 'abc'
  1366. self.assertEqual('abc', proto.oneof_string)
  1367. self.assertEqual(11, nested.bb)
  1368. self.assertFalse(proto.HasField('oneof_nested_message'))
  1369. def assertInitialized(self, proto):
  1370. self.assertTrue(proto.IsInitialized())
  1371. # Neither method should raise an exception.
  1372. proto.SerializeToString()
  1373. proto.SerializePartialToString()
  1374. def assertNotInitialized(self, proto):
  1375. self.assertFalse(proto.IsInitialized())
  1376. self.assertRaises(message.EncodeError, proto.SerializeToString)
  1377. # "Partial" serialization doesn't care if message is uninitialized.
  1378. proto.SerializePartialToString()
  1379. def testIsInitialized(self):
  1380. # Trivial cases - all optional fields and extensions.
  1381. proto = unittest_pb2.TestAllTypes()
  1382. self.assertInitialized(proto)
  1383. proto = unittest_pb2.TestAllExtensions()
  1384. self.assertInitialized(proto)
  1385. # The case of uninitialized required fields.
  1386. proto = unittest_pb2.TestRequired()
  1387. self.assertNotInitialized(proto)
  1388. proto.a = proto.b = proto.c = 2
  1389. self.assertInitialized(proto)
  1390. # The case of uninitialized submessage.
  1391. proto = unittest_pb2.TestRequiredForeign()
  1392. self.assertInitialized(proto)
  1393. proto.optional_message.a = 1
  1394. self.assertNotInitialized(proto)
  1395. proto.optional_message.b = 0
  1396. proto.optional_message.c = 0
  1397. self.assertInitialized(proto)
  1398. # Uninitialized repeated submessage.
  1399. message1 = proto.repeated_message.add()
  1400. self.assertNotInitialized(proto)
  1401. message1.a = message1.b = message1.c = 0
  1402. self.assertInitialized(proto)
  1403. # Uninitialized repeated group in an extension.
  1404. proto = unittest_pb2.TestAllExtensions()
  1405. extension = unittest_pb2.TestRequired.multi
  1406. message1 = proto.Extensions[extension].add()
  1407. message2 = proto.Extensions[extension].add()
  1408. self.assertNotInitialized(proto)
  1409. message1.a = 1
  1410. message1.b = 1
  1411. message1.c = 1
  1412. self.assertNotInitialized(proto)
  1413. message2.a = 2
  1414. message2.b = 2
  1415. message2.c = 2
  1416. self.assertInitialized(proto)
  1417. # Uninitialized nonrepeated message in an extension.
  1418. proto = unittest_pb2.TestAllExtensions()
  1419. extension = unittest_pb2.TestRequired.single
  1420. proto.Extensions[extension].a = 1
  1421. self.assertNotInitialized(proto)
  1422. proto.Extensions[extension].b = 2
  1423. proto.Extensions[extension].c = 3
  1424. self.assertInitialized(proto)
  1425. # Try passing an errors list.
  1426. errors = []
  1427. proto = unittest_pb2.TestRequired()
  1428. self.assertFalse(proto.IsInitialized(errors))
  1429. self.assertEqual(errors, ['a', 'b', 'c'])
  1430. @skipIf(
  1431. api_implementation.Type() != 'cpp' or api_implementation.Version() != 2,
  1432. 'Errors are only available from the most recent C++ implementation.')
  1433. def testFileDescriptorErrors(self):
  1434. file_name = 'test_file_descriptor_errors.proto'
  1435. package_name = 'test_file_descriptor_errors.proto'
  1436. file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
  1437. file_descriptor_proto.name = file_name
  1438. file_descriptor_proto.package = package_name
  1439. m1 = file_descriptor_proto.message_type.add()
  1440. m1.name = 'msg1'
  1441. # Compiles the proto into the C++ descriptor pool
  1442. descriptor.FileDescriptor(
  1443. file_name,
  1444. package_name,
  1445. serialized_pb=file_descriptor_proto.SerializeToString())
  1446. # Add a FileDescriptorProto that has duplicate symbols
  1447. another_file_name = 'another_test_file_descriptor_errors.proto'
  1448. file_descriptor_proto.name = another_file_name
  1449. m2 = file_descriptor_proto.message_type.add()
  1450. m2.name = 'msg2'
  1451. try:
  1452. descriptor.FileDescriptor(
  1453. another_file_name,
  1454. package_name,
  1455. serialized_pb=file_descriptor_proto.SerializeToString())
  1456. except TypeError as e:
  1457. message = str(e)
  1458. else:
  1459. self.fail("Did not raise TypeError")
  1460. self.assertTrue('test_file_descriptor_errors.proto' in message)
  1461. def testStringUTF8Encoding(self):
  1462. proto = unittest_pb2.TestAllTypes()
  1463. # Assignment of a unicode object to a field of type 'bytes' is not allowed.
  1464. self.assertRaises(TypeError,
  1465. setattr, proto, 'optional_bytes', u'unicode object')
  1466. # Check that the default value is of python's 'unicode' type.
  1467. self.assertEqual(type(proto.optional_string), six.text_type)
  1468. proto.optional_string = six.text_type('Testing')
  1469. self.assertEqual(proto.optional_string, str('Testing'))
  1470. # Assign a value of type 'str' which can be encoded in UTF-8.
  1471. proto.optional_string = str('Testing')
  1472. self.assertEqual(proto.optional_string, six.text_type('Testing'))
  1473. # Try to assign a 'bytes' object which contains non-UTF-8.
  1474. self.assertRaises(ValueError,
  1475. setattr, proto, 'optional_string', b'a\x80a')
  1476. # No exception: Assign already encoded UTF-8 bytes to a string field.
  1477. utf8_bytes = u'Тест'.encode('utf-8')
  1478. proto.optional_string = utf8_bytes
  1479. # No exception: Assign the a non-ascii unicode object.
  1480. proto.optional_string = u'Тест'
  1481. # No exception thrown (normal str assignment containing ASCII).
  1482. proto.optional_string = 'abc'
  1483. def testStringUTF8Serialization(self):
  1484. proto = unittest_mset_pb2.TestMessageSet()
  1485. extension_message = unittest_mset_pb2.TestMessageSetExtension2
  1486. extension = extension_message.message_set_extension
  1487. test_utf8 = u'Тест'
  1488. test_utf8_bytes = test_utf8.encode('utf-8')
  1489. # 'Test' in another language, using UTF-8 charset.
  1490. proto.Extensions[extension].str = test_utf8
  1491. # Serialize using the MessageSet wire format (this is specified in the
  1492. # .proto file).
  1493. serialized = proto.SerializeToString()
  1494. # Check byte size.
  1495. self.assertEqual(proto.ByteSize(), len(serialized))
  1496. raw = unittest_mset_pb2.RawMessageSet()
  1497. bytes_read = raw.MergeFromString(serialized)
  1498. self.assertEqual(len(serialized), bytes_read)
  1499. message2 = unittest_mset_pb2.TestMessageSetExtension2()
  1500. self.assertEqual(1, len(raw.item))
  1501. # Check that the type_id is the same as the tag ID in the .proto file.
  1502. self.assertEqual(raw.item[0].type_id, 1547769)
  1503. # Check the actual bytes on the wire.
  1504. self.assertTrue(
  1505. raw.item[0].message.endswith(test_utf8_bytes))
  1506. bytes_read = message2.MergeFromString(raw.item[0].message)
  1507. self.assertEqual(len(raw.item[0].message), bytes_read)
  1508. self.assertEqual(type(message2.str), six.text_type)
  1509. self.assertEqual(message2.str, test_utf8)
  1510. # The pure Python API throws an exception on MergeFromString(),
  1511. # if any of the string fields of the message can't be UTF-8 decoded.
  1512. # The C++ implementation of the API has no way to check that on
  1513. # MergeFromString and thus has no way to throw the exception.
  1514. #
  1515. # The pure Python API always returns objects of type 'unicode' (UTF-8
  1516. # encoded), or 'bytes' (in 7 bit ASCII).
  1517. badbytes = raw.item[0].message.replace(
  1518. test_utf8_bytes, len(test_utf8_bytes) * b'\xff')
  1519. unicode_decode_failed = False
  1520. try:
  1521. message2.MergeFromString(badbytes)
  1522. except UnicodeDecodeError:
  1523. unicode_decode_failed = True
  1524. string_field = message2.str
  1525. self.assertTrue(unicode_decode_failed or type(string_field) is bytes)
  1526. def testBytesInTextFormat(self):
  1527. proto = unittest_pb2.TestAllTypes(optional_bytes=b'\x00\x7f\x80\xff')
  1528. self.assertEqual(u'optional_bytes: "\\000\\177\\200\\377"\n',
  1529. six.text_type(proto))
  1530. def testEmptyNestedMessage(self):
  1531. proto = unittest_pb2.TestAllTypes()
  1532. proto.optional_nested_message.MergeFrom(
  1533. unittest_pb2.TestAllTypes.NestedMessage())
  1534. self.assertTrue(proto.HasField('optional_nested_message'))
  1535. proto = unittest_pb2.TestAllTypes()
  1536. proto.optional_nested_message.CopyFrom(
  1537. unittest_pb2.TestAllTypes.NestedMessage())
  1538. self.assertTrue(proto.HasField('optional_nested_message'))
  1539. proto = unittest_pb2.TestAllTypes()
  1540. bytes_read = proto.optional_nested_message.MergeFromString(b'')
  1541. self.assertEqual(0, bytes_read)
  1542. self.assertTrue(proto.HasField('optional_nested_message'))
  1543. proto = unittest_pb2.TestAllTypes()
  1544. proto.optional_nested_message.ParseFromString(b'')
  1545. self.assertTrue(proto.HasField('optional_nested_message'))
  1546. serialized = proto.SerializeToString()
  1547. proto2 = unittest_pb2.TestAllTypes()
  1548. self.assertEqual(
  1549. len(serialized),
  1550. proto2.MergeFromString(serialized))
  1551. self.assertTrue(proto2.HasField('optional_nested_message'))
  1552. def testSetInParent(self):
  1553. proto = unittest_pb2.TestAllTypes()
  1554. self.assertFalse(proto.HasField('optionalgroup'))
  1555. proto.optionalgroup.SetInParent()
  1556. self.assertTrue(proto.HasField('optionalgroup'))
  1557. def testPackageInitializationImport(self):
  1558. """Test that we can import nested messages from their __init__.py.
  1559. Such setup is not trivial since at the time of processing of __init__.py one
  1560. can't refer to its submodules by name in code, so expressions like
  1561. google.protobuf.internal.import_test_package.inner_pb2
  1562. don't work. They do work in imports, so we have assign an alias at import
  1563. and then use that alias in generated code.
  1564. """
  1565. # We import here since it's the import that used to fail, and we want
  1566. # the failure to have the right context.
  1567. # pylint: disable=g-import-not-at-top
  1568. from google.protobuf.internal import import_test_package
  1569. # pylint: enable=g-import-not-at-top
  1570. msg = import_test_package.myproto.Outer()
  1571. # Just check the default value.
  1572. self.assertEqual(57, msg.inner.value)
  1573. # Since we had so many tests for protocol buffer equality, we broke these out
  1574. # into separate TestCase classes.
  1575. class TestAllTypesEqualityTest(unittest.TestCase):
  1576. def setUp(self):
  1577. self.first_proto = unittest_pb2.TestAllTypes()
  1578. self.second_proto = unittest_pb2.TestAllTypes()
  1579. def testNotHashable(self):
  1580. self.assertRaises(TypeError, hash, self.first_proto)
  1581. def testSelfEquality(self):
  1582. self.assertEqual(self.first_proto, self.first_proto)
  1583. def testEmptyProtosEqual(self):
  1584. self.assertEqual(self.first_proto, self.second_proto)
  1585. class FullProtosEqualityTest(unittest.TestCase):
  1586. """Equality tests using completely-full protos as a starting point."""
  1587. def setUp(self):
  1588. self.first_proto = unittest_pb2.TestAllTypes()
  1589. self.second_proto = unittest_pb2.TestAllTypes()
  1590. test_util.SetAllFields(self.first_proto)
  1591. test_util.SetAllFields(self.second_proto)
  1592. def testNotHashable(self):
  1593. self.assertRaises(TypeError, hash, self.first_proto)
  1594. def testNoneNotEqual(self):
  1595. self.assertNotEqual(self.first_proto, None)
  1596. self.assertNotEqual(None, self.second_proto)
  1597. def testNotEqualToOtherMessage(self):
  1598. third_proto = unittest_pb2.TestRequired()
  1599. self.assertNotEqual(self.first_proto, third_proto)
  1600. self.assertNotEqual(third_proto, self.second_proto)
  1601. def testAllFieldsFilledEquality(self):
  1602. self.assertEqual(self.first_proto, self.second_proto)
  1603. def testNonRepeatedScalar(self):
  1604. # Nonrepeated scalar field change should cause inequality.
  1605. self.first_proto.optional_int32 += 1
  1606. self.assertNotEqual(self.first_proto, self.second_proto)
  1607. # ...as should clearing a field.
  1608. self.first_proto.ClearField('optional_int32')
  1609. self.assertNotEqual(self.first_proto, self.second_proto)
  1610. def testNonRepeatedComposite(self):
  1611. # Change a nonrepeated composite field.
  1612. self.first_proto.optional_nested_message.bb += 1
  1613. self.assertNotEqual(self.first_proto, self.second_proto)
  1614. self.first_proto.optional_nested_message.bb -= 1
  1615. self.assertEqual(self.first_proto, self.second_proto)
  1616. # Clear a field in the nested message.
  1617. self.first_proto.optional_nested_message.ClearField('bb')
  1618. self.assertNotEqual(self.first_proto, self.second_proto)
  1619. self.first_proto.optional_nested_message.bb = (
  1620. self.second_proto.optional_nested_message.bb)
  1621. self.assertEqual(self.first_proto, self.second_proto)
  1622. # Remove the nested message entirely.
  1623. self.first_proto.ClearField('optional_nested_message')
  1624. self.assertNotEqual(self.first_proto, self.second_proto)
  1625. def testRepeatedScalar(self):
  1626. # Change a repeated scalar field.
  1627. self.first_proto.repeated_int32.append(5)
  1628. self.assertNotEqual(self.first_proto, self.second_proto)
  1629. self.first_proto.ClearField('repeated_int32')
  1630. self.assertNotEqual(self.first_proto, self.second_proto)
  1631. def testRepeatedComposite(self):
  1632. # Change value within a repeated composite field.
  1633. self.first_proto.repeated_nested_message[0].bb += 1
  1634. self.assertNotEqual(self.first_proto, self.second_proto)
  1635. self.first_proto.repeated_nested_message[0].bb -= 1
  1636. self.assertEqual(self.first_proto, self.second_proto)
  1637. # Add a value to a repeated composite field.
  1638. self.first_proto.repeated_nested_message.add()
  1639. self.assertNotEqual(self.first_proto, self.second_proto)
  1640. self.second_proto.repeated_nested_message.add()
  1641. self.assertEqual(self.first_proto, self.second_proto)
  1642. def testNonRepeatedScalarHasBits(self):
  1643. # Ensure that we test "has" bits as well as value for
  1644. # nonrepeated scalar field.
  1645. self.first_proto.ClearField('optional_int32')
  1646. self.second_proto.optional_int32 = 0
  1647. self.assertNotEqual(self.first_proto, self.second_proto)
  1648. def testNonRepeatedCompositeHasBits(self):
  1649. # Ensure that we test "has" bits as well as value for
  1650. # nonrepeated composite field.
  1651. self.first_proto.ClearField('optional_nested_message')
  1652. self.second_proto.optional_nested_message.ClearField('bb')
  1653. self.assertNotEqual(self.first_proto, self.second_proto)
  1654. self.first_proto.optional_nested_message.bb = 0
  1655. self.first_proto.optional_nested_message.ClearField('bb')
  1656. self.assertEqual(self.first_proto, self.second_proto)
  1657. class ExtensionEqualityTest(unittest.TestCase):
  1658. def testExtensionEquality(self):
  1659. first_proto = unittest_pb2.TestAllExtensions()
  1660. second_proto = unittest_pb2.TestAllExtensions()
  1661. self.assertEqual(first_proto, second_proto)
  1662. test_util.SetAllExtensions(first_proto)
  1663. self.assertNotEqual(first_proto, second_proto)
  1664. test_util.SetAllExtensions(second_proto)
  1665. self.assertEqual(first_proto, second_proto)
  1666. # Ensure that we check value equality.
  1667. first_proto.Extensions[unittest_pb2.optional_int32_extension] += 1
  1668. self.assertNotEqual(first_proto, second_proto)
  1669. first_proto.Extensions[unittest_pb2.optional_int32_extension] -= 1
  1670. self.assertEqual(first_proto, second_proto)
  1671. # Ensure that we also look at "has" bits.
  1672. first_proto.ClearExtension(unittest_pb2.optional_int32_extension)
  1673. second_proto.Extensions[unittest_pb2.optional_int32_extension] = 0
  1674. self.assertNotEqual(first_proto, second_proto)
  1675. first_proto.Extensions[unittest_pb2.optional_int32_extension] = 0
  1676. self.assertEqual(first_proto, second_proto)
  1677. # Ensure that differences in cached values
  1678. # don't matter if "has" bits are both false.
  1679. first_proto = unittest_pb2.TestAllExtensions()
  1680. second_proto = unittest_pb2.TestAllExtensions()
  1681. self.assertEqual(
  1682. 0, first_proto.Extensions[unittest_pb2.optional_int32_extension])
  1683. self.assertEqual(first_proto, second_proto)
  1684. class MutualRecursionEqualityTest(unittest.TestCase):
  1685. def testEqualityWithMutualRecursion(self):
  1686. first_proto = unittest_pb2.TestMutualRecursionA()
  1687. second_proto = unittest_pb2.TestMutualRecursionA()
  1688. self.assertEqual(first_proto, second_proto)
  1689. first_proto.bb.a.bb.optional_int32 = 23
  1690. self.assertNotEqual(first_proto, second_proto)
  1691. second_proto.bb.a.bb.optional_int32 = 23
  1692. self.assertEqual(first_proto, second_proto)
  1693. class ByteSizeTest(unittest.TestCase):
  1694. def setUp(self):
  1695. self.proto = unittest_pb2.TestAllTypes()
  1696. self.extended_proto = more_extensions_pb2.ExtendedMessage()
  1697. self.packed_proto = unittest_pb2.TestPackedTypes()
  1698. self.packed_extended_proto = unittest_pb2.TestPackedExtensions()
  1699. def Size(self):
  1700. return self.proto.ByteSize()
  1701. def testEmptyMessage(self):
  1702. self.assertEqual(0, self.proto.ByteSize())
  1703. def testSizedOnKwargs(self):
  1704. # Use a separate message to ensure testing right after creation.
  1705. proto = unittest_pb2.TestAllTypes()
  1706. self.assertEqual(0, proto.ByteSize())
  1707. proto_kwargs = unittest_pb2.TestAllTypes(optional_int64 = 1)
  1708. # One byte for the tag, one to encode varint 1.
  1709. self.assertEqual(2, proto_kwargs.ByteSize())
  1710. def testVarints(self):
  1711. def Test(i, expected_varint_size):
  1712. self.proto.Clear()
  1713. self.proto.optional_int64 = i
  1714. # Add one to the varint size for the tag info
  1715. # for tag 1.
  1716. self.assertEqual(expected_varint_size + 1, self.Size())
  1717. Test(0, 1)
  1718. Test(1, 1)
  1719. for i, num_bytes in zip(range(7, 63, 7), range(1, 10000)):
  1720. Test((1 << i) - 1, num_bytes)
  1721. Test(-1, 10)
  1722. Test(-2, 10)
  1723. Test(-(1 << 63), 10)
  1724. def testStrings(self):
  1725. self.proto.optional_string = ''
  1726. # Need one byte for tag info (tag #14), and one byte for length.
  1727. self.assertEqual(2, self.Size())
  1728. self.proto.optional_string = 'abc'
  1729. # Need one byte for tag info (tag #14), and one byte for length.
  1730. self.assertEqual(2 + len(self.proto.optional_string), self.Size())
  1731. self.proto.optional_string = 'x' * 128
  1732. # Need one byte for tag info (tag #14), and TWO bytes for length.
  1733. self.assertEqual(3 + len(self.proto.optional_string), self.Size())
  1734. def testOtherNumerics(self):
  1735. self.proto.optional_fixed32 = 1234
  1736. # One byte for tag and 4 bytes for fixed32.
  1737. self.assertEqual(5, self.Size())
  1738. self.proto = unittest_pb2.TestAllTypes()
  1739. self.proto.optional_fixed64 = 1234
  1740. # One byte for tag and 8 bytes for fixed64.
  1741. self.assertEqual(9, self.Size())
  1742. self.proto = unittest_pb2.TestAllTypes()
  1743. self.proto.optional_float = 1.234
  1744. # One byte for tag and 4 bytes for float.
  1745. self.assertEqual(5, self.Size())
  1746. self.proto = unittest_pb2.TestAllTypes()
  1747. self.proto.optional_double = 1.234
  1748. # One byte for tag and 8 bytes for float.
  1749. self.assertEqual(9, self.Size())
  1750. self.proto = unittest_pb2.TestAllTypes()
  1751. self.proto.optional_sint32 = 64
  1752. # One byte for tag and 2 bytes for zig-zag-encoded 64.
  1753. self.assertEqual(3, self.Size())
  1754. self.proto = unittest_pb2.TestAllTypes()
  1755. def testComposites(self):
  1756. # 3 bytes.
  1757. self.proto.optional_nested_message.bb = (1 << 14)
  1758. # Plus one byte for bb tag.
  1759. # Plus 1 byte for optional_nested_message serialized size.
  1760. # Plus two bytes for optional_nested_message tag.
  1761. self.assertEqual(3 + 1 + 1 + 2, self.Size())
  1762. def testGroups(self):
  1763. # 4 bytes.
  1764. self.proto.optionalgroup.a = (1 << 21)
  1765. # Plus two bytes for |a| tag.
  1766. # Plus 2 * two bytes for START_GROUP and END_GROUP tags.
  1767. self.assertEqual(4 + 2 + 2*2, self.Size())
  1768. def testRepeatedScalars(self):
  1769. self.proto.repeated_int32.append(10) # 1 byte.
  1770. self.proto.repeated_int32.append(128) # 2 bytes.
  1771. # Also need 2 bytes for each entry for tag.
  1772. self.assertEqual(1 + 2 + 2*2, self.Size())
  1773. def testRepeatedScalarsExtend(self):
  1774. self.proto.repeated_int32.extend([10, 128]) # 3 bytes.
  1775. # Also need 2 bytes for each entry for tag.
  1776. self.assertEqual(1 + 2 + 2*2, self.Size())
  1777. def testRepeatedScalarsRemove(self):
  1778. self.proto.repeated_int32.append(10) # 1 byte.
  1779. self.proto.repeated_int32.append(128) # 2 bytes.
  1780. # Also need 2 bytes for each entry for tag.
  1781. self.assertEqual(1 + 2 + 2*2, self.Size())
  1782. self.proto.repeated_int32.remove(128)
  1783. self.assertEqual(1 + 2, self.Size())
  1784. def testRepeatedComposites(self):
  1785. # Empty message. 2 bytes tag plus 1 byte length.
  1786. foreign_message_0 = self.proto.repeated_nested_message.add()
  1787. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1788. foreign_message_1 = self.proto.repeated_nested_message.add()
  1789. foreign_message_1.bb = 7
  1790. self.assertEqual(2 + 1 + 2 + 1 + 1 + 1, self.Size())
  1791. def testRepeatedCompositesDelete(self):
  1792. # Empty message. 2 bytes tag plus 1 byte length.
  1793. foreign_message_0 = self.proto.repeated_nested_message.add()
  1794. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1795. foreign_message_1 = self.proto.repeated_nested_message.add()
  1796. foreign_message_1.bb = 9
  1797. self.assertEqual(2 + 1 + 2 + 1 + 1 + 1, self.Size())
  1798. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1799. del self.proto.repeated_nested_message[0]
  1800. self.assertEqual(2 + 1 + 1 + 1, self.Size())
  1801. # Now add a new message.
  1802. foreign_message_2 = self.proto.repeated_nested_message.add()
  1803. foreign_message_2.bb = 12
  1804. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1805. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1806. self.assertEqual(2 + 1 + 1 + 1 + 2 + 1 + 1 + 1, self.Size())
  1807. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int.
  1808. del self.proto.repeated_nested_message[1]
  1809. self.assertEqual(2 + 1 + 1 + 1, self.Size())
  1810. del self.proto.repeated_nested_message[0]
  1811. self.assertEqual(0, self.Size())
  1812. def testRepeatedGroups(self):
  1813. # 2-byte START_GROUP plus 2-byte END_GROUP.
  1814. group_0 = self.proto.repeatedgroup.add()
  1815. # 2-byte START_GROUP plus 2-byte |a| tag + 1-byte |a|
  1816. # plus 2-byte END_GROUP.
  1817. group_1 = self.proto.repeatedgroup.add()
  1818. group_1.a = 7
  1819. self.assertEqual(2 + 2 + 2 + 2 + 1 + 2, self.Size())
  1820. def testExtensions(self):
  1821. proto = unittest_pb2.TestAllExtensions()
  1822. self.assertEqual(0, proto.ByteSize())
  1823. extension = unittest_pb2.optional_int32_extension # Field #1, 1 byte.
  1824. proto.Extensions[extension] = 23
  1825. # 1 byte for tag, 1 byte for value.
  1826. self.assertEqual(2, proto.ByteSize())
  1827. def testCacheInvalidationForNonrepeatedScalar(self):
  1828. # Test non-extension.
  1829. self.proto.optional_int32 = 1
  1830. self.assertEqual(2, self.proto.ByteSize())
  1831. self.proto.optional_int32 = 128
  1832. self.assertEqual(3, self.proto.ByteSize())
  1833. self.proto.ClearField('optional_int32')
  1834. self.assertEqual(0, self.proto.ByteSize())
  1835. # Test within extension.
  1836. extension = more_extensions_pb2.optional_int_extension
  1837. self.extended_proto.Extensions[extension] = 1
  1838. self.assertEqual(2, self.extended_proto.ByteSize())
  1839. self.extended_proto.Extensions[extension] = 128
  1840. self.assertEqual(3, self.extended_proto.ByteSize())
  1841. self.extended_proto.ClearExtension(extension)
  1842. self.assertEqual(0, self.extended_proto.ByteSize())
  1843. def testCacheInvalidationForRepeatedScalar(self):
  1844. # Test non-extension.
  1845. self.proto.repeated_int32.append(1)
  1846. self.assertEqual(3, self.proto.ByteSize())
  1847. self.proto.repeated_int32.append(1)
  1848. self.assertEqual(6, self.proto.ByteSize())
  1849. self.proto.repeated_int32[1] = 128
  1850. self.assertEqual(7, self.proto.ByteSize())
  1851. self.proto.ClearField('repeated_int32')
  1852. self.assertEqual(0, self.proto.ByteSize())
  1853. # Test within extension.
  1854. extension = more_extensions_pb2.repeated_int_extension
  1855. repeated = self.extended_proto.Extensions[extension]
  1856. repeated.append(1)
  1857. self.assertEqual(2, self.extended_proto.ByteSize())
  1858. repeated.append(1)
  1859. self.assertEqual(4, self.extended_proto.ByteSize())
  1860. repeated[1] = 128
  1861. self.assertEqual(5, self.extended_proto.ByteSize())
  1862. self.extended_proto.ClearExtension(extension)
  1863. self.assertEqual(0, self.extended_proto.ByteSize())
  1864. def testCacheInvalidationForNonrepeatedMessage(self):
  1865. # Test non-extension.
  1866. self.proto.optional_foreign_message.c = 1
  1867. self.assertEqual(5, self.proto.ByteSize())
  1868. self.proto.optional_foreign_message.c = 128
  1869. self.assertEqual(6, self.proto.ByteSize())
  1870. self.proto.optional_foreign_message.ClearField('c')
  1871. self.assertEqual(3, self.proto.ByteSize())
  1872. self.proto.ClearField('optional_foreign_message')
  1873. self.assertEqual(0, self.proto.ByteSize())
  1874. if api_implementation.Type() == 'python':
  1875. # This is only possible in pure-Python implementation of the API.
  1876. child = self.proto.optional_foreign_message
  1877. self.proto.ClearField('optional_foreign_message')
  1878. child.c = 128
  1879. self.assertEqual(0, self.proto.ByteSize())
  1880. # Test within extension.
  1881. extension = more_extensions_pb2.optional_message_extension
  1882. child = self.extended_proto.Extensions[extension]
  1883. self.assertEqual(0, self.extended_proto.ByteSize())
  1884. child.foreign_message_int = 1
  1885. self.assertEqual(4, self.extended_proto.ByteSize())
  1886. child.foreign_message_int = 128
  1887. self.assertEqual(5, self.extended_proto.ByteSize())
  1888. self.extended_proto.ClearExtension(extension)
  1889. self.assertEqual(0, self.extended_proto.ByteSize())
  1890. def testCacheInvalidationForRepeatedMessage(self):
  1891. # Test non-extension.
  1892. child0 = self.proto.repeated_foreign_message.add()
  1893. self.assertEqual(3, self.proto.ByteSize())
  1894. self.proto.repeated_foreign_message.add()
  1895. self.assertEqual(6, self.proto.ByteSize())
  1896. child0.c = 1
  1897. self.assertEqual(8, self.proto.ByteSize())
  1898. self.proto.ClearField('repeated_foreign_message')
  1899. self.assertEqual(0, self.proto.ByteSize())
  1900. # Test within extension.
  1901. extension = more_extensions_pb2.repeated_message_extension
  1902. child_list = self.extended_proto.Extensions[extension]
  1903. child0 = child_list.add()
  1904. self.assertEqual(2, self.extended_proto.ByteSize())
  1905. child_list.add()
  1906. self.assertEqual(4, self.extended_proto.ByteSize())
  1907. child0.foreign_message_int = 1
  1908. self.assertEqual(6, self.extended_proto.ByteSize())
  1909. child0.ClearField('foreign_message_int')
  1910. self.assertEqual(4, self.extended_proto.ByteSize())
  1911. self.extended_proto.ClearExtension(extension)
  1912. self.assertEqual(0, self.extended_proto.ByteSize())
  1913. def testPackedRepeatedScalars(self):
  1914. self.assertEqual(0, self.packed_proto.ByteSize())
  1915. self.packed_proto.packed_int32.append(10) # 1 byte.
  1916. self.packed_proto.packed_int32.append(128) # 2 bytes.
  1917. # The tag is 2 bytes (the field number is 90), and the varint
  1918. # storing the length is 1 byte.
  1919. int_size = 1 + 2 + 3
  1920. self.assertEqual(int_size, self.packed_proto.ByteSize())
  1921. self.packed_proto.packed_double.append(4.2) # 8 bytes
  1922. self.packed_proto.packed_double.append(3.25) # 8 bytes
  1923. # 2 more tag bytes, 1 more length byte.
  1924. double_size = 8 + 8 + 3
  1925. self.assertEqual(int_size+double_size, self.packed_proto.ByteSize())
  1926. self.packed_proto.ClearField('packed_int32')
  1927. self.assertEqual(double_size, self.packed_proto.ByteSize())
  1928. def testPackedExtensions(self):
  1929. self.assertEqual(0, self.packed_extended_proto.ByteSize())
  1930. extension = self.packed_extended_proto.Extensions[
  1931. unittest_pb2.packed_fixed32_extension]
  1932. extension.extend([1, 2, 3, 4]) # 16 bytes
  1933. # Tag is 3 bytes.
  1934. self.assertEqual(19, self.packed_extended_proto.ByteSize())
  1935. # Issues to be sure to cover include:
  1936. # * Handling of unrecognized tags ("uninterpreted_bytes").
  1937. # * Handling of MessageSets.
  1938. # * Consistent ordering of tags in the wire format,
  1939. # including ordering between extensions and non-extension
  1940. # fields.
  1941. # * Consistent serialization of negative numbers, especially
  1942. # negative int32s.
  1943. # * Handling of empty submessages (with and without "has"
  1944. # bits set).
  1945. class SerializationTest(unittest.TestCase):
  1946. def testSerializeEmtpyMessage(self):
  1947. first_proto = unittest_pb2.TestAllTypes()
  1948. second_proto = unittest_pb2.TestAllTypes()
  1949. serialized = first_proto.SerializeToString()
  1950. self.assertEqual(first_proto.ByteSize(), len(serialized))
  1951. self.assertEqual(
  1952. len(serialized),
  1953. second_proto.MergeFromString(serialized))
  1954. self.assertEqual(first_proto, second_proto)
  1955. def testSerializeAllFields(self):
  1956. first_proto = unittest_pb2.TestAllTypes()
  1957. second_proto = unittest_pb2.TestAllTypes()
  1958. test_util.SetAllFields(first_proto)
  1959. serialized = first_proto.SerializeToString()
  1960. self.assertEqual(first_proto.ByteSize(), len(serialized))
  1961. self.assertEqual(
  1962. len(serialized),
  1963. second_proto.MergeFromString(serialized))
  1964. self.assertEqual(first_proto, second_proto)
  1965. def testSerializeAllExtensions(self):
  1966. first_proto = unittest_pb2.TestAllExtensions()
  1967. second_proto = unittest_pb2.TestAllExtensions()
  1968. test_util.SetAllExtensions(first_proto)
  1969. serialized = first_proto.SerializeToString()
  1970. self.assertEqual(
  1971. len(serialized),
  1972. second_proto.MergeFromString(serialized))
  1973. self.assertEqual(first_proto, second_proto)
  1974. def testSerializeWithOptionalGroup(self):
  1975. first_proto = unittest_pb2.TestAllTypes()
  1976. second_proto = unittest_pb2.TestAllTypes()
  1977. first_proto.optionalgroup.a = 242
  1978. serialized = first_proto.SerializeToString()
  1979. self.assertEqual(
  1980. len(serialized),
  1981. second_proto.MergeFromString(serialized))
  1982. self.assertEqual(first_proto, second_proto)
  1983. def testSerializeNegativeValues(self):
  1984. first_proto = unittest_pb2.TestAllTypes()
  1985. first_proto.optional_int32 = -1
  1986. first_proto.optional_int64 = -(2 << 40)
  1987. first_proto.optional_sint32 = -3
  1988. first_proto.optional_sint64 = -(4 << 40)
  1989. first_proto.optional_sfixed32 = -5
  1990. first_proto.optional_sfixed64 = -(6 << 40)
  1991. second_proto = unittest_pb2.TestAllTypes.FromString(
  1992. first_proto.SerializeToString())
  1993. self.assertEqual(first_proto, second_proto)
  1994. def testParseTruncated(self):
  1995. # This test is only applicable for the Python implementation of the API.
  1996. if api_implementation.Type() != 'python':
  1997. return
  1998. first_proto = unittest_pb2.TestAllTypes()
  1999. test_util.SetAllFields(first_proto)
  2000. serialized = first_proto.SerializeToString()
  2001. for truncation_point in range(len(serialized) + 1):
  2002. try:
  2003. second_proto = unittest_pb2.TestAllTypes()
  2004. unknown_fields = unittest_pb2.TestEmptyMessage()
  2005. pos = second_proto._InternalParse(serialized, 0, truncation_point)
  2006. # If we didn't raise an error then we read exactly the amount expected.
  2007. self.assertEqual(truncation_point, pos)
  2008. # Parsing to unknown fields should not throw if parsing to known fields
  2009. # did not.
  2010. try:
  2011. pos2 = unknown_fields._InternalParse(serialized, 0, truncation_point)
  2012. self.assertEqual(truncation_point, pos2)
  2013. except message.DecodeError:
  2014. self.fail('Parsing unknown fields failed when parsing known fields '
  2015. 'did not.')
  2016. except message.DecodeError:
  2017. # Parsing unknown fields should also fail.
  2018. self.assertRaises(message.DecodeError, unknown_fields._InternalParse,
  2019. serialized, 0, truncation_point)
  2020. def testCanonicalSerializationOrder(self):
  2021. proto = more_messages_pb2.OutOfOrderFields()
  2022. # These are also their tag numbers. Even though we're setting these in
  2023. # reverse-tag order AND they're listed in reverse tag-order in the .proto
  2024. # file, they should nonetheless be serialized in tag order.
  2025. proto.optional_sint32 = 5
  2026. proto.Extensions[more_messages_pb2.optional_uint64] = 4
  2027. proto.optional_uint32 = 3
  2028. proto.Extensions[more_messages_pb2.optional_int64] = 2
  2029. proto.optional_int32 = 1
  2030. serialized = proto.SerializeToString()
  2031. self.assertEqual(proto.ByteSize(), len(serialized))
  2032. d = _MiniDecoder(serialized)
  2033. ReadTag = d.ReadFieldNumberAndWireType
  2034. self.assertEqual((1, wire_format.WIRETYPE_VARINT), ReadTag())
  2035. self.assertEqual(1, d.ReadInt32())
  2036. self.assertEqual((2, wire_format.WIRETYPE_VARINT), ReadTag())
  2037. self.assertEqual(2, d.ReadInt64())
  2038. self.assertEqual((3, wire_format.WIRETYPE_VARINT), ReadTag())
  2039. self.assertEqual(3, d.ReadUInt32())
  2040. self.assertEqual((4, wire_format.WIRETYPE_VARINT), ReadTag())
  2041. self.assertEqual(4, d.ReadUInt64())
  2042. self.assertEqual((5, wire_format.WIRETYPE_VARINT), ReadTag())
  2043. self.assertEqual(5, d.ReadSInt32())
  2044. def testCanonicalSerializationOrderSameAsCpp(self):
  2045. # Copy of the same test we use for C++.
  2046. proto = unittest_pb2.TestFieldOrderings()
  2047. test_util.SetAllFieldsAndExtensions(proto)
  2048. serialized = proto.SerializeToString()
  2049. test_util.ExpectAllFieldsAndExtensionsInOrder(serialized)
  2050. def testMergeFromStringWhenFieldsAlreadySet(self):
  2051. first_proto = unittest_pb2.TestAllTypes()
  2052. first_proto.repeated_string.append('foobar')
  2053. first_proto.optional_int32 = 23
  2054. first_proto.optional_nested_message.bb = 42
  2055. serialized = first_proto.SerializeToString()
  2056. second_proto = unittest_pb2.TestAllTypes()
  2057. second_proto.repeated_string.append('baz')
  2058. second_proto.optional_int32 = 100
  2059. second_proto.optional_nested_message.bb = 999
  2060. bytes_parsed = second_proto.MergeFromString(serialized)
  2061. self.assertEqual(len(serialized), bytes_parsed)
  2062. # Ensure that we append to repeated fields.
  2063. self.assertEqual(['baz', 'foobar'], list(second_proto.repeated_string))
  2064. # Ensure that we overwrite nonrepeatd scalars.
  2065. self.assertEqual(23, second_proto.optional_int32)
  2066. # Ensure that we recursively call MergeFromString() on
  2067. # submessages.
  2068. self.assertEqual(42, second_proto.optional_nested_message.bb)
  2069. def testMessageSetWireFormat(self):
  2070. proto = unittest_mset_pb2.TestMessageSet()
  2071. extension_message1 = unittest_mset_pb2.TestMessageSetExtension1
  2072. extension_message2 = unittest_mset_pb2.TestMessageSetExtension2
  2073. extension1 = extension_message1.message_set_extension
  2074. extension2 = extension_message2.message_set_extension
  2075. proto.Extensions[extension1].i = 123
  2076. proto.Extensions[extension2].str = 'foo'
  2077. # Serialize using the MessageSet wire format (this is specified in the
  2078. # .proto file).
  2079. serialized = proto.SerializeToString()
  2080. raw = unittest_mset_pb2.RawMessageSet()
  2081. self.assertEqual(False,
  2082. raw.DESCRIPTOR.GetOptions().message_set_wire_format)
  2083. self.assertEqual(
  2084. len(serialized),
  2085. raw.MergeFromString(serialized))
  2086. self.assertEqual(2, len(raw.item))
  2087. message1 = unittest_mset_pb2.TestMessageSetExtension1()
  2088. self.assertEqual(
  2089. len(raw.item[0].message),
  2090. message1.MergeFromString(raw.item[0].message))
  2091. self.assertEqual(123, message1.i)
  2092. message2 = unittest_mset_pb2.TestMessageSetExtension2()
  2093. self.assertEqual(
  2094. len(raw.item[1].message),
  2095. message2.MergeFromString(raw.item[1].message))
  2096. self.assertEqual('foo', message2.str)
  2097. # Deserialize using the MessageSet wire format.
  2098. proto2 = unittest_mset_pb2.TestMessageSet()
  2099. self.assertEqual(
  2100. len(serialized),
  2101. proto2.MergeFromString(serialized))
  2102. self.assertEqual(123, proto2.Extensions[extension1].i)
  2103. self.assertEqual('foo', proto2.Extensions[extension2].str)
  2104. # Check byte size.
  2105. self.assertEqual(proto2.ByteSize(), len(serialized))
  2106. self.assertEqual(proto.ByteSize(), len(serialized))
  2107. def testMessageSetWireFormatUnknownExtension(self):
  2108. # Create a message using the message set wire format with an unknown
  2109. # message.
  2110. raw = unittest_mset_pb2.RawMessageSet()
  2111. # Add an item.
  2112. item = raw.item.add()
  2113. item.type_id = 1545008
  2114. extension_message1 = unittest_mset_pb2.TestMessageSetExtension1
  2115. message1 = unittest_mset_pb2.TestMessageSetExtension1()
  2116. message1.i = 12345
  2117. item.message = message1.SerializeToString()
  2118. # Add a second, unknown extension.
  2119. item = raw.item.add()
  2120. item.type_id = 1545009
  2121. extension_message1 = unittest_mset_pb2.TestMessageSetExtension1
  2122. message1 = unittest_mset_pb2.TestMessageSetExtension1()
  2123. message1.i = 12346
  2124. item.message = message1.SerializeToString()
  2125. # Add another unknown extension.
  2126. item = raw.item.add()
  2127. item.type_id = 1545010
  2128. message1 = unittest_mset_pb2.TestMessageSetExtension2()
  2129. message1.str = 'foo'
  2130. item.message = message1.SerializeToString()
  2131. serialized = raw.SerializeToString()
  2132. # Parse message using the message set wire format.
  2133. proto = unittest_mset_pb2.TestMessageSet()
  2134. self.assertEqual(
  2135. len(serialized),
  2136. proto.MergeFromString(serialized))
  2137. # Check that the message parsed well.
  2138. extension_message1 = unittest_mset_pb2.TestMessageSetExtension1
  2139. extension1 = extension_message1.message_set_extension
  2140. self.assertEqual(12345, proto.Extensions[extension1].i)
  2141. def testUnknownFields(self):
  2142. proto = unittest_pb2.TestAllTypes()
  2143. test_util.SetAllFields(proto)
  2144. serialized = proto.SerializeToString()
  2145. # The empty message should be parsable with all of the fields
  2146. # unknown.
  2147. proto2 = unittest_pb2.TestEmptyMessage()
  2148. # Parsing this message should succeed.
  2149. self.assertEqual(
  2150. len(serialized),
  2151. proto2.MergeFromString(serialized))
  2152. # Now test with a int64 field set.
  2153. proto = unittest_pb2.TestAllTypes()
  2154. proto.optional_int64 = 0x0fffffffffffffff
  2155. serialized = proto.SerializeToString()
  2156. # The empty message should be parsable with all of the fields
  2157. # unknown.
  2158. proto2 = unittest_pb2.TestEmptyMessage()
  2159. # Parsing this message should succeed.
  2160. self.assertEqual(
  2161. len(serialized),
  2162. proto2.MergeFromString(serialized))
  2163. def _CheckRaises(self, exc_class, callable_obj, exception):
  2164. """This method checks if the excpetion type and message are as expected."""
  2165. try:
  2166. callable_obj()
  2167. except exc_class as ex:
  2168. # Check if the exception message is the right one.
  2169. self.assertEqual(exception, str(ex))
  2170. return
  2171. else:
  2172. raise self.failureException('%s not raised' % str(exc_class))
  2173. def testSerializeUninitialized(self):
  2174. proto = unittest_pb2.TestRequired()
  2175. self._CheckRaises(
  2176. message.EncodeError,
  2177. proto.SerializeToString,
  2178. 'Message protobuf_unittest.TestRequired is missing required fields: '
  2179. 'a,b,c')
  2180. # Shouldn't raise exceptions.
  2181. partial = proto.SerializePartialToString()
  2182. proto2 = unittest_pb2.TestRequired()
  2183. self.assertFalse(proto2.HasField('a'))
  2184. # proto2 ParseFromString does not check that required fields are set.
  2185. proto2.ParseFromString(partial)
  2186. self.assertFalse(proto2.HasField('a'))
  2187. proto.a = 1
  2188. self._CheckRaises(
  2189. message.EncodeError,
  2190. proto.SerializeToString,
  2191. 'Message protobuf_unittest.TestRequired is missing required fields: b,c')
  2192. # Shouldn't raise exceptions.
  2193. partial = proto.SerializePartialToString()
  2194. proto.b = 2
  2195. self._CheckRaises(
  2196. message.EncodeError,
  2197. proto.SerializeToString,
  2198. 'Message protobuf_unittest.TestRequired is missing required fields: c')
  2199. # Shouldn't raise exceptions.
  2200. partial = proto.SerializePartialToString()
  2201. proto.c = 3
  2202. serialized = proto.SerializeToString()
  2203. # Shouldn't raise exceptions.
  2204. partial = proto.SerializePartialToString()
  2205. proto2 = unittest_pb2.TestRequired()
  2206. self.assertEqual(
  2207. len(serialized),
  2208. proto2.MergeFromString(serialized))
  2209. self.assertEqual(1, proto2.a)
  2210. self.assertEqual(2, proto2.b)
  2211. self.assertEqual(3, proto2.c)
  2212. self.assertEqual(
  2213. len(partial),
  2214. proto2.MergeFromString(partial))
  2215. self.assertEqual(1, proto2.a)
  2216. self.assertEqual(2, proto2.b)
  2217. self.assertEqual(3, proto2.c)
  2218. def testSerializeUninitializedSubMessage(self):
  2219. proto = unittest_pb2.TestRequiredForeign()
  2220. # Sub-message doesn't exist yet, so this succeeds.
  2221. proto.SerializeToString()
  2222. proto.optional_message.a = 1
  2223. self._CheckRaises(
  2224. message.EncodeError,
  2225. proto.SerializeToString,
  2226. 'Message protobuf_unittest.TestRequiredForeign '
  2227. 'is missing required fields: '
  2228. 'optional_message.b,optional_message.c')
  2229. proto.optional_message.b = 2
  2230. proto.optional_message.c = 3
  2231. proto.SerializeToString()
  2232. proto.repeated_message.add().a = 1
  2233. proto.repeated_message.add().b = 2
  2234. self._CheckRaises(
  2235. message.EncodeError,
  2236. proto.SerializeToString,
  2237. 'Message protobuf_unittest.TestRequiredForeign is missing required fields: '
  2238. 'repeated_message[0].b,repeated_message[0].c,'
  2239. 'repeated_message[1].a,repeated_message[1].c')
  2240. proto.repeated_message[0].b = 2
  2241. proto.repeated_message[0].c = 3
  2242. proto.repeated_message[1].a = 1
  2243. proto.repeated_message[1].c = 3
  2244. proto.SerializeToString()
  2245. def testSerializeAllPackedFields(self):
  2246. first_proto = unittest_pb2.TestPackedTypes()
  2247. second_proto = unittest_pb2.TestPackedTypes()
  2248. test_util.SetAllPackedFields(first_proto)
  2249. serialized = first_proto.SerializeToString()
  2250. self.assertEqual(first_proto.ByteSize(), len(serialized))
  2251. bytes_read = second_proto.MergeFromString(serialized)
  2252. self.assertEqual(second_proto.ByteSize(), bytes_read)
  2253. self.assertEqual(first_proto, second_proto)
  2254. def testSerializeAllPackedExtensions(self):
  2255. first_proto = unittest_pb2.TestPackedExtensions()
  2256. second_proto = unittest_pb2.TestPackedExtensions()
  2257. test_util.SetAllPackedExtensions(first_proto)
  2258. serialized = first_proto.SerializeToString()
  2259. bytes_read = second_proto.MergeFromString(serialized)
  2260. self.assertEqual(second_proto.ByteSize(), bytes_read)
  2261. self.assertEqual(first_proto, second_proto)
  2262. def testMergePackedFromStringWhenSomeFieldsAlreadySet(self):
  2263. first_proto = unittest_pb2.TestPackedTypes()
  2264. first_proto.packed_int32.extend([1, 2])
  2265. first_proto.packed_double.append(3.0)
  2266. serialized = first_proto.SerializeToString()
  2267. second_proto = unittest_pb2.TestPackedTypes()
  2268. second_proto.packed_int32.append(3)
  2269. second_proto.packed_double.extend([1.0, 2.0])
  2270. second_proto.packed_sint32.append(4)
  2271. self.assertEqual(
  2272. len(serialized),
  2273. second_proto.MergeFromString(serialized))
  2274. self.assertEqual([3, 1, 2], second_proto.packed_int32)
  2275. self.assertEqual([1.0, 2.0, 3.0], second_proto.packed_double)
  2276. self.assertEqual([4], second_proto.packed_sint32)
  2277. def testPackedFieldsWireFormat(self):
  2278. proto = unittest_pb2.TestPackedTypes()
  2279. proto.packed_int32.extend([1, 2, 150, 3]) # 1 + 1 + 2 + 1 bytes
  2280. proto.packed_double.extend([1.0, 1000.0]) # 8 + 8 bytes
  2281. proto.packed_float.append(2.0) # 4 bytes, will be before double
  2282. serialized = proto.SerializeToString()
  2283. self.assertEqual(proto.ByteSize(), len(serialized))
  2284. d = _MiniDecoder(serialized)
  2285. ReadTag = d.ReadFieldNumberAndWireType
  2286. self.assertEqual((90, wire_format.WIRETYPE_LENGTH_DELIMITED), ReadTag())
  2287. self.assertEqual(1+1+1+2, d.ReadInt32())
  2288. self.assertEqual(1, d.ReadInt32())
  2289. self.assertEqual(2, d.ReadInt32())
  2290. self.assertEqual(150, d.ReadInt32())
  2291. self.assertEqual(3, d.ReadInt32())
  2292. self.assertEqual((100, wire_format.WIRETYPE_LENGTH_DELIMITED), ReadTag())
  2293. self.assertEqual(4, d.ReadInt32())
  2294. self.assertEqual(2.0, d.ReadFloat())
  2295. self.assertEqual((101, wire_format.WIRETYPE_LENGTH_DELIMITED), ReadTag())
  2296. self.assertEqual(8+8, d.ReadInt32())
  2297. self.assertEqual(1.0, d.ReadDouble())
  2298. self.assertEqual(1000.0, d.ReadDouble())
  2299. self.assertTrue(d.EndOfStream())
  2300. def testParsePackedFromUnpacked(self):
  2301. unpacked = unittest_pb2.TestUnpackedTypes()
  2302. test_util.SetAllUnpackedFields(unpacked)
  2303. packed = unittest_pb2.TestPackedTypes()
  2304. serialized = unpacked.SerializeToString()
  2305. self.assertEqual(
  2306. len(serialized),
  2307. packed.MergeFromString(serialized))
  2308. expected = unittest_pb2.TestPackedTypes()
  2309. test_util.SetAllPackedFields(expected)
  2310. self.assertEqual(expected, packed)
  2311. def testParseUnpackedFromPacked(self):
  2312. packed = unittest_pb2.TestPackedTypes()
  2313. test_util.SetAllPackedFields(packed)
  2314. unpacked = unittest_pb2.TestUnpackedTypes()
  2315. serialized = packed.SerializeToString()
  2316. self.assertEqual(
  2317. len(serialized),
  2318. unpacked.MergeFromString(serialized))
  2319. expected = unittest_pb2.TestUnpackedTypes()
  2320. test_util.SetAllUnpackedFields(expected)
  2321. self.assertEqual(expected, unpacked)
  2322. def testFieldNumbers(self):
  2323. proto = unittest_pb2.TestAllTypes()
  2324. self.assertEqual(unittest_pb2.TestAllTypes.NestedMessage.BB_FIELD_NUMBER, 1)
  2325. self.assertEqual(unittest_pb2.TestAllTypes.OPTIONAL_INT32_FIELD_NUMBER, 1)
  2326. self.assertEqual(unittest_pb2.TestAllTypes.OPTIONALGROUP_FIELD_NUMBER, 16)
  2327. self.assertEqual(
  2328. unittest_pb2.TestAllTypes.OPTIONAL_NESTED_MESSAGE_FIELD_NUMBER, 18)
  2329. self.assertEqual(
  2330. unittest_pb2.TestAllTypes.OPTIONAL_NESTED_ENUM_FIELD_NUMBER, 21)
  2331. self.assertEqual(unittest_pb2.TestAllTypes.REPEATED_INT32_FIELD_NUMBER, 31)
  2332. self.assertEqual(unittest_pb2.TestAllTypes.REPEATEDGROUP_FIELD_NUMBER, 46)
  2333. self.assertEqual(
  2334. unittest_pb2.TestAllTypes.REPEATED_NESTED_MESSAGE_FIELD_NUMBER, 48)
  2335. self.assertEqual(
  2336. unittest_pb2.TestAllTypes.REPEATED_NESTED_ENUM_FIELD_NUMBER, 51)
  2337. def testExtensionFieldNumbers(self):
  2338. self.assertEqual(unittest_pb2.TestRequired.single.number, 1000)
  2339. self.assertEqual(unittest_pb2.TestRequired.SINGLE_FIELD_NUMBER, 1000)
  2340. self.assertEqual(unittest_pb2.TestRequired.multi.number, 1001)
  2341. self.assertEqual(unittest_pb2.TestRequired.MULTI_FIELD_NUMBER, 1001)
  2342. self.assertEqual(unittest_pb2.optional_int32_extension.number, 1)
  2343. self.assertEqual(unittest_pb2.OPTIONAL_INT32_EXTENSION_FIELD_NUMBER, 1)
  2344. self.assertEqual(unittest_pb2.optionalgroup_extension.number, 16)
  2345. self.assertEqual(unittest_pb2.OPTIONALGROUP_EXTENSION_FIELD_NUMBER, 16)
  2346. self.assertEqual(unittest_pb2.optional_nested_message_extension.number, 18)
  2347. self.assertEqual(
  2348. unittest_pb2.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18)
  2349. self.assertEqual(unittest_pb2.optional_nested_enum_extension.number, 21)
  2350. self.assertEqual(unittest_pb2.OPTIONAL_NESTED_ENUM_EXTENSION_FIELD_NUMBER,
  2351. 21)
  2352. self.assertEqual(unittest_pb2.repeated_int32_extension.number, 31)
  2353. self.assertEqual(unittest_pb2.REPEATED_INT32_EXTENSION_FIELD_NUMBER, 31)
  2354. self.assertEqual(unittest_pb2.repeatedgroup_extension.number, 46)
  2355. self.assertEqual(unittest_pb2.REPEATEDGROUP_EXTENSION_FIELD_NUMBER, 46)
  2356. self.assertEqual(unittest_pb2.repeated_nested_message_extension.number, 48)
  2357. self.assertEqual(
  2358. unittest_pb2.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48)
  2359. self.assertEqual(unittest_pb2.repeated_nested_enum_extension.number, 51)
  2360. self.assertEqual(unittest_pb2.REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER,
  2361. 51)
  2362. def testInitKwargs(self):
  2363. proto = unittest_pb2.TestAllTypes(
  2364. optional_int32=1,
  2365. optional_string='foo',
  2366. optional_bool=True,
  2367. optional_bytes=b'bar',
  2368. optional_nested_message=unittest_pb2.TestAllTypes.NestedMessage(bb=1),
  2369. optional_foreign_message=unittest_pb2.ForeignMessage(c=1),
  2370. optional_nested_enum=unittest_pb2.TestAllTypes.FOO,
  2371. optional_foreign_enum=unittest_pb2.FOREIGN_FOO,
  2372. repeated_int32=[1, 2, 3])
  2373. self.assertTrue(proto.IsInitialized())
  2374. self.assertTrue(proto.HasField('optional_int32'))
  2375. self.assertTrue(proto.HasField('optional_string'))
  2376. self.assertTrue(proto.HasField('optional_bool'))
  2377. self.assertTrue(proto.HasField('optional_bytes'))
  2378. self.assertTrue(proto.HasField('optional_nested_message'))
  2379. self.assertTrue(proto.HasField('optional_foreign_message'))
  2380. self.assertTrue(proto.HasField('optional_nested_enum'))
  2381. self.assertTrue(proto.HasField('optional_foreign_enum'))
  2382. self.assertEqual(1, proto.optional_int32)
  2383. self.assertEqual('foo', proto.optional_string)
  2384. self.assertEqual(True, proto.optional_bool)
  2385. self.assertEqual(b'bar', proto.optional_bytes)
  2386. self.assertEqual(1, proto.optional_nested_message.bb)
  2387. self.assertEqual(1, proto.optional_foreign_message.c)
  2388. self.assertEqual(unittest_pb2.TestAllTypes.FOO,
  2389. proto.optional_nested_enum)
  2390. self.assertEqual(unittest_pb2.FOREIGN_FOO, proto.optional_foreign_enum)
  2391. self.assertEqual([1, 2, 3], proto.repeated_int32)
  2392. def testInitArgsUnknownFieldName(self):
  2393. def InitalizeEmptyMessageWithExtraKeywordArg():
  2394. unused_proto = unittest_pb2.TestEmptyMessage(unknown='unknown')
  2395. self._CheckRaises(ValueError,
  2396. InitalizeEmptyMessageWithExtraKeywordArg,
  2397. 'Protocol message has no "unknown" field.')
  2398. def testInitRequiredKwargs(self):
  2399. proto = unittest_pb2.TestRequired(a=1, b=1, c=1)
  2400. self.assertTrue(proto.IsInitialized())
  2401. self.assertTrue(proto.HasField('a'))
  2402. self.assertTrue(proto.HasField('b'))
  2403. self.assertTrue(proto.HasField('c'))
  2404. self.assertTrue(not proto.HasField('dummy2'))
  2405. self.assertEqual(1, proto.a)
  2406. self.assertEqual(1, proto.b)
  2407. self.assertEqual(1, proto.c)
  2408. def testInitRequiredForeignKwargs(self):
  2409. proto = unittest_pb2.TestRequiredForeign(
  2410. optional_message=unittest_pb2.TestRequired(a=1, b=1, c=1))
  2411. self.assertTrue(proto.IsInitialized())
  2412. self.assertTrue(proto.HasField('optional_message'))
  2413. self.assertTrue(proto.optional_message.IsInitialized())
  2414. self.assertTrue(proto.optional_message.HasField('a'))
  2415. self.assertTrue(proto.optional_message.HasField('b'))
  2416. self.assertTrue(proto.optional_message.HasField('c'))
  2417. self.assertTrue(not proto.optional_message.HasField('dummy2'))
  2418. self.assertEqual(unittest_pb2.TestRequired(a=1, b=1, c=1),
  2419. proto.optional_message)
  2420. self.assertEqual(1, proto.optional_message.a)
  2421. self.assertEqual(1, proto.optional_message.b)
  2422. self.assertEqual(1, proto.optional_message.c)
  2423. def testInitRepeatedKwargs(self):
  2424. proto = unittest_pb2.TestAllTypes(repeated_int32=[1, 2, 3])
  2425. self.assertTrue(proto.IsInitialized())
  2426. self.assertEqual(1, proto.repeated_int32[0])
  2427. self.assertEqual(2, proto.repeated_int32[1])
  2428. self.assertEqual(3, proto.repeated_int32[2])
  2429. class OptionsTest(unittest.TestCase):
  2430. def testMessageOptions(self):
  2431. proto = unittest_mset_pb2.TestMessageSet()
  2432. self.assertEqual(True,
  2433. proto.DESCRIPTOR.GetOptions().message_set_wire_format)
  2434. proto = unittest_pb2.TestAllTypes()
  2435. self.assertEqual(False,
  2436. proto.DESCRIPTOR.GetOptions().message_set_wire_format)
  2437. def testPackedOptions(self):
  2438. proto = unittest_pb2.TestAllTypes()
  2439. proto.optional_int32 = 1
  2440. proto.optional_double = 3.0
  2441. for field_descriptor, _ in proto.ListFields():
  2442. self.assertEqual(False, field_descriptor.GetOptions().packed)
  2443. proto = unittest_pb2.TestPackedTypes()
  2444. proto.packed_int32.append(1)
  2445. proto.packed_double.append(3.0)
  2446. for field_descriptor, _ in proto.ListFields():
  2447. self.assertEqual(True, field_descriptor.GetOptions().packed)
  2448. self.assertEqual(reflection._FieldDescriptor.LABEL_REPEATED,
  2449. field_descriptor.label)
  2450. class ClassAPITest(unittest.TestCase):
  2451. @skipIf(
  2452. api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
  2453. 'C++ implementation requires a call to MakeDescriptor()')
  2454. def testMakeClassWithNestedDescriptor(self):
  2455. leaf_desc = descriptor.Descriptor('leaf', 'package.parent.child.leaf', '',
  2456. containing_type=None, fields=[],
  2457. nested_types=[], enum_types=[],
  2458. extensions=[])
  2459. child_desc = descriptor.Descriptor('child', 'package.parent.child', '',
  2460. containing_type=None, fields=[],
  2461. nested_types=[leaf_desc], enum_types=[],
  2462. extensions=[])
  2463. sibling_desc = descriptor.Descriptor('sibling', 'package.parent.sibling',
  2464. '', containing_type=None, fields=[],
  2465. nested_types=[], enum_types=[],
  2466. extensions=[])
  2467. parent_desc = descriptor.Descriptor('parent', 'package.parent', '',
  2468. containing_type=None, fields=[],
  2469. nested_types=[child_desc, sibling_desc],
  2470. enum_types=[], extensions=[])
  2471. message_class = reflection.MakeClass(parent_desc)
  2472. self.assertIn('child', message_class.__dict__)
  2473. self.assertIn('sibling', message_class.__dict__)
  2474. self.assertIn('leaf', message_class.child.__dict__)
  2475. def _GetSerializedFileDescriptor(self, name):
  2476. """Get a serialized representation of a test FileDescriptorProto.
  2477. Args:
  2478. name: All calls to this must use a unique message name, to avoid
  2479. collisions in the cpp descriptor pool.
  2480. Returns:
  2481. A string containing the serialized form of a test FileDescriptorProto.
  2482. """
  2483. file_descriptor_str = (
  2484. 'message_type {'
  2485. ' name: "' + name + '"'
  2486. ' field {'
  2487. ' name: "flat"'
  2488. ' number: 1'
  2489. ' label: LABEL_REPEATED'
  2490. ' type: TYPE_UINT32'
  2491. ' }'
  2492. ' field {'
  2493. ' name: "bar"'
  2494. ' number: 2'
  2495. ' label: LABEL_OPTIONAL'
  2496. ' type: TYPE_MESSAGE'
  2497. ' type_name: "Bar"'
  2498. ' }'
  2499. ' nested_type {'
  2500. ' name: "Bar"'
  2501. ' field {'
  2502. ' name: "baz"'
  2503. ' number: 3'
  2504. ' label: LABEL_OPTIONAL'
  2505. ' type: TYPE_MESSAGE'
  2506. ' type_name: "Baz"'
  2507. ' }'
  2508. ' nested_type {'
  2509. ' name: "Baz"'
  2510. ' enum_type {'
  2511. ' name: "deep_enum"'
  2512. ' value {'
  2513. ' name: "VALUE_A"'
  2514. ' number: 0'
  2515. ' }'
  2516. ' }'
  2517. ' field {'
  2518. ' name: "deep"'
  2519. ' number: 4'
  2520. ' label: LABEL_OPTIONAL'
  2521. ' type: TYPE_UINT32'
  2522. ' }'
  2523. ' }'
  2524. ' }'
  2525. '}')
  2526. file_descriptor = descriptor_pb2.FileDescriptorProto()
  2527. text_format.Merge(file_descriptor_str, file_descriptor)
  2528. return file_descriptor.SerializeToString()
  2529. def testParsingFlatClassWithExplicitClassDeclaration(self):
  2530. """Test that the generated class can parse a flat message."""
  2531. file_descriptor = descriptor_pb2.FileDescriptorProto()
  2532. file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
  2533. msg_descriptor = descriptor.MakeDescriptor(
  2534. file_descriptor.message_type[0])
  2535. class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
  2536. DESCRIPTOR = msg_descriptor
  2537. msg = MessageClass()
  2538. msg_str = (
  2539. 'flat: 0 '
  2540. 'flat: 1 '
  2541. 'flat: 2 ')
  2542. text_format.Merge(msg_str, msg)
  2543. self.assertEqual(msg.flat, [0, 1, 2])
  2544. def testParsingFlatClass(self):
  2545. """Test that the generated class can parse a flat message."""
  2546. file_descriptor = descriptor_pb2.FileDescriptorProto()
  2547. file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('B'))
  2548. msg_descriptor = descriptor.MakeDescriptor(
  2549. file_descriptor.message_type[0])
  2550. msg_class = reflection.MakeClass(msg_descriptor)
  2551. msg = msg_class()
  2552. msg_str = (
  2553. 'flat: 0 '
  2554. 'flat: 1 '
  2555. 'flat: 2 ')
  2556. text_format.Merge(msg_str, msg)
  2557. self.assertEqual(msg.flat, [0, 1, 2])
  2558. def testParsingNestedClass(self):
  2559. """Test that the generated class can parse a nested message."""
  2560. file_descriptor = descriptor_pb2.FileDescriptorProto()
  2561. file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('C'))
  2562. msg_descriptor = descriptor.MakeDescriptor(
  2563. file_descriptor.message_type[0])
  2564. msg_class = reflection.MakeClass(msg_descriptor)
  2565. msg = msg_class()
  2566. msg_str = (
  2567. 'bar {'
  2568. ' baz {'
  2569. ' deep: 4'
  2570. ' }'
  2571. '}')
  2572. text_format.Merge(msg_str, msg)
  2573. self.assertEqual(msg.bar.baz.deep, 4)
  2574. if __name__ == '__main__':
  2575. unittest.main()