reflection_test.py 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983
  1. #! /usr/bin/env 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 six
  40. import struct
  41. try:
  42. import unittest2 as unittest #PY26
  43. except ImportError:
  44. import unittest
  45. from google.protobuf import unittest_import_pb2
  46. from google.protobuf import unittest_mset_pb2
  47. from google.protobuf import unittest_pb2
  48. from google.protobuf import descriptor_pb2
  49. from google.protobuf import descriptor
  50. from google.protobuf import message
  51. from google.protobuf import reflection
  52. from google.protobuf import text_format
  53. from google.protobuf.internal import api_implementation
  54. from google.protobuf.internal import more_extensions_pb2
  55. from google.protobuf.internal import more_messages_pb2
  56. from google.protobuf.internal import message_set_extensions_pb2
  57. from google.protobuf.internal import wire_format
  58. from google.protobuf.internal import test_util
  59. from google.protobuf.internal import decoder
  60. class _MiniDecoder(object):
  61. """Decodes a stream of values from a string.
  62. Once upon a time we actually had a class called decoder.Decoder. Then we
  63. got rid of it during a redesign that made decoding much, much faster overall.
  64. But a couple tests in this file used it to check that the serialized form of
  65. a message was correct. So, this class implements just the methods that were
  66. used by said tests, so that we don't have to rewrite the tests.
  67. """
  68. def __init__(self, bytes):
  69. self._bytes = bytes
  70. self._pos = 0
  71. def ReadVarint(self):
  72. result, self._pos = decoder._DecodeVarint(self._bytes, self._pos)
  73. return result
  74. ReadInt32 = ReadVarint
  75. ReadInt64 = ReadVarint
  76. ReadUInt32 = ReadVarint
  77. ReadUInt64 = ReadVarint
  78. def ReadSInt64(self):
  79. return wire_format.ZigZagDecode(self.ReadVarint())
  80. ReadSInt32 = ReadSInt64
  81. def ReadFieldNumberAndWireType(self):
  82. return wire_format.UnpackTag(self.ReadVarint())
  83. def ReadFloat(self):
  84. result = struct.unpack("<f", self._bytes[self._pos:self._pos+4])[0]
  85. self._pos += 4
  86. return result
  87. def ReadDouble(self):
  88. result = struct.unpack("<d", self._bytes[self._pos:self._pos+8])[0]
  89. self._pos += 8
  90. return result
  91. def EndOfStream(self):
  92. return self._pos == len(self._bytes)
  93. class ReflectionTest(unittest.TestCase):
  94. def assertListsEqual(self, values, others):
  95. self.assertEqual(len(values), len(others))
  96. for i in range(len(values)):
  97. self.assertEqual(values[i], others[i])
  98. def testScalarConstructor(self):
  99. # Constructor with only scalar types should succeed.
  100. proto = unittest_pb2.TestAllTypes(
  101. optional_int32=24,
  102. optional_double=54.321,
  103. optional_string='optional_string',
  104. optional_float=None)
  105. self.assertEqual(24, proto.optional_int32)
  106. self.assertEqual(54.321, proto.optional_double)
  107. self.assertEqual('optional_string', proto.optional_string)
  108. self.assertFalse(proto.HasField("optional_float"))
  109. def testRepeatedScalarConstructor(self):
  110. # Constructor with only repeated scalar types should succeed.
  111. proto = unittest_pb2.TestAllTypes(
  112. repeated_int32=[1, 2, 3, 4],
  113. repeated_double=[1.23, 54.321],
  114. repeated_bool=[True, False, False],
  115. repeated_string=["optional_string"],
  116. repeated_float=None)
  117. self.assertEqual([1, 2, 3, 4], list(proto.repeated_int32))
  118. self.assertEqual([1.23, 54.321], list(proto.repeated_double))
  119. self.assertEqual([True, False, False], list(proto.repeated_bool))
  120. self.assertEqual(["optional_string"], list(proto.repeated_string))
  121. self.assertEqual([], list(proto.repeated_float))
  122. def testRepeatedCompositeConstructor(self):
  123. # Constructor with only repeated composite types should succeed.
  124. proto = unittest_pb2.TestAllTypes(
  125. repeated_nested_message=[
  126. unittest_pb2.TestAllTypes.NestedMessage(
  127. bb=unittest_pb2.TestAllTypes.FOO),
  128. unittest_pb2.TestAllTypes.NestedMessage(
  129. bb=unittest_pb2.TestAllTypes.BAR)],
  130. repeated_foreign_message=[
  131. unittest_pb2.ForeignMessage(c=-43),
  132. unittest_pb2.ForeignMessage(c=45324),
  133. unittest_pb2.ForeignMessage(c=12)],
  134. repeatedgroup=[
  135. unittest_pb2.TestAllTypes.RepeatedGroup(),
  136. unittest_pb2.TestAllTypes.RepeatedGroup(a=1),
  137. unittest_pb2.TestAllTypes.RepeatedGroup(a=2)])
  138. self.assertEqual(
  139. [unittest_pb2.TestAllTypes.NestedMessage(
  140. bb=unittest_pb2.TestAllTypes.FOO),
  141. unittest_pb2.TestAllTypes.NestedMessage(
  142. bb=unittest_pb2.TestAllTypes.BAR)],
  143. list(proto.repeated_nested_message))
  144. self.assertEqual(
  145. [unittest_pb2.ForeignMessage(c=-43),
  146. unittest_pb2.ForeignMessage(c=45324),
  147. unittest_pb2.ForeignMessage(c=12)],
  148. list(proto.repeated_foreign_message))
  149. self.assertEqual(
  150. [unittest_pb2.TestAllTypes.RepeatedGroup(),
  151. unittest_pb2.TestAllTypes.RepeatedGroup(a=1),
  152. unittest_pb2.TestAllTypes.RepeatedGroup(a=2)],
  153. list(proto.repeatedgroup))
  154. def testMixedConstructor(self):
  155. # Constructor with only mixed types should succeed.
  156. proto = unittest_pb2.TestAllTypes(
  157. optional_int32=24,
  158. optional_string='optional_string',
  159. repeated_double=[1.23, 54.321],
  160. repeated_bool=[True, False, False],
  161. repeated_nested_message=[
  162. unittest_pb2.TestAllTypes.NestedMessage(
  163. bb=unittest_pb2.TestAllTypes.FOO),
  164. unittest_pb2.TestAllTypes.NestedMessage(
  165. bb=unittest_pb2.TestAllTypes.BAR)],
  166. repeated_foreign_message=[
  167. unittest_pb2.ForeignMessage(c=-43),
  168. unittest_pb2.ForeignMessage(c=45324),
  169. unittest_pb2.ForeignMessage(c=12)],
  170. optional_nested_message=None)
  171. self.assertEqual(24, proto.optional_int32)
  172. self.assertEqual('optional_string', proto.optional_string)
  173. self.assertEqual([1.23, 54.321], list(proto.repeated_double))
  174. self.assertEqual([True, False, False], list(proto.repeated_bool))
  175. self.assertEqual(
  176. [unittest_pb2.TestAllTypes.NestedMessage(
  177. bb=unittest_pb2.TestAllTypes.FOO),
  178. unittest_pb2.TestAllTypes.NestedMessage(
  179. bb=unittest_pb2.TestAllTypes.BAR)],
  180. list(proto.repeated_nested_message))
  181. self.assertEqual(
  182. [unittest_pb2.ForeignMessage(c=-43),
  183. unittest_pb2.ForeignMessage(c=45324),
  184. unittest_pb2.ForeignMessage(c=12)],
  185. list(proto.repeated_foreign_message))
  186. self.assertFalse(proto.HasField("optional_nested_message"))
  187. def testConstructorTypeError(self):
  188. self.assertRaises(
  189. TypeError, unittest_pb2.TestAllTypes, optional_int32="foo")
  190. self.assertRaises(
  191. TypeError, unittest_pb2.TestAllTypes, optional_string=1234)
  192. self.assertRaises(
  193. TypeError, unittest_pb2.TestAllTypes, optional_nested_message=1234)
  194. self.assertRaises(
  195. TypeError, unittest_pb2.TestAllTypes, repeated_int32=1234)
  196. self.assertRaises(
  197. TypeError, unittest_pb2.TestAllTypes, repeated_int32=["foo"])
  198. self.assertRaises(
  199. TypeError, unittest_pb2.TestAllTypes, repeated_string=1234)
  200. self.assertRaises(
  201. TypeError, unittest_pb2.TestAllTypes, repeated_string=[1234])
  202. self.assertRaises(
  203. TypeError, unittest_pb2.TestAllTypes, repeated_nested_message=1234)
  204. self.assertRaises(
  205. TypeError, unittest_pb2.TestAllTypes, repeated_nested_message=[1234])
  206. def testConstructorInvalidatesCachedByteSize(self):
  207. message = unittest_pb2.TestAllTypes(optional_int32 = 12)
  208. self.assertEqual(2, message.ByteSize())
  209. message = unittest_pb2.TestAllTypes(
  210. optional_nested_message = unittest_pb2.TestAllTypes.NestedMessage())
  211. self.assertEqual(3, message.ByteSize())
  212. message = unittest_pb2.TestAllTypes(repeated_int32 = [12])
  213. self.assertEqual(3, message.ByteSize())
  214. message = unittest_pb2.TestAllTypes(
  215. repeated_nested_message = [unittest_pb2.TestAllTypes.NestedMessage()])
  216. self.assertEqual(3, message.ByteSize())
  217. def testSimpleHasBits(self):
  218. # Test a scalar.
  219. proto = unittest_pb2.TestAllTypes()
  220. self.assertTrue(not proto.HasField('optional_int32'))
  221. self.assertEqual(0, proto.optional_int32)
  222. # HasField() shouldn't be true if all we've done is
  223. # read the default value.
  224. self.assertTrue(not proto.HasField('optional_int32'))
  225. proto.optional_int32 = 1
  226. # Setting a value however *should* set the "has" bit.
  227. self.assertTrue(proto.HasField('optional_int32'))
  228. proto.ClearField('optional_int32')
  229. # And clearing that value should unset the "has" bit.
  230. self.assertTrue(not proto.HasField('optional_int32'))
  231. def testHasBitsWithSinglyNestedScalar(self):
  232. # Helper used to test foreign messages and groups.
  233. #
  234. # composite_field_name should be the name of a non-repeated
  235. # composite (i.e., foreign or group) field in TestAllTypes,
  236. # and scalar_field_name should be the name of an integer-valued
  237. # scalar field within that composite.
  238. #
  239. # I never thought I'd miss C++ macros and templates so much. :(
  240. # This helper is semantically just:
  241. #
  242. # assert proto.composite_field.scalar_field == 0
  243. # assert not proto.composite_field.HasField('scalar_field')
  244. # assert not proto.HasField('composite_field')
  245. #
  246. # proto.composite_field.scalar_field = 10
  247. # old_composite_field = proto.composite_field
  248. #
  249. # assert proto.composite_field.scalar_field == 10
  250. # assert proto.composite_field.HasField('scalar_field')
  251. # assert proto.HasField('composite_field')
  252. #
  253. # proto.ClearField('composite_field')
  254. #
  255. # assert not proto.composite_field.HasField('scalar_field')
  256. # assert not proto.HasField('composite_field')
  257. # assert proto.composite_field.scalar_field == 0
  258. #
  259. # # Now ensure that ClearField('composite_field') disconnected
  260. # # the old field object from the object tree...
  261. # assert old_composite_field is not proto.composite_field
  262. # old_composite_field.scalar_field = 20
  263. # assert not proto.composite_field.HasField('scalar_field')
  264. # assert not proto.HasField('composite_field')
  265. def TestCompositeHasBits(composite_field_name, scalar_field_name):
  266. proto = unittest_pb2.TestAllTypes()
  267. # First, check that we can get the scalar value, and see that it's the
  268. # default (0), but that proto.HasField('omposite') and
  269. # proto.composite.HasField('scalar') will still return False.
  270. composite_field = getattr(proto, composite_field_name)
  271. original_scalar_value = getattr(composite_field, scalar_field_name)
  272. self.assertEqual(0, original_scalar_value)
  273. # Assert that the composite object does not "have" the scalar.
  274. self.assertTrue(not composite_field.HasField(scalar_field_name))
  275. # Assert that proto does not "have" the composite field.
  276. self.assertTrue(not proto.HasField(composite_field_name))
  277. # Now set the scalar within the composite field. Ensure that the setting
  278. # is reflected, and that proto.HasField('composite') and
  279. # proto.composite.HasField('scalar') now both return True.
  280. new_val = 20
  281. setattr(composite_field, scalar_field_name, new_val)
  282. self.assertEqual(new_val, getattr(composite_field, scalar_field_name))
  283. # Hold on to a reference to the current composite_field object.
  284. old_composite_field = composite_field
  285. # Assert that the has methods now return true.
  286. self.assertTrue(composite_field.HasField(scalar_field_name))
  287. self.assertTrue(proto.HasField(composite_field_name))
  288. # Now call the clear method...
  289. proto.ClearField(composite_field_name)
  290. # ...and ensure that the "has" bits are all back to False...
  291. composite_field = getattr(proto, composite_field_name)
  292. self.assertTrue(not composite_field.HasField(scalar_field_name))
  293. self.assertTrue(not proto.HasField(composite_field_name))
  294. # ...and ensure that the scalar field has returned to its default.
  295. self.assertEqual(0, getattr(composite_field, scalar_field_name))
  296. self.assertTrue(old_composite_field is not composite_field)
  297. setattr(old_composite_field, scalar_field_name, new_val)
  298. self.assertTrue(not composite_field.HasField(scalar_field_name))
  299. self.assertTrue(not proto.HasField(composite_field_name))
  300. self.assertEqual(0, getattr(composite_field, scalar_field_name))
  301. # Test simple, single-level nesting when we set a scalar.
  302. TestCompositeHasBits('optionalgroup', 'a')
  303. TestCompositeHasBits('optional_nested_message', 'bb')
  304. TestCompositeHasBits('optional_foreign_message', 'c')
  305. TestCompositeHasBits('optional_import_message', 'd')
  306. def testReferencesToNestedMessage(self):
  307. proto = unittest_pb2.TestAllTypes()
  308. nested = proto.optional_nested_message
  309. del proto
  310. # A previous version had a bug where this would raise an exception when
  311. # hitting a now-dead weak reference.
  312. nested.bb = 23
  313. def testDisconnectingNestedMessageBeforeSettingField(self):
  314. proto = unittest_pb2.TestAllTypes()
  315. nested = proto.optional_nested_message
  316. proto.ClearField('optional_nested_message') # Should disconnect from parent
  317. self.assertTrue(nested is not proto.optional_nested_message)
  318. nested.bb = 23
  319. self.assertTrue(not proto.HasField('optional_nested_message'))
  320. self.assertEqual(0, proto.optional_nested_message.bb)
  321. def testGetDefaultMessageAfterDisconnectingDefaultMessage(self):
  322. proto = unittest_pb2.TestAllTypes()
  323. nested = proto.optional_nested_message
  324. proto.ClearField('optional_nested_message')
  325. del proto
  326. del nested
  327. # Force a garbage collect so that the underlying CMessages are freed along
  328. # with the Messages they point to. This is to make sure we're not deleting
  329. # default message instances.
  330. gc.collect()
  331. proto = unittest_pb2.TestAllTypes()
  332. nested = proto.optional_nested_message
  333. def testDisconnectingNestedMessageAfterSettingField(self):
  334. proto = unittest_pb2.TestAllTypes()
  335. nested = proto.optional_nested_message
  336. nested.bb = 5
  337. self.assertTrue(proto.HasField('optional_nested_message'))
  338. proto.ClearField('optional_nested_message') # Should disconnect from parent
  339. self.assertEqual(5, nested.bb)
  340. self.assertEqual(0, proto.optional_nested_message.bb)
  341. self.assertTrue(nested is not proto.optional_nested_message)
  342. nested.bb = 23
  343. self.assertTrue(not proto.HasField('optional_nested_message'))
  344. self.assertEqual(0, proto.optional_nested_message.bb)
  345. def testDisconnectingNestedMessageBeforeGettingField(self):
  346. proto = unittest_pb2.TestAllTypes()
  347. self.assertTrue(not proto.HasField('optional_nested_message'))
  348. proto.ClearField('optional_nested_message')
  349. self.assertTrue(not proto.HasField('optional_nested_message'))
  350. def testDisconnectingNestedMessageAfterMerge(self):
  351. # This test exercises the code path that does not use ReleaseMessage().
  352. # The underlying fear is that if we use ReleaseMessage() incorrectly,
  353. # we will have memory leaks. It's hard to check that that doesn't happen,
  354. # but at least we can exercise that code path to make sure it works.
  355. proto1 = unittest_pb2.TestAllTypes()
  356. proto2 = unittest_pb2.TestAllTypes()
  357. proto2.optional_nested_message.bb = 5
  358. proto1.MergeFrom(proto2)
  359. self.assertTrue(proto1.HasField('optional_nested_message'))
  360. proto1.ClearField('optional_nested_message')
  361. self.assertTrue(not proto1.HasField('optional_nested_message'))
  362. def testDisconnectingLazyNestedMessage(self):
  363. # This test exercises releasing a nested message that is lazy. This test
  364. # only exercises real code in the C++ implementation as Python does not
  365. # support lazy parsing, but the current C++ implementation results in
  366. # memory corruption and a crash.
  367. if api_implementation.Type() != 'python':
  368. return
  369. proto = unittest_pb2.TestAllTypes()
  370. proto.optional_lazy_message.bb = 5
  371. proto.ClearField('optional_lazy_message')
  372. del proto
  373. gc.collect()
  374. def testHasBitsWhenModifyingRepeatedFields(self):
  375. # Test nesting when we add an element to a repeated field in a submessage.
  376. proto = unittest_pb2.TestNestedMessageHasBits()
  377. proto.optional_nested_message.nestedmessage_repeated_int32.append(5)
  378. self.assertEqual(
  379. [5], proto.optional_nested_message.nestedmessage_repeated_int32)
  380. self.assertTrue(proto.HasField('optional_nested_message'))
  381. # Do the same test, but with a repeated composite field within the
  382. # submessage.
  383. proto.ClearField('optional_nested_message')
  384. self.assertTrue(not proto.HasField('optional_nested_message'))
  385. proto.optional_nested_message.nestedmessage_repeated_foreignmessage.add()
  386. self.assertTrue(proto.HasField('optional_nested_message'))
  387. def testHasBitsForManyLevelsOfNesting(self):
  388. # Test nesting many levels deep.
  389. recursive_proto = unittest_pb2.TestMutualRecursionA()
  390. self.assertTrue(not recursive_proto.HasField('bb'))
  391. self.assertEqual(0, recursive_proto.bb.a.bb.a.bb.optional_int32)
  392. self.assertTrue(not recursive_proto.HasField('bb'))
  393. recursive_proto.bb.a.bb.a.bb.optional_int32 = 5
  394. self.assertEqual(5, recursive_proto.bb.a.bb.a.bb.optional_int32)
  395. self.assertTrue(recursive_proto.HasField('bb'))
  396. self.assertTrue(recursive_proto.bb.HasField('a'))
  397. self.assertTrue(recursive_proto.bb.a.HasField('bb'))
  398. self.assertTrue(recursive_proto.bb.a.bb.HasField('a'))
  399. self.assertTrue(recursive_proto.bb.a.bb.a.HasField('bb'))
  400. self.assertTrue(not recursive_proto.bb.a.bb.a.bb.HasField('a'))
  401. self.assertTrue(recursive_proto.bb.a.bb.a.bb.HasField('optional_int32'))
  402. def testSingularListFields(self):
  403. proto = unittest_pb2.TestAllTypes()
  404. proto.optional_fixed32 = 1
  405. proto.optional_int32 = 5
  406. proto.optional_string = 'foo'
  407. # Access sub-message but don't set it yet.
  408. nested_message = proto.optional_nested_message
  409. self.assertEqual(
  410. [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 5),
  411. (proto.DESCRIPTOR.fields_by_name['optional_fixed32'], 1),
  412. (proto.DESCRIPTOR.fields_by_name['optional_string' ], 'foo') ],
  413. proto.ListFields())
  414. proto.optional_nested_message.bb = 123
  415. self.assertEqual(
  416. [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 5),
  417. (proto.DESCRIPTOR.fields_by_name['optional_fixed32'], 1),
  418. (proto.DESCRIPTOR.fields_by_name['optional_string' ], 'foo'),
  419. (proto.DESCRIPTOR.fields_by_name['optional_nested_message' ],
  420. nested_message) ],
  421. proto.ListFields())
  422. def testRepeatedListFields(self):
  423. proto = unittest_pb2.TestAllTypes()
  424. proto.repeated_fixed32.append(1)
  425. proto.repeated_int32.append(5)
  426. proto.repeated_int32.append(11)
  427. proto.repeated_string.extend(['foo', 'bar'])
  428. proto.repeated_string.extend([])
  429. proto.repeated_string.append('baz')
  430. proto.repeated_string.extend(str(x) for x in range(2))
  431. proto.optional_int32 = 21
  432. proto.repeated_bool # Access but don't set anything; should not be listed.
  433. self.assertEqual(
  434. [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 21),
  435. (proto.DESCRIPTOR.fields_by_name['repeated_int32' ], [5, 11]),
  436. (proto.DESCRIPTOR.fields_by_name['repeated_fixed32'], [1]),
  437. (proto.DESCRIPTOR.fields_by_name['repeated_string' ],
  438. ['foo', 'bar', 'baz', '0', '1']) ],
  439. proto.ListFields())
  440. def testSingularListExtensions(self):
  441. proto = unittest_pb2.TestAllExtensions()
  442. proto.Extensions[unittest_pb2.optional_fixed32_extension] = 1
  443. proto.Extensions[unittest_pb2.optional_int32_extension ] = 5
  444. proto.Extensions[unittest_pb2.optional_string_extension ] = 'foo'
  445. self.assertEqual(
  446. [ (unittest_pb2.optional_int32_extension , 5),
  447. (unittest_pb2.optional_fixed32_extension, 1),
  448. (unittest_pb2.optional_string_extension , 'foo') ],
  449. proto.ListFields())
  450. def testRepeatedListExtensions(self):
  451. proto = unittest_pb2.TestAllExtensions()
  452. proto.Extensions[unittest_pb2.repeated_fixed32_extension].append(1)
  453. proto.Extensions[unittest_pb2.repeated_int32_extension ].append(5)
  454. proto.Extensions[unittest_pb2.repeated_int32_extension ].append(11)
  455. proto.Extensions[unittest_pb2.repeated_string_extension ].append('foo')
  456. proto.Extensions[unittest_pb2.repeated_string_extension ].append('bar')
  457. proto.Extensions[unittest_pb2.repeated_string_extension ].append('baz')
  458. proto.Extensions[unittest_pb2.optional_int32_extension ] = 21
  459. self.assertEqual(
  460. [ (unittest_pb2.optional_int32_extension , 21),
  461. (unittest_pb2.repeated_int32_extension , [5, 11]),
  462. (unittest_pb2.repeated_fixed32_extension, [1]),
  463. (unittest_pb2.repeated_string_extension , ['foo', 'bar', 'baz']) ],
  464. proto.ListFields())
  465. def testListFieldsAndExtensions(self):
  466. proto = unittest_pb2.TestFieldOrderings()
  467. test_util.SetAllFieldsAndExtensions(proto)
  468. unittest_pb2.my_extension_int
  469. self.assertEqual(
  470. [ (proto.DESCRIPTOR.fields_by_name['my_int' ], 1),
  471. (unittest_pb2.my_extension_int , 23),
  472. (proto.DESCRIPTOR.fields_by_name['my_string'], 'foo'),
  473. (unittest_pb2.my_extension_string , 'bar'),
  474. (proto.DESCRIPTOR.fields_by_name['my_float' ], 1.0) ],
  475. proto.ListFields())
  476. def testDefaultValues(self):
  477. proto = unittest_pb2.TestAllTypes()
  478. self.assertEqual(0, proto.optional_int32)
  479. self.assertEqual(0, proto.optional_int64)
  480. self.assertEqual(0, proto.optional_uint32)
  481. self.assertEqual(0, proto.optional_uint64)
  482. self.assertEqual(0, proto.optional_sint32)
  483. self.assertEqual(0, proto.optional_sint64)
  484. self.assertEqual(0, proto.optional_fixed32)
  485. self.assertEqual(0, proto.optional_fixed64)
  486. self.assertEqual(0, proto.optional_sfixed32)
  487. self.assertEqual(0, proto.optional_sfixed64)
  488. self.assertEqual(0.0, proto.optional_float)
  489. self.assertEqual(0.0, proto.optional_double)
  490. self.assertEqual(False, proto.optional_bool)
  491. self.assertEqual('', proto.optional_string)
  492. self.assertEqual(b'', proto.optional_bytes)
  493. self.assertEqual(41, proto.default_int32)
  494. self.assertEqual(42, proto.default_int64)
  495. self.assertEqual(43, proto.default_uint32)
  496. self.assertEqual(44, proto.default_uint64)
  497. self.assertEqual(-45, proto.default_sint32)
  498. self.assertEqual(46, proto.default_sint64)
  499. self.assertEqual(47, proto.default_fixed32)
  500. self.assertEqual(48, proto.default_fixed64)
  501. self.assertEqual(49, proto.default_sfixed32)
  502. self.assertEqual(-50, proto.default_sfixed64)
  503. self.assertEqual(51.5, proto.default_float)
  504. self.assertEqual(52e3, proto.default_double)
  505. self.assertEqual(True, proto.default_bool)
  506. self.assertEqual('hello', proto.default_string)
  507. self.assertEqual(b'world', proto.default_bytes)
  508. self.assertEqual(unittest_pb2.TestAllTypes.BAR, proto.default_nested_enum)
  509. self.assertEqual(unittest_pb2.FOREIGN_BAR, proto.default_foreign_enum)
  510. self.assertEqual(unittest_import_pb2.IMPORT_BAR,
  511. proto.default_import_enum)
  512. proto = unittest_pb2.TestExtremeDefaultValues()
  513. self.assertEqual(u'\u1234', proto.utf8_string)
  514. def testHasFieldWithUnknownFieldName(self):
  515. proto = unittest_pb2.TestAllTypes()
  516. self.assertRaises(ValueError, proto.HasField, 'nonexistent_field')
  517. def testClearFieldWithUnknownFieldName(self):
  518. proto = unittest_pb2.TestAllTypes()
  519. self.assertRaises(ValueError, proto.ClearField, 'nonexistent_field')
  520. def testClearRemovesChildren(self):
  521. # Make sure there aren't any implementation bugs that are only partially
  522. # clearing the message (which can happen in the more complex C++
  523. # implementation which has parallel message lists).
  524. proto = unittest_pb2.TestRequiredForeign()
  525. for i in range(10):
  526. proto.repeated_message.add()
  527. proto2 = unittest_pb2.TestRequiredForeign()
  528. proto.CopyFrom(proto2)
  529. self.assertRaises(IndexError, lambda: proto.repeated_message[5])
  530. def testDisallowedAssignments(self):
  531. # It's illegal to assign values directly to repeated fields
  532. # or to nonrepeated composite fields. Ensure that this fails.
  533. proto = unittest_pb2.TestAllTypes()
  534. # Repeated fields.
  535. self.assertRaises(AttributeError, setattr, proto, 'repeated_int32', 10)
  536. # Lists shouldn't work, either.
  537. self.assertRaises(AttributeError, setattr, proto, 'repeated_int32', [10])
  538. # Composite fields.
  539. self.assertRaises(AttributeError, setattr, proto,
  540. 'optional_nested_message', 23)
  541. # Assignment to a repeated nested message field without specifying
  542. # the index in the array of nested messages.
  543. self.assertRaises(AttributeError, setattr, proto.repeated_nested_message,
  544. 'bb', 34)
  545. # Assignment to an attribute of a repeated field.
  546. self.assertRaises(AttributeError, setattr, proto.repeated_float,
  547. 'some_attribute', 34)
  548. # proto.nonexistent_field = 23 should fail as well.
  549. self.assertRaises(AttributeError, setattr, proto, 'nonexistent_field', 23)
  550. def testSingleScalarTypeSafety(self):
  551. proto = unittest_pb2.TestAllTypes()
  552. self.assertRaises(TypeError, setattr, proto, 'optional_int32', 1.1)
  553. self.assertRaises(TypeError, setattr, proto, 'optional_int32', 'foo')
  554. self.assertRaises(TypeError, setattr, proto, 'optional_string', 10)
  555. self.assertRaises(TypeError, setattr, proto, 'optional_bytes', 10)
  556. def testIntegerTypes(self):
  557. def TestGetAndDeserialize(field_name, value, expected_type):
  558. proto = unittest_pb2.TestAllTypes()
  559. setattr(proto, field_name, value)
  560. self.assertIsInstance(getattr(proto, field_name), expected_type)
  561. proto2 = unittest_pb2.TestAllTypes()
  562. proto2.ParseFromString(proto.SerializeToString())
  563. self.assertIsInstance(getattr(proto2, field_name), expected_type)
  564. TestGetAndDeserialize('optional_int32', 1, int)
  565. TestGetAndDeserialize('optional_int32', 1 << 30, int)
  566. TestGetAndDeserialize('optional_uint32', 1 << 30, int)
  567. try:
  568. integer_64 = long
  569. except NameError: # Python3
  570. integer_64 = int
  571. if struct.calcsize('L') == 4:
  572. # Python only has signed ints, so 32-bit python can't fit an uint32
  573. # in an int.
  574. TestGetAndDeserialize('optional_uint32', 1 << 31, long)
  575. else:
  576. # 64-bit python can fit uint32 inside an int
  577. TestGetAndDeserialize('optional_uint32', 1 << 31, int)
  578. TestGetAndDeserialize('optional_int64', 1 << 30, integer_64)
  579. TestGetAndDeserialize('optional_int64', 1 << 60, integer_64)
  580. TestGetAndDeserialize('optional_uint64', 1 << 30, integer_64)
  581. TestGetAndDeserialize('optional_uint64', 1 << 60, integer_64)
  582. def testSingleScalarBoundsChecking(self):
  583. def TestMinAndMaxIntegers(field_name, expected_min, expected_max):
  584. pb = unittest_pb2.TestAllTypes()
  585. setattr(pb, field_name, expected_min)
  586. self.assertEqual(expected_min, getattr(pb, field_name))
  587. setattr(pb, field_name, expected_max)
  588. self.assertEqual(expected_max, getattr(pb, field_name))
  589. self.assertRaises(ValueError, setattr, pb, field_name, expected_min - 1)
  590. self.assertRaises(ValueError, setattr, pb, field_name, expected_max + 1)
  591. TestMinAndMaxIntegers('optional_int32', -(1 << 31), (1 << 31) - 1)
  592. TestMinAndMaxIntegers('optional_uint32', 0, 0xffffffff)
  593. TestMinAndMaxIntegers('optional_int64', -(1 << 63), (1 << 63) - 1)
  594. TestMinAndMaxIntegers('optional_uint64', 0, 0xffffffffffffffff)
  595. pb = unittest_pb2.TestAllTypes()
  596. pb.optional_nested_enum = 1
  597. self.assertEqual(1, pb.optional_nested_enum)
  598. def testRepeatedScalarTypeSafety(self):
  599. proto = unittest_pb2.TestAllTypes()
  600. self.assertRaises(TypeError, proto.repeated_int32.append, 1.1)
  601. self.assertRaises(TypeError, proto.repeated_int32.append, 'foo')
  602. self.assertRaises(TypeError, proto.repeated_string, 10)
  603. self.assertRaises(TypeError, proto.repeated_bytes, 10)
  604. proto.repeated_int32.append(10)
  605. proto.repeated_int32[0] = 23
  606. self.assertRaises(IndexError, proto.repeated_int32.__setitem__, 500, 23)
  607. self.assertRaises(TypeError, proto.repeated_int32.__setitem__, 0, 'abc')
  608. # Repeated enums tests.
  609. #proto.repeated_nested_enum.append(0)
  610. def testSingleScalarGettersAndSetters(self):
  611. proto = unittest_pb2.TestAllTypes()
  612. self.assertEqual(0, proto.optional_int32)
  613. proto.optional_int32 = 1
  614. self.assertEqual(1, proto.optional_int32)
  615. proto.optional_uint64 = 0xffffffffffff
  616. self.assertEqual(0xffffffffffff, proto.optional_uint64)
  617. proto.optional_uint64 = 0xffffffffffffffff
  618. self.assertEqual(0xffffffffffffffff, proto.optional_uint64)
  619. # TODO(robinson): Test all other scalar field types.
  620. def testSingleScalarClearField(self):
  621. proto = unittest_pb2.TestAllTypes()
  622. # Should be allowed to clear something that's not there (a no-op).
  623. proto.ClearField('optional_int32')
  624. proto.optional_int32 = 1
  625. self.assertTrue(proto.HasField('optional_int32'))
  626. proto.ClearField('optional_int32')
  627. self.assertEqual(0, proto.optional_int32)
  628. self.assertTrue(not proto.HasField('optional_int32'))
  629. # TODO(robinson): Test all other scalar field types.
  630. def testEnums(self):
  631. proto = unittest_pb2.TestAllTypes()
  632. self.assertEqual(1, proto.FOO)
  633. self.assertEqual(1, unittest_pb2.TestAllTypes.FOO)
  634. self.assertEqual(2, proto.BAR)
  635. self.assertEqual(2, unittest_pb2.TestAllTypes.BAR)
  636. self.assertEqual(3, proto.BAZ)
  637. self.assertEqual(3, unittest_pb2.TestAllTypes.BAZ)
  638. def testEnum_Name(self):
  639. self.assertEqual('FOREIGN_FOO',
  640. unittest_pb2.ForeignEnum.Name(unittest_pb2.FOREIGN_FOO))
  641. self.assertEqual('FOREIGN_BAR',
  642. unittest_pb2.ForeignEnum.Name(unittest_pb2.FOREIGN_BAR))
  643. self.assertEqual('FOREIGN_BAZ',
  644. unittest_pb2.ForeignEnum.Name(unittest_pb2.FOREIGN_BAZ))
  645. self.assertRaises(ValueError,
  646. unittest_pb2.ForeignEnum.Name, 11312)
  647. proto = unittest_pb2.TestAllTypes()
  648. self.assertEqual('FOO',
  649. proto.NestedEnum.Name(proto.FOO))
  650. self.assertEqual('FOO',
  651. unittest_pb2.TestAllTypes.NestedEnum.Name(proto.FOO))
  652. self.assertEqual('BAR',
  653. proto.NestedEnum.Name(proto.BAR))
  654. self.assertEqual('BAR',
  655. unittest_pb2.TestAllTypes.NestedEnum.Name(proto.BAR))
  656. self.assertEqual('BAZ',
  657. proto.NestedEnum.Name(proto.BAZ))
  658. self.assertEqual('BAZ',
  659. unittest_pb2.TestAllTypes.NestedEnum.Name(proto.BAZ))
  660. self.assertRaises(ValueError,
  661. proto.NestedEnum.Name, 11312)
  662. self.assertRaises(ValueError,
  663. unittest_pb2.TestAllTypes.NestedEnum.Name, 11312)
  664. def testEnum_Value(self):
  665. self.assertEqual(unittest_pb2.FOREIGN_FOO,
  666. unittest_pb2.ForeignEnum.Value('FOREIGN_FOO'))
  667. self.assertEqual(unittest_pb2.FOREIGN_BAR,
  668. unittest_pb2.ForeignEnum.Value('FOREIGN_BAR'))
  669. self.assertEqual(unittest_pb2.FOREIGN_BAZ,
  670. unittest_pb2.ForeignEnum.Value('FOREIGN_BAZ'))
  671. self.assertRaises(ValueError,
  672. unittest_pb2.ForeignEnum.Value, 'FO')
  673. proto = unittest_pb2.TestAllTypes()
  674. self.assertEqual(proto.FOO,
  675. proto.NestedEnum.Value('FOO'))
  676. self.assertEqual(proto.FOO,
  677. unittest_pb2.TestAllTypes.NestedEnum.Value('FOO'))
  678. self.assertEqual(proto.BAR,
  679. proto.NestedEnum.Value('BAR'))
  680. self.assertEqual(proto.BAR,
  681. unittest_pb2.TestAllTypes.NestedEnum.Value('BAR'))
  682. self.assertEqual(proto.BAZ,
  683. proto.NestedEnum.Value('BAZ'))
  684. self.assertEqual(proto.BAZ,
  685. unittest_pb2.TestAllTypes.NestedEnum.Value('BAZ'))
  686. self.assertRaises(ValueError,
  687. proto.NestedEnum.Value, 'Foo')
  688. self.assertRaises(ValueError,
  689. unittest_pb2.TestAllTypes.NestedEnum.Value, 'Foo')
  690. def testEnum_KeysAndValues(self):
  691. self.assertEqual(['FOREIGN_FOO', 'FOREIGN_BAR', 'FOREIGN_BAZ'],
  692. list(unittest_pb2.ForeignEnum.keys()))
  693. self.assertEqual([4, 5, 6],
  694. list(unittest_pb2.ForeignEnum.values()))
  695. self.assertEqual([('FOREIGN_FOO', 4), ('FOREIGN_BAR', 5),
  696. ('FOREIGN_BAZ', 6)],
  697. list(unittest_pb2.ForeignEnum.items()))
  698. proto = unittest_pb2.TestAllTypes()
  699. self.assertEqual(['FOO', 'BAR', 'BAZ', 'NEG'], list(proto.NestedEnum.keys()))
  700. self.assertEqual([1, 2, 3, -1], list(proto.NestedEnum.values()))
  701. self.assertEqual([('FOO', 1), ('BAR', 2), ('BAZ', 3), ('NEG', -1)],
  702. list(proto.NestedEnum.items()))
  703. def testRepeatedScalars(self):
  704. proto = unittest_pb2.TestAllTypes()
  705. self.assertTrue(not proto.repeated_int32)
  706. self.assertEqual(0, len(proto.repeated_int32))
  707. proto.repeated_int32.append(5)
  708. proto.repeated_int32.append(10)
  709. proto.repeated_int32.append(15)
  710. self.assertTrue(proto.repeated_int32)
  711. self.assertEqual(3, len(proto.repeated_int32))
  712. self.assertEqual([5, 10, 15], proto.repeated_int32)
  713. # Test single retrieval.
  714. self.assertEqual(5, proto.repeated_int32[0])
  715. self.assertEqual(15, proto.repeated_int32[-1])
  716. # Test out-of-bounds indices.
  717. self.assertRaises(IndexError, proto.repeated_int32.__getitem__, 1234)
  718. self.assertRaises(IndexError, proto.repeated_int32.__getitem__, -1234)
  719. # Test incorrect types passed to __getitem__.
  720. self.assertRaises(TypeError, proto.repeated_int32.__getitem__, 'foo')
  721. self.assertRaises(TypeError, proto.repeated_int32.__getitem__, None)
  722. # Test single assignment.
  723. proto.repeated_int32[1] = 20
  724. self.assertEqual([5, 20, 15], proto.repeated_int32)
  725. # Test insertion.
  726. proto.repeated_int32.insert(1, 25)
  727. self.assertEqual([5, 25, 20, 15], proto.repeated_int32)
  728. # Test slice retrieval.
  729. proto.repeated_int32.append(30)
  730. self.assertEqual([25, 20, 15], proto.repeated_int32[1:4])
  731. self.assertEqual([5, 25, 20, 15, 30], proto.repeated_int32[:])
  732. # Test slice assignment with an iterator
  733. proto.repeated_int32[1:4] = (i for i in range(3))
  734. self.assertEqual([5, 0, 1, 2, 30], proto.repeated_int32)
  735. # Test slice assignment.
  736. proto.repeated_int32[1:4] = [35, 40, 45]
  737. self.assertEqual([5, 35, 40, 45, 30], proto.repeated_int32)
  738. # Test that we can use the field as an iterator.
  739. result = []
  740. for i in proto.repeated_int32:
  741. result.append(i)
  742. self.assertEqual([5, 35, 40, 45, 30], result)
  743. # Test single deletion.
  744. del proto.repeated_int32[2]
  745. self.assertEqual([5, 35, 45, 30], proto.repeated_int32)
  746. # Test slice deletion.
  747. del proto.repeated_int32[2:]
  748. self.assertEqual([5, 35], proto.repeated_int32)
  749. # Test extending.
  750. proto.repeated_int32.extend([3, 13])
  751. self.assertEqual([5, 35, 3, 13], proto.repeated_int32)
  752. # Test clearing.
  753. proto.ClearField('repeated_int32')
  754. self.assertTrue(not proto.repeated_int32)
  755. self.assertEqual(0, len(proto.repeated_int32))
  756. proto.repeated_int32.append(1)
  757. self.assertEqual(1, proto.repeated_int32[-1])
  758. # Test assignment to a negative index.
  759. proto.repeated_int32[-1] = 2
  760. self.assertEqual(2, proto.repeated_int32[-1])
  761. # Test deletion at negative indices.
  762. proto.repeated_int32[:] = [0, 1, 2, 3]
  763. del proto.repeated_int32[-1]
  764. self.assertEqual([0, 1, 2], proto.repeated_int32)
  765. del proto.repeated_int32[-2]
  766. self.assertEqual([0, 2], proto.repeated_int32)
  767. self.assertRaises(IndexError, proto.repeated_int32.__delitem__, -3)
  768. self.assertRaises(IndexError, proto.repeated_int32.__delitem__, 300)
  769. del proto.repeated_int32[-2:-1]
  770. self.assertEqual([2], proto.repeated_int32)
  771. del proto.repeated_int32[100:10000]
  772. self.assertEqual([2], proto.repeated_int32)
  773. def testRepeatedScalarsRemove(self):
  774. proto = unittest_pb2.TestAllTypes()
  775. self.assertTrue(not proto.repeated_int32)
  776. self.assertEqual(0, len(proto.repeated_int32))
  777. proto.repeated_int32.append(5)
  778. proto.repeated_int32.append(10)
  779. proto.repeated_int32.append(5)
  780. proto.repeated_int32.append(5)
  781. self.assertEqual(4, len(proto.repeated_int32))
  782. proto.repeated_int32.remove(5)
  783. self.assertEqual(3, len(proto.repeated_int32))
  784. self.assertEqual(10, proto.repeated_int32[0])
  785. self.assertEqual(5, proto.repeated_int32[1])
  786. self.assertEqual(5, proto.repeated_int32[2])
  787. proto.repeated_int32.remove(5)
  788. self.assertEqual(2, len(proto.repeated_int32))
  789. self.assertEqual(10, proto.repeated_int32[0])
  790. self.assertEqual(5, proto.repeated_int32[1])
  791. proto.repeated_int32.remove(10)
  792. self.assertEqual(1, len(proto.repeated_int32))
  793. self.assertEqual(5, proto.repeated_int32[0])
  794. # Remove a non-existent element.
  795. self.assertRaises(ValueError, proto.repeated_int32.remove, 123)
  796. def testRepeatedComposites(self):
  797. proto = unittest_pb2.TestAllTypes()
  798. self.assertTrue(not proto.repeated_nested_message)
  799. self.assertEqual(0, len(proto.repeated_nested_message))
  800. m0 = proto.repeated_nested_message.add()
  801. m1 = proto.repeated_nested_message.add()
  802. self.assertTrue(proto.repeated_nested_message)
  803. self.assertEqual(2, len(proto.repeated_nested_message))
  804. self.assertListsEqual([m0, m1], proto.repeated_nested_message)
  805. self.assertIsInstance(m0, unittest_pb2.TestAllTypes.NestedMessage)
  806. # Test out-of-bounds indices.
  807. self.assertRaises(IndexError, proto.repeated_nested_message.__getitem__,
  808. 1234)
  809. self.assertRaises(IndexError, proto.repeated_nested_message.__getitem__,
  810. -1234)
  811. # Test incorrect types passed to __getitem__.
  812. self.assertRaises(TypeError, proto.repeated_nested_message.__getitem__,
  813. 'foo')
  814. self.assertRaises(TypeError, proto.repeated_nested_message.__getitem__,
  815. None)
  816. # Test slice retrieval.
  817. m2 = proto.repeated_nested_message.add()
  818. m3 = proto.repeated_nested_message.add()
  819. m4 = proto.repeated_nested_message.add()
  820. self.assertListsEqual(
  821. [m1, m2, m3], proto.repeated_nested_message[1:4])
  822. self.assertListsEqual(
  823. [m0, m1, m2, m3, m4], proto.repeated_nested_message[:])
  824. self.assertListsEqual(
  825. [m0, m1], proto.repeated_nested_message[:2])
  826. self.assertListsEqual(
  827. [m2, m3, m4], proto.repeated_nested_message[2:])
  828. self.assertEqual(
  829. m0, proto.repeated_nested_message[0])
  830. self.assertListsEqual(
  831. [m0], proto.repeated_nested_message[:1])
  832. # Test that we can use the field as an iterator.
  833. result = []
  834. for i in proto.repeated_nested_message:
  835. result.append(i)
  836. self.assertListsEqual([m0, m1, m2, m3, m4], result)
  837. # Test single deletion.
  838. del proto.repeated_nested_message[2]
  839. self.assertListsEqual([m0, m1, m3, m4], proto.repeated_nested_message)
  840. # Test slice deletion.
  841. del proto.repeated_nested_message[2:]
  842. self.assertListsEqual([m0, m1], proto.repeated_nested_message)
  843. # Test extending.
  844. n1 = unittest_pb2.TestAllTypes.NestedMessage(bb=1)
  845. n2 = unittest_pb2.TestAllTypes.NestedMessage(bb=2)
  846. proto.repeated_nested_message.extend([n1,n2])
  847. self.assertEqual(4, len(proto.repeated_nested_message))
  848. self.assertEqual(n1, proto.repeated_nested_message[2])
  849. self.assertEqual(n2, proto.repeated_nested_message[3])
  850. # Test clearing.
  851. proto.ClearField('repeated_nested_message')
  852. self.assertTrue(not proto.repeated_nested_message)
  853. self.assertEqual(0, len(proto.repeated_nested_message))
  854. # Test constructing an element while adding it.
  855. proto.repeated_nested_message.add(bb=23)
  856. self.assertEqual(1, len(proto.repeated_nested_message))
  857. self.assertEqual(23, proto.repeated_nested_message[0].bb)
  858. def testRepeatedCompositeRemove(self):
  859. proto = unittest_pb2.TestAllTypes()
  860. self.assertEqual(0, len(proto.repeated_nested_message))
  861. m0 = proto.repeated_nested_message.add()
  862. # Need to set some differentiating variable so m0 != m1 != m2:
  863. m0.bb = len(proto.repeated_nested_message)
  864. m1 = proto.repeated_nested_message.add()
  865. m1.bb = len(proto.repeated_nested_message)
  866. self.assertTrue(m0 != m1)
  867. m2 = proto.repeated_nested_message.add()
  868. m2.bb = len(proto.repeated_nested_message)
  869. self.assertListsEqual([m0, m1, m2], proto.repeated_nested_message)
  870. self.assertEqual(3, len(proto.repeated_nested_message))
  871. proto.repeated_nested_message.remove(m0)
  872. self.assertEqual(2, len(proto.repeated_nested_message))
  873. self.assertEqual(m1, proto.repeated_nested_message[0])
  874. self.assertEqual(m2, proto.repeated_nested_message[1])
  875. # Removing m0 again or removing None should raise error
  876. self.assertRaises(ValueError, proto.repeated_nested_message.remove, m0)
  877. self.assertRaises(ValueError, proto.repeated_nested_message.remove, None)
  878. self.assertEqual(2, len(proto.repeated_nested_message))
  879. proto.repeated_nested_message.remove(m2)
  880. self.assertEqual(1, len(proto.repeated_nested_message))
  881. self.assertEqual(m1, proto.repeated_nested_message[0])
  882. def testHandWrittenReflection(self):
  883. # Hand written extensions are only supported by the pure-Python
  884. # implementation of the API.
  885. if api_implementation.Type() != 'python':
  886. return
  887. FieldDescriptor = descriptor.FieldDescriptor
  888. foo_field_descriptor = FieldDescriptor(
  889. name='foo_field', full_name='MyProto.foo_field',
  890. index=0, number=1, type=FieldDescriptor.TYPE_INT64,
  891. cpp_type=FieldDescriptor.CPPTYPE_INT64,
  892. label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
  893. containing_type=None, message_type=None, enum_type=None,
  894. is_extension=False, extension_scope=None,
  895. options=descriptor_pb2.FieldOptions())
  896. mydescriptor = descriptor.Descriptor(
  897. name='MyProto', full_name='MyProto', filename='ignored',
  898. containing_type=None, nested_types=[], enum_types=[],
  899. fields=[foo_field_descriptor], extensions=[],
  900. options=descriptor_pb2.MessageOptions())
  901. class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
  902. DESCRIPTOR = mydescriptor
  903. myproto_instance = MyProtoClass()
  904. self.assertEqual(0, myproto_instance.foo_field)
  905. self.assertTrue(not myproto_instance.HasField('foo_field'))
  906. myproto_instance.foo_field = 23
  907. self.assertEqual(23, myproto_instance.foo_field)
  908. self.assertTrue(myproto_instance.HasField('foo_field'))
  909. def testDescriptorProtoSupport(self):
  910. # Hand written descriptors/reflection are only supported by the pure-Python
  911. # implementation of the API.
  912. if api_implementation.Type() != 'python':
  913. return
  914. def AddDescriptorField(proto, field_name, field_type):
  915. AddDescriptorField.field_index += 1
  916. new_field = proto.field.add()
  917. new_field.name = field_name
  918. new_field.type = field_type
  919. new_field.number = AddDescriptorField.field_index
  920. new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL
  921. AddDescriptorField.field_index = 0
  922. desc_proto = descriptor_pb2.DescriptorProto()
  923. desc_proto.name = 'Car'
  924. fdp = descriptor_pb2.FieldDescriptorProto
  925. AddDescriptorField(desc_proto, 'name', fdp.TYPE_STRING)
  926. AddDescriptorField(desc_proto, 'year', fdp.TYPE_INT64)
  927. AddDescriptorField(desc_proto, 'automatic', fdp.TYPE_BOOL)
  928. AddDescriptorField(desc_proto, 'price', fdp.TYPE_DOUBLE)
  929. # Add a repeated field
  930. AddDescriptorField.field_index += 1
  931. new_field = desc_proto.field.add()
  932. new_field.name = 'owners'
  933. new_field.type = fdp.TYPE_STRING
  934. new_field.number = AddDescriptorField.field_index
  935. new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_REPEATED
  936. desc = descriptor.MakeDescriptor(desc_proto)
  937. self.assertTrue('name' in desc.fields_by_name)
  938. self.assertTrue('year' in desc.fields_by_name)
  939. self.assertTrue('automatic' in desc.fields_by_name)
  940. self.assertTrue('price' in desc.fields_by_name)
  941. self.assertTrue('owners' in desc.fields_by_name)
  942. class CarMessage(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
  943. DESCRIPTOR = desc
  944. prius = CarMessage()
  945. prius.name = 'prius'
  946. prius.year = 2010
  947. prius.automatic = True
  948. prius.price = 25134.75
  949. prius.owners.extend(['bob', 'susan'])
  950. serialized_prius = prius.SerializeToString()
  951. new_prius = reflection.ParseMessage(desc, serialized_prius)
  952. self.assertTrue(new_prius is not prius)
  953. self.assertEqual(prius, new_prius)
  954. # these are unnecessary assuming message equality works as advertised but
  955. # explicitly check to be safe since we're mucking about in metaclass foo
  956. self.assertEqual(prius.name, new_prius.name)
  957. self.assertEqual(prius.year, new_prius.year)
  958. self.assertEqual(prius.automatic, new_prius.automatic)
  959. self.assertEqual(prius.price, new_prius.price)
  960. self.assertEqual(prius.owners, new_prius.owners)
  961. def testTopLevelExtensionsForOptionalScalar(self):
  962. extendee_proto = unittest_pb2.TestAllExtensions()
  963. extension = unittest_pb2.optional_int32_extension
  964. self.assertTrue(not extendee_proto.HasExtension(extension))
  965. self.assertEqual(0, extendee_proto.Extensions[extension])
  966. # As with normal scalar fields, just doing a read doesn't actually set the
  967. # "has" bit.
  968. self.assertTrue(not extendee_proto.HasExtension(extension))
  969. # Actually set the thing.
  970. extendee_proto.Extensions[extension] = 23
  971. self.assertEqual(23, extendee_proto.Extensions[extension])
  972. self.assertTrue(extendee_proto.HasExtension(extension))
  973. # Ensure that clearing works as well.
  974. extendee_proto.ClearExtension(extension)
  975. self.assertEqual(0, extendee_proto.Extensions[extension])
  976. self.assertTrue(not extendee_proto.HasExtension(extension))
  977. def testTopLevelExtensionsForRepeatedScalar(self):
  978. extendee_proto = unittest_pb2.TestAllExtensions()
  979. extension = unittest_pb2.repeated_string_extension
  980. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  981. extendee_proto.Extensions[extension].append('foo')
  982. self.assertEqual(['foo'], extendee_proto.Extensions[extension])
  983. string_list = extendee_proto.Extensions[extension]
  984. extendee_proto.ClearExtension(extension)
  985. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  986. self.assertTrue(string_list is not extendee_proto.Extensions[extension])
  987. # Shouldn't be allowed to do Extensions[extension] = 'a'
  988. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  989. extension, 'a')
  990. def testTopLevelExtensionsForOptionalMessage(self):
  991. extendee_proto = unittest_pb2.TestAllExtensions()
  992. extension = unittest_pb2.optional_foreign_message_extension
  993. self.assertTrue(not extendee_proto.HasExtension(extension))
  994. self.assertEqual(0, extendee_proto.Extensions[extension].c)
  995. # As with normal (non-extension) fields, merely reading from the
  996. # thing shouldn't set the "has" bit.
  997. self.assertTrue(not extendee_proto.HasExtension(extension))
  998. extendee_proto.Extensions[extension].c = 23
  999. self.assertEqual(23, extendee_proto.Extensions[extension].c)
  1000. self.assertTrue(extendee_proto.HasExtension(extension))
  1001. # Save a reference here.
  1002. foreign_message = extendee_proto.Extensions[extension]
  1003. extendee_proto.ClearExtension(extension)
  1004. self.assertTrue(foreign_message is not extendee_proto.Extensions[extension])
  1005. # Setting a field on foreign_message now shouldn't set
  1006. # any "has" bits on extendee_proto.
  1007. foreign_message.c = 42
  1008. self.assertEqual(42, foreign_message.c)
  1009. self.assertTrue(foreign_message.HasField('c'))
  1010. self.assertTrue(not extendee_proto.HasExtension(extension))
  1011. # Shouldn't be allowed to do Extensions[extension] = 'a'
  1012. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  1013. extension, 'a')
  1014. def testTopLevelExtensionsForRepeatedMessage(self):
  1015. extendee_proto = unittest_pb2.TestAllExtensions()
  1016. extension = unittest_pb2.repeatedgroup_extension
  1017. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  1018. group = extendee_proto.Extensions[extension].add()
  1019. group.a = 23
  1020. self.assertEqual(23, extendee_proto.Extensions[extension][0].a)
  1021. group.a = 42
  1022. self.assertEqual(42, extendee_proto.Extensions[extension][0].a)
  1023. group_list = extendee_proto.Extensions[extension]
  1024. extendee_proto.ClearExtension(extension)
  1025. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  1026. self.assertTrue(group_list is not extendee_proto.Extensions[extension])
  1027. # Shouldn't be allowed to do Extensions[extension] = 'a'
  1028. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  1029. extension, 'a')
  1030. def testNestedExtensions(self):
  1031. extendee_proto = unittest_pb2.TestAllExtensions()
  1032. extension = unittest_pb2.TestRequired.single
  1033. # We just test the non-repeated case.
  1034. self.assertTrue(not extendee_proto.HasExtension(extension))
  1035. required = extendee_proto.Extensions[extension]
  1036. self.assertEqual(0, required.a)
  1037. self.assertTrue(not extendee_proto.HasExtension(extension))
  1038. required.a = 23
  1039. self.assertEqual(23, extendee_proto.Extensions[extension].a)
  1040. self.assertTrue(extendee_proto.HasExtension(extension))
  1041. extendee_proto.ClearExtension(extension)
  1042. self.assertTrue(required is not extendee_proto.Extensions[extension])
  1043. self.assertTrue(not extendee_proto.HasExtension(extension))
  1044. def testRegisteredExtensions(self):
  1045. self.assertTrue('protobuf_unittest.optional_int32_extension' in
  1046. unittest_pb2.TestAllExtensions._extensions_by_name)
  1047. self.assertTrue(1 in unittest_pb2.TestAllExtensions._extensions_by_number)
  1048. # Make sure extensions haven't been registered into types that shouldn't
  1049. # have any.
  1050. self.assertEqual(0, len(unittest_pb2.TestAllTypes._extensions_by_name))
  1051. # If message A directly contains message B, and
  1052. # a.HasField('b') is currently False, then mutating any
  1053. # extension in B should change a.HasField('b') to True
  1054. # (and so on up the object tree).
  1055. def testHasBitsForAncestorsOfExtendedMessage(self):
  1056. # Optional scalar extension.
  1057. toplevel = more_extensions_pb2.TopLevelMessage()
  1058. self.assertTrue(not toplevel.HasField('submessage'))
  1059. self.assertEqual(0, toplevel.submessage.Extensions[
  1060. more_extensions_pb2.optional_int_extension])
  1061. self.assertTrue(not toplevel.HasField('submessage'))
  1062. toplevel.submessage.Extensions[
  1063. more_extensions_pb2.optional_int_extension] = 23
  1064. self.assertEqual(23, toplevel.submessage.Extensions[
  1065. more_extensions_pb2.optional_int_extension])
  1066. self.assertTrue(toplevel.HasField('submessage'))
  1067. # Repeated scalar extension.
  1068. toplevel = more_extensions_pb2.TopLevelMessage()
  1069. self.assertTrue(not toplevel.HasField('submessage'))
  1070. self.assertEqual([], toplevel.submessage.Extensions[
  1071. more_extensions_pb2.repeated_int_extension])
  1072. self.assertTrue(not toplevel.HasField('submessage'))
  1073. toplevel.submessage.Extensions[
  1074. more_extensions_pb2.repeated_int_extension].append(23)
  1075. self.assertEqual([23], toplevel.submessage.Extensions[
  1076. more_extensions_pb2.repeated_int_extension])
  1077. self.assertTrue(toplevel.HasField('submessage'))
  1078. # Optional message extension.
  1079. toplevel = more_extensions_pb2.TopLevelMessage()
  1080. self.assertTrue(not toplevel.HasField('submessage'))
  1081. self.assertEqual(0, toplevel.submessage.Extensions[
  1082. more_extensions_pb2.optional_message_extension].foreign_message_int)
  1083. self.assertTrue(not toplevel.HasField('submessage'))
  1084. toplevel.submessage.Extensions[
  1085. more_extensions_pb2.optional_message_extension].foreign_message_int = 23
  1086. self.assertEqual(23, toplevel.submessage.Extensions[
  1087. more_extensions_pb2.optional_message_extension].foreign_message_int)
  1088. self.assertTrue(toplevel.HasField('submessage'))
  1089. # Repeated message extension.
  1090. toplevel = more_extensions_pb2.TopLevelMessage()
  1091. self.assertTrue(not toplevel.HasField('submessage'))
  1092. self.assertEqual(0, len(toplevel.submessage.Extensions[
  1093. more_extensions_pb2.repeated_message_extension]))
  1094. self.assertTrue(not toplevel.HasField('submessage'))
  1095. foreign = toplevel.submessage.Extensions[
  1096. more_extensions_pb2.repeated_message_extension].add()
  1097. self.assertEqual(foreign, toplevel.submessage.Extensions[
  1098. more_extensions_pb2.repeated_message_extension][0])
  1099. self.assertTrue(toplevel.HasField('submessage'))
  1100. def testDisconnectionAfterClearingEmptyMessage(self):
  1101. toplevel = more_extensions_pb2.TopLevelMessage()
  1102. extendee_proto = toplevel.submessage
  1103. extension = more_extensions_pb2.optional_message_extension
  1104. extension_proto = extendee_proto.Extensions[extension]
  1105. extendee_proto.ClearExtension(extension)
  1106. extension_proto.foreign_message_int = 23
  1107. self.assertTrue(extension_proto is not extendee_proto.Extensions[extension])
  1108. def testExtensionFailureModes(self):
  1109. extendee_proto = unittest_pb2.TestAllExtensions()
  1110. # Try non-extension-handle arguments to HasExtension,
  1111. # ClearExtension(), and Extensions[]...
  1112. self.assertRaises(KeyError, extendee_proto.HasExtension, 1234)
  1113. self.assertRaises(KeyError, extendee_proto.ClearExtension, 1234)
  1114. self.assertRaises(KeyError, extendee_proto.Extensions.__getitem__, 1234)
  1115. self.assertRaises(KeyError, extendee_proto.Extensions.__setitem__, 1234, 5)
  1116. # Try something that *is* an extension handle, just not for
  1117. # this message...
  1118. for unknown_handle in (more_extensions_pb2.optional_int_extension,
  1119. more_extensions_pb2.optional_message_extension,
  1120. more_extensions_pb2.repeated_int_extension,
  1121. more_extensions_pb2.repeated_message_extension):
  1122. self.assertRaises(KeyError, extendee_proto.HasExtension,
  1123. unknown_handle)
  1124. self.assertRaises(KeyError, extendee_proto.ClearExtension,
  1125. unknown_handle)
  1126. self.assertRaises(KeyError, extendee_proto.Extensions.__getitem__,
  1127. unknown_handle)
  1128. self.assertRaises(KeyError, extendee_proto.Extensions.__setitem__,
  1129. unknown_handle, 5)
  1130. # Try call HasExtension() with a valid handle, but for a
  1131. # *repeated* field. (Just as with non-extension repeated
  1132. # fields, Has*() isn't supported for extension repeated fields).
  1133. self.assertRaises(KeyError, extendee_proto.HasExtension,
  1134. unittest_pb2.repeated_string_extension)
  1135. def testStaticParseFrom(self):
  1136. proto1 = unittest_pb2.TestAllTypes()
  1137. test_util.SetAllFields(proto1)
  1138. string1 = proto1.SerializeToString()
  1139. proto2 = unittest_pb2.TestAllTypes.FromString(string1)
  1140. # Messages should be equal.
  1141. self.assertEqual(proto2, proto1)
  1142. def testMergeFromSingularField(self):
  1143. # Test merge with just a singular field.
  1144. proto1 = unittest_pb2.TestAllTypes()
  1145. proto1.optional_int32 = 1
  1146. proto2 = unittest_pb2.TestAllTypes()
  1147. # This shouldn't get overwritten.
  1148. proto2.optional_string = 'value'
  1149. proto2.MergeFrom(proto1)
  1150. self.assertEqual(1, proto2.optional_int32)
  1151. self.assertEqual('value', proto2.optional_string)
  1152. def testMergeFromRepeatedField(self):
  1153. # Test merge with just a repeated field.
  1154. proto1 = unittest_pb2.TestAllTypes()
  1155. proto1.repeated_int32.append(1)
  1156. proto1.repeated_int32.append(2)
  1157. proto2 = unittest_pb2.TestAllTypes()
  1158. proto2.repeated_int32.append(0)
  1159. proto2.MergeFrom(proto1)
  1160. self.assertEqual(0, proto2.repeated_int32[0])
  1161. self.assertEqual(1, proto2.repeated_int32[1])
  1162. self.assertEqual(2, proto2.repeated_int32[2])
  1163. def testMergeFromOptionalGroup(self):
  1164. # Test merge with an optional group.
  1165. proto1 = unittest_pb2.TestAllTypes()
  1166. proto1.optionalgroup.a = 12
  1167. proto2 = unittest_pb2.TestAllTypes()
  1168. proto2.MergeFrom(proto1)
  1169. self.assertEqual(12, proto2.optionalgroup.a)
  1170. def testMergeFromRepeatedNestedMessage(self):
  1171. # Test merge with a repeated nested message.
  1172. proto1 = unittest_pb2.TestAllTypes()
  1173. m = proto1.repeated_nested_message.add()
  1174. m.bb = 123
  1175. m = proto1.repeated_nested_message.add()
  1176. m.bb = 321
  1177. proto2 = unittest_pb2.TestAllTypes()
  1178. m = proto2.repeated_nested_message.add()
  1179. m.bb = 999
  1180. proto2.MergeFrom(proto1)
  1181. self.assertEqual(999, proto2.repeated_nested_message[0].bb)
  1182. self.assertEqual(123, proto2.repeated_nested_message[1].bb)
  1183. self.assertEqual(321, proto2.repeated_nested_message[2].bb)
  1184. proto3 = unittest_pb2.TestAllTypes()
  1185. proto3.repeated_nested_message.MergeFrom(proto2.repeated_nested_message)
  1186. self.assertEqual(999, proto3.repeated_nested_message[0].bb)
  1187. self.assertEqual(123, proto3.repeated_nested_message[1].bb)
  1188. self.assertEqual(321, proto3.repeated_nested_message[2].bb)
  1189. def testMergeFromAllFields(self):
  1190. # With all fields set.
  1191. proto1 = unittest_pb2.TestAllTypes()
  1192. test_util.SetAllFields(proto1)
  1193. proto2 = unittest_pb2.TestAllTypes()
  1194. proto2.MergeFrom(proto1)
  1195. # Messages should be equal.
  1196. self.assertEqual(proto2, proto1)
  1197. # Serialized string should be equal too.
  1198. string1 = proto1.SerializeToString()
  1199. string2 = proto2.SerializeToString()
  1200. self.assertEqual(string1, string2)
  1201. def testMergeFromExtensionsSingular(self):
  1202. proto1 = unittest_pb2.TestAllExtensions()
  1203. proto1.Extensions[unittest_pb2.optional_int32_extension] = 1
  1204. proto2 = unittest_pb2.TestAllExtensions()
  1205. proto2.MergeFrom(proto1)
  1206. self.assertEqual(
  1207. 1, proto2.Extensions[unittest_pb2.optional_int32_extension])
  1208. def testMergeFromExtensionsRepeated(self):
  1209. proto1 = unittest_pb2.TestAllExtensions()
  1210. proto1.Extensions[unittest_pb2.repeated_int32_extension].append(1)
  1211. proto1.Extensions[unittest_pb2.repeated_int32_extension].append(2)
  1212. proto2 = unittest_pb2.TestAllExtensions()
  1213. proto2.Extensions[unittest_pb2.repeated_int32_extension].append(0)
  1214. proto2.MergeFrom(proto1)
  1215. self.assertEqual(
  1216. 3, len(proto2.Extensions[unittest_pb2.repeated_int32_extension]))
  1217. self.assertEqual(
  1218. 0, proto2.Extensions[unittest_pb2.repeated_int32_extension][0])
  1219. self.assertEqual(
  1220. 1, proto2.Extensions[unittest_pb2.repeated_int32_extension][1])
  1221. self.assertEqual(
  1222. 2, proto2.Extensions[unittest_pb2.repeated_int32_extension][2])
  1223. def testMergeFromExtensionsNestedMessage(self):
  1224. proto1 = unittest_pb2.TestAllExtensions()
  1225. ext1 = proto1.Extensions[
  1226. unittest_pb2.repeated_nested_message_extension]
  1227. m = ext1.add()
  1228. m.bb = 222
  1229. m = ext1.add()
  1230. m.bb = 333
  1231. proto2 = unittest_pb2.TestAllExtensions()
  1232. ext2 = proto2.Extensions[
  1233. unittest_pb2.repeated_nested_message_extension]
  1234. m = ext2.add()
  1235. m.bb = 111
  1236. proto2.MergeFrom(proto1)
  1237. ext2 = proto2.Extensions[
  1238. unittest_pb2.repeated_nested_message_extension]
  1239. self.assertEqual(3, len(ext2))
  1240. self.assertEqual(111, ext2[0].bb)
  1241. self.assertEqual(222, ext2[1].bb)
  1242. self.assertEqual(333, ext2[2].bb)
  1243. def testMergeFromBug(self):
  1244. message1 = unittest_pb2.TestAllTypes()
  1245. message2 = unittest_pb2.TestAllTypes()
  1246. # Cause optional_nested_message to be instantiated within message1, even
  1247. # though it is not considered to be "present".
  1248. message1.optional_nested_message
  1249. self.assertFalse(message1.HasField('optional_nested_message'))
  1250. # Merge into message2. This should not instantiate the field is message2.
  1251. message2.MergeFrom(message1)
  1252. self.assertFalse(message2.HasField('optional_nested_message'))
  1253. def testCopyFromSingularField(self):
  1254. # Test copy with just a singular field.
  1255. proto1 = unittest_pb2.TestAllTypes()
  1256. proto1.optional_int32 = 1
  1257. proto1.optional_string = 'important-text'
  1258. proto2 = unittest_pb2.TestAllTypes()
  1259. proto2.optional_string = 'value'
  1260. proto2.CopyFrom(proto1)
  1261. self.assertEqual(1, proto2.optional_int32)
  1262. self.assertEqual('important-text', proto2.optional_string)
  1263. def testCopyFromRepeatedField(self):
  1264. # Test copy with a repeated field.
  1265. proto1 = unittest_pb2.TestAllTypes()
  1266. proto1.repeated_int32.append(1)
  1267. proto1.repeated_int32.append(2)
  1268. proto2 = unittest_pb2.TestAllTypes()
  1269. proto2.repeated_int32.append(0)
  1270. proto2.CopyFrom(proto1)
  1271. self.assertEqual(1, proto2.repeated_int32[0])
  1272. self.assertEqual(2, proto2.repeated_int32[1])
  1273. def testCopyFromAllFields(self):
  1274. # With all fields set.
  1275. proto1 = unittest_pb2.TestAllTypes()
  1276. test_util.SetAllFields(proto1)
  1277. proto2 = unittest_pb2.TestAllTypes()
  1278. proto2.CopyFrom(proto1)
  1279. # Messages should be equal.
  1280. self.assertEqual(proto2, proto1)
  1281. # Serialized string should be equal too.
  1282. string1 = proto1.SerializeToString()
  1283. string2 = proto2.SerializeToString()
  1284. self.assertEqual(string1, string2)
  1285. def testCopyFromSelf(self):
  1286. proto1 = unittest_pb2.TestAllTypes()
  1287. proto1.repeated_int32.append(1)
  1288. proto1.optional_int32 = 2
  1289. proto1.optional_string = 'important-text'
  1290. proto1.CopyFrom(proto1)
  1291. self.assertEqual(1, proto1.repeated_int32[0])
  1292. self.assertEqual(2, proto1.optional_int32)
  1293. self.assertEqual('important-text', proto1.optional_string)
  1294. def testCopyFromBadType(self):
  1295. # The python implementation doesn't raise an exception in this
  1296. # case. In theory it should.
  1297. if api_implementation.Type() == 'python':
  1298. return
  1299. proto1 = unittest_pb2.TestAllTypes()
  1300. proto2 = unittest_pb2.TestAllExtensions()
  1301. self.assertRaises(TypeError, proto1.CopyFrom, proto2)
  1302. def testDeepCopy(self):
  1303. proto1 = unittest_pb2.TestAllTypes()
  1304. proto1.optional_int32 = 1
  1305. proto2 = copy.deepcopy(proto1)
  1306. self.assertEqual(1, proto2.optional_int32)
  1307. proto1.repeated_int32.append(2)
  1308. proto1.repeated_int32.append(3)
  1309. container = copy.deepcopy(proto1.repeated_int32)
  1310. self.assertEqual([2, 3], container)
  1311. # TODO(anuraag): Implement deepcopy for repeated composite / extension dict
  1312. def testClear(self):
  1313. proto = unittest_pb2.TestAllTypes()
  1314. # C++ implementation does not support lazy fields right now so leave it
  1315. # out for now.
  1316. if api_implementation.Type() == 'python':
  1317. test_util.SetAllFields(proto)
  1318. else:
  1319. test_util.SetAllNonLazyFields(proto)
  1320. # Clear the message.
  1321. proto.Clear()
  1322. self.assertEqual(proto.ByteSize(), 0)
  1323. empty_proto = unittest_pb2.TestAllTypes()
  1324. self.assertEqual(proto, empty_proto)
  1325. # Test if extensions which were set are cleared.
  1326. proto = unittest_pb2.TestAllExtensions()
  1327. test_util.SetAllExtensions(proto)
  1328. # Clear the message.
  1329. proto.Clear()
  1330. self.assertEqual(proto.ByteSize(), 0)
  1331. empty_proto = unittest_pb2.TestAllExtensions()
  1332. self.assertEqual(proto, empty_proto)
  1333. def testDisconnectingBeforeClear(self):
  1334. proto = unittest_pb2.TestAllTypes()
  1335. nested = proto.optional_nested_message
  1336. proto.Clear()
  1337. self.assertTrue(nested is not proto.optional_nested_message)
  1338. nested.bb = 23
  1339. self.assertTrue(not proto.HasField('optional_nested_message'))
  1340. self.assertEqual(0, proto.optional_nested_message.bb)
  1341. proto = unittest_pb2.TestAllTypes()
  1342. nested = proto.optional_nested_message
  1343. nested.bb = 5
  1344. foreign = proto.optional_foreign_message
  1345. foreign.c = 6
  1346. proto.Clear()
  1347. self.assertTrue(nested is not proto.optional_nested_message)
  1348. self.assertTrue(foreign is not proto.optional_foreign_message)
  1349. self.assertEqual(5, nested.bb)
  1350. self.assertEqual(6, foreign.c)
  1351. nested.bb = 15
  1352. foreign.c = 16
  1353. self.assertFalse(proto.HasField('optional_nested_message'))
  1354. self.assertEqual(0, proto.optional_nested_message.bb)
  1355. self.assertFalse(proto.HasField('optional_foreign_message'))
  1356. self.assertEqual(0, proto.optional_foreign_message.c)
  1357. def testOneOf(self):
  1358. proto = unittest_pb2.TestAllTypes()
  1359. proto.oneof_uint32 = 10
  1360. proto.oneof_nested_message.bb = 11
  1361. self.assertEqual(11, proto.oneof_nested_message.bb)
  1362. self.assertFalse(proto.HasField('oneof_uint32'))
  1363. nested = proto.oneof_nested_message
  1364. proto.oneof_string = 'abc'
  1365. self.assertEqual('abc', proto.oneof_string)
  1366. self.assertEqual(11, nested.bb)
  1367. self.assertFalse(proto.HasField('oneof_nested_message'))
  1368. def assertInitialized(self, proto):
  1369. self.assertTrue(proto.IsInitialized())
  1370. # Neither method should raise an exception.
  1371. proto.SerializeToString()
  1372. proto.SerializePartialToString()
  1373. def assertNotInitialized(self, proto):
  1374. self.assertFalse(proto.IsInitialized())
  1375. self.assertRaises(message.EncodeError, proto.SerializeToString)
  1376. # "Partial" serialization doesn't care if message is uninitialized.
  1377. proto.SerializePartialToString()
  1378. def testIsInitialized(self):
  1379. # Trivial cases - all optional fields and extensions.
  1380. proto = unittest_pb2.TestAllTypes()
  1381. self.assertInitialized(proto)
  1382. proto = unittest_pb2.TestAllExtensions()
  1383. self.assertInitialized(proto)
  1384. # The case of uninitialized required fields.
  1385. proto = unittest_pb2.TestRequired()
  1386. self.assertNotInitialized(proto)
  1387. proto.a = proto.b = proto.c = 2
  1388. self.assertInitialized(proto)
  1389. # The case of uninitialized submessage.
  1390. proto = unittest_pb2.TestRequiredForeign()
  1391. self.assertInitialized(proto)
  1392. proto.optional_message.a = 1
  1393. self.assertNotInitialized(proto)
  1394. proto.optional_message.b = 0
  1395. proto.optional_message.c = 0
  1396. self.assertInitialized(proto)
  1397. # Uninitialized repeated submessage.
  1398. message1 = proto.repeated_message.add()
  1399. self.assertNotInitialized(proto)
  1400. message1.a = message1.b = message1.c = 0
  1401. self.assertInitialized(proto)
  1402. # Uninitialized repeated group in an extension.
  1403. proto = unittest_pb2.TestAllExtensions()
  1404. extension = unittest_pb2.TestRequired.multi
  1405. message1 = proto.Extensions[extension].add()
  1406. message2 = proto.Extensions[extension].add()
  1407. self.assertNotInitialized(proto)
  1408. message1.a = 1
  1409. message1.b = 1
  1410. message1.c = 1
  1411. self.assertNotInitialized(proto)
  1412. message2.a = 2
  1413. message2.b = 2
  1414. message2.c = 2
  1415. self.assertInitialized(proto)
  1416. # Uninitialized nonrepeated message in an extension.
  1417. proto = unittest_pb2.TestAllExtensions()
  1418. extension = unittest_pb2.TestRequired.single
  1419. proto.Extensions[extension].a = 1
  1420. self.assertNotInitialized(proto)
  1421. proto.Extensions[extension].b = 2
  1422. proto.Extensions[extension].c = 3
  1423. self.assertInitialized(proto)
  1424. # Try passing an errors list.
  1425. errors = []
  1426. proto = unittest_pb2.TestRequired()
  1427. self.assertFalse(proto.IsInitialized(errors))
  1428. self.assertEqual(errors, ['a', 'b', 'c'])
  1429. @unittest.skipIf(
  1430. api_implementation.Type() != 'cpp' or api_implementation.Version() != 2,
  1431. 'Errors are only available from the most recent C++ implementation.')
  1432. def testFileDescriptorErrors(self):
  1433. file_name = 'test_file_descriptor_errors.proto'
  1434. package_name = 'test_file_descriptor_errors.proto'
  1435. file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
  1436. file_descriptor_proto.name = file_name
  1437. file_descriptor_proto.package = package_name
  1438. m1 = file_descriptor_proto.message_type.add()
  1439. m1.name = 'msg1'
  1440. # Compiles the proto into the C++ descriptor pool
  1441. descriptor.FileDescriptor(
  1442. file_name,
  1443. package_name,
  1444. serialized_pb=file_descriptor_proto.SerializeToString())
  1445. # Add a FileDescriptorProto that has duplicate symbols
  1446. another_file_name = 'another_test_file_descriptor_errors.proto'
  1447. file_descriptor_proto.name = another_file_name
  1448. m2 = file_descriptor_proto.message_type.add()
  1449. m2.name = 'msg2'
  1450. with self.assertRaises(TypeError) as cm:
  1451. descriptor.FileDescriptor(
  1452. another_file_name,
  1453. package_name,
  1454. serialized_pb=file_descriptor_proto.SerializeToString())
  1455. self.assertTrue(hasattr(cm, 'exception'), '%s not raised' %
  1456. getattr(cm.expected, '__name__', cm.expected))
  1457. self.assertIn('test_file_descriptor_errors.proto', str(cm.exception))
  1458. # Error message will say something about this definition being a
  1459. # duplicate, though we don't check the message exactly to avoid a
  1460. # dependency on the C++ logging code.
  1461. self.assertIn('test_file_descriptor_errors.msg1', str(cm.exception))
  1462. def testStringUTF8Encoding(self):
  1463. proto = unittest_pb2.TestAllTypes()
  1464. # Assignment of a unicode object to a field of type 'bytes' is not allowed.
  1465. self.assertRaises(TypeError,
  1466. setattr, proto, 'optional_bytes', u'unicode object')
  1467. # Check that the default value is of python's 'unicode' type.
  1468. self.assertEqual(type(proto.optional_string), six.text_type)
  1469. proto.optional_string = six.text_type('Testing')
  1470. self.assertEqual(proto.optional_string, str('Testing'))
  1471. # Assign a value of type 'str' which can be encoded in UTF-8.
  1472. proto.optional_string = str('Testing')
  1473. self.assertEqual(proto.optional_string, six.text_type('Testing'))
  1474. # Try to assign a 'bytes' object which contains non-UTF-8.
  1475. self.assertRaises(ValueError,
  1476. setattr, proto, 'optional_string', b'a\x80a')
  1477. # No exception: Assign already encoded UTF-8 bytes to a string field.
  1478. utf8_bytes = u'Тест'.encode('utf-8')
  1479. proto.optional_string = utf8_bytes
  1480. # No exception: Assign the a non-ascii unicode object.
  1481. proto.optional_string = u'Тест'
  1482. # No exception thrown (normal str assignment containing ASCII).
  1483. proto.optional_string = 'abc'
  1484. def testStringUTF8Serialization(self):
  1485. proto = message_set_extensions_pb2.TestMessageSet()
  1486. extension_message = message_set_extensions_pb2.TestMessageSetExtension2
  1487. extension = extension_message.message_set_extension
  1488. test_utf8 = u'Тест'
  1489. test_utf8_bytes = test_utf8.encode('utf-8')
  1490. # 'Test' in another language, using UTF-8 charset.
  1491. proto.Extensions[extension].str = test_utf8
  1492. # Serialize using the MessageSet wire format (this is specified in the
  1493. # .proto file).
  1494. serialized = proto.SerializeToString()
  1495. # Check byte size.
  1496. self.assertEqual(proto.ByteSize(), len(serialized))
  1497. raw = unittest_mset_pb2.RawMessageSet()
  1498. bytes_read = raw.MergeFromString(serialized)
  1499. self.assertEqual(len(serialized), bytes_read)
  1500. message2 = message_set_extensions_pb2.TestMessageSetExtension2()
  1501. self.assertEqual(1, len(raw.item))
  1502. # Check that the type_id is the same as the tag ID in the .proto file.
  1503. self.assertEqual(raw.item[0].type_id, 98418634)
  1504. # Check the actual bytes on the wire.
  1505. self.assertTrue(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 = message_set_extensions_pb2.TestMessageSet()
  2071. extension_message1 = message_set_extensions_pb2.TestMessageSetExtension1
  2072. extension_message2 = message_set_extensions_pb2.TestMessageSetExtension2
  2073. extension1 = extension_message1.message_set_extension
  2074. extension2 = extension_message2.message_set_extension
  2075. extension3 = message_set_extensions_pb2.message_set_extension3
  2076. proto.Extensions[extension1].i = 123
  2077. proto.Extensions[extension2].str = 'foo'
  2078. proto.Extensions[extension3].text = 'bar'
  2079. # Serialize using the MessageSet wire format (this is specified in the
  2080. # .proto file).
  2081. serialized = proto.SerializeToString()
  2082. raw = unittest_mset_pb2.RawMessageSet()
  2083. self.assertEqual(False,
  2084. raw.DESCRIPTOR.GetOptions().message_set_wire_format)
  2085. self.assertEqual(
  2086. len(serialized),
  2087. raw.MergeFromString(serialized))
  2088. self.assertEqual(3, len(raw.item))
  2089. message1 = message_set_extensions_pb2.TestMessageSetExtension1()
  2090. self.assertEqual(
  2091. len(raw.item[0].message),
  2092. message1.MergeFromString(raw.item[0].message))
  2093. self.assertEqual(123, message1.i)
  2094. message2 = message_set_extensions_pb2.TestMessageSetExtension2()
  2095. self.assertEqual(
  2096. len(raw.item[1].message),
  2097. message2.MergeFromString(raw.item[1].message))
  2098. self.assertEqual('foo', message2.str)
  2099. message3 = message_set_extensions_pb2.TestMessageSetExtension3()
  2100. self.assertEqual(
  2101. len(raw.item[2].message),
  2102. message3.MergeFromString(raw.item[2].message))
  2103. self.assertEqual('bar', message3.text)
  2104. # Deserialize using the MessageSet wire format.
  2105. proto2 = message_set_extensions_pb2.TestMessageSet()
  2106. self.assertEqual(
  2107. len(serialized),
  2108. proto2.MergeFromString(serialized))
  2109. self.assertEqual(123, proto2.Extensions[extension1].i)
  2110. self.assertEqual('foo', proto2.Extensions[extension2].str)
  2111. self.assertEqual('bar', proto2.Extensions[extension3].text)
  2112. # Check byte size.
  2113. self.assertEqual(proto2.ByteSize(), len(serialized))
  2114. self.assertEqual(proto.ByteSize(), len(serialized))
  2115. def testMessageSetWireFormatUnknownExtension(self):
  2116. # Create a message using the message set wire format with an unknown
  2117. # message.
  2118. raw = unittest_mset_pb2.RawMessageSet()
  2119. # Add an item.
  2120. item = raw.item.add()
  2121. item.type_id = 98418603
  2122. extension_message1 = message_set_extensions_pb2.TestMessageSetExtension1
  2123. message1 = message_set_extensions_pb2.TestMessageSetExtension1()
  2124. message1.i = 12345
  2125. item.message = message1.SerializeToString()
  2126. # Add a second, unknown extension.
  2127. item = raw.item.add()
  2128. item.type_id = 98418604
  2129. extension_message1 = message_set_extensions_pb2.TestMessageSetExtension1
  2130. message1 = message_set_extensions_pb2.TestMessageSetExtension1()
  2131. message1.i = 12346
  2132. item.message = message1.SerializeToString()
  2133. # Add another unknown extension.
  2134. item = raw.item.add()
  2135. item.type_id = 98418605
  2136. message1 = message_set_extensions_pb2.TestMessageSetExtension2()
  2137. message1.str = 'foo'
  2138. item.message = message1.SerializeToString()
  2139. serialized = raw.SerializeToString()
  2140. # Parse message using the message set wire format.
  2141. proto = message_set_extensions_pb2.TestMessageSet()
  2142. self.assertEqual(
  2143. len(serialized),
  2144. proto.MergeFromString(serialized))
  2145. # Check that the message parsed well.
  2146. extension_message1 = message_set_extensions_pb2.TestMessageSetExtension1
  2147. extension1 = extension_message1.message_set_extension
  2148. self.assertEqual(12345, proto.Extensions[extension1].i)
  2149. def testUnknownFields(self):
  2150. proto = unittest_pb2.TestAllTypes()
  2151. test_util.SetAllFields(proto)
  2152. serialized = proto.SerializeToString()
  2153. # The empty message should be parsable with all of the fields
  2154. # unknown.
  2155. proto2 = unittest_pb2.TestEmptyMessage()
  2156. # Parsing this message should succeed.
  2157. self.assertEqual(
  2158. len(serialized),
  2159. proto2.MergeFromString(serialized))
  2160. # Now test with a int64 field set.
  2161. proto = unittest_pb2.TestAllTypes()
  2162. proto.optional_int64 = 0x0fffffffffffffff
  2163. serialized = proto.SerializeToString()
  2164. # The empty message should be parsable with all of the fields
  2165. # unknown.
  2166. proto2 = unittest_pb2.TestEmptyMessage()
  2167. # Parsing this message should succeed.
  2168. self.assertEqual(
  2169. len(serialized),
  2170. proto2.MergeFromString(serialized))
  2171. def _CheckRaises(self, exc_class, callable_obj, exception):
  2172. """This method checks if the excpetion type and message are as expected."""
  2173. try:
  2174. callable_obj()
  2175. except exc_class as ex:
  2176. # Check if the exception message is the right one.
  2177. self.assertEqual(exception, str(ex))
  2178. return
  2179. else:
  2180. raise self.failureException('%s not raised' % str(exc_class))
  2181. def testSerializeUninitialized(self):
  2182. proto = unittest_pb2.TestRequired()
  2183. self._CheckRaises(
  2184. message.EncodeError,
  2185. proto.SerializeToString,
  2186. 'Message protobuf_unittest.TestRequired is missing required fields: '
  2187. 'a,b,c')
  2188. # Shouldn't raise exceptions.
  2189. partial = proto.SerializePartialToString()
  2190. proto2 = unittest_pb2.TestRequired()
  2191. self.assertFalse(proto2.HasField('a'))
  2192. # proto2 ParseFromString does not check that required fields are set.
  2193. proto2.ParseFromString(partial)
  2194. self.assertFalse(proto2.HasField('a'))
  2195. proto.a = 1
  2196. self._CheckRaises(
  2197. message.EncodeError,
  2198. proto.SerializeToString,
  2199. 'Message protobuf_unittest.TestRequired is missing required fields: b,c')
  2200. # Shouldn't raise exceptions.
  2201. partial = proto.SerializePartialToString()
  2202. proto.b = 2
  2203. self._CheckRaises(
  2204. message.EncodeError,
  2205. proto.SerializeToString,
  2206. 'Message protobuf_unittest.TestRequired is missing required fields: c')
  2207. # Shouldn't raise exceptions.
  2208. partial = proto.SerializePartialToString()
  2209. proto.c = 3
  2210. serialized = proto.SerializeToString()
  2211. # Shouldn't raise exceptions.
  2212. partial = proto.SerializePartialToString()
  2213. proto2 = unittest_pb2.TestRequired()
  2214. self.assertEqual(
  2215. len(serialized),
  2216. proto2.MergeFromString(serialized))
  2217. self.assertEqual(1, proto2.a)
  2218. self.assertEqual(2, proto2.b)
  2219. self.assertEqual(3, proto2.c)
  2220. self.assertEqual(
  2221. len(partial),
  2222. proto2.MergeFromString(partial))
  2223. self.assertEqual(1, proto2.a)
  2224. self.assertEqual(2, proto2.b)
  2225. self.assertEqual(3, proto2.c)
  2226. def testSerializeUninitializedSubMessage(self):
  2227. proto = unittest_pb2.TestRequiredForeign()
  2228. # Sub-message doesn't exist yet, so this succeeds.
  2229. proto.SerializeToString()
  2230. proto.optional_message.a = 1
  2231. self._CheckRaises(
  2232. message.EncodeError,
  2233. proto.SerializeToString,
  2234. 'Message protobuf_unittest.TestRequiredForeign '
  2235. 'is missing required fields: '
  2236. 'optional_message.b,optional_message.c')
  2237. proto.optional_message.b = 2
  2238. proto.optional_message.c = 3
  2239. proto.SerializeToString()
  2240. proto.repeated_message.add().a = 1
  2241. proto.repeated_message.add().b = 2
  2242. self._CheckRaises(
  2243. message.EncodeError,
  2244. proto.SerializeToString,
  2245. 'Message protobuf_unittest.TestRequiredForeign is missing required fields: '
  2246. 'repeated_message[0].b,repeated_message[0].c,'
  2247. 'repeated_message[1].a,repeated_message[1].c')
  2248. proto.repeated_message[0].b = 2
  2249. proto.repeated_message[0].c = 3
  2250. proto.repeated_message[1].a = 1
  2251. proto.repeated_message[1].c = 3
  2252. proto.SerializeToString()
  2253. def testSerializeAllPackedFields(self):
  2254. first_proto = unittest_pb2.TestPackedTypes()
  2255. second_proto = unittest_pb2.TestPackedTypes()
  2256. test_util.SetAllPackedFields(first_proto)
  2257. serialized = first_proto.SerializeToString()
  2258. self.assertEqual(first_proto.ByteSize(), len(serialized))
  2259. bytes_read = second_proto.MergeFromString(serialized)
  2260. self.assertEqual(second_proto.ByteSize(), bytes_read)
  2261. self.assertEqual(first_proto, second_proto)
  2262. def testSerializeAllPackedExtensions(self):
  2263. first_proto = unittest_pb2.TestPackedExtensions()
  2264. second_proto = unittest_pb2.TestPackedExtensions()
  2265. test_util.SetAllPackedExtensions(first_proto)
  2266. serialized = first_proto.SerializeToString()
  2267. bytes_read = second_proto.MergeFromString(serialized)
  2268. self.assertEqual(second_proto.ByteSize(), bytes_read)
  2269. self.assertEqual(first_proto, second_proto)
  2270. def testMergePackedFromStringWhenSomeFieldsAlreadySet(self):
  2271. first_proto = unittest_pb2.TestPackedTypes()
  2272. first_proto.packed_int32.extend([1, 2])
  2273. first_proto.packed_double.append(3.0)
  2274. serialized = first_proto.SerializeToString()
  2275. second_proto = unittest_pb2.TestPackedTypes()
  2276. second_proto.packed_int32.append(3)
  2277. second_proto.packed_double.extend([1.0, 2.0])
  2278. second_proto.packed_sint32.append(4)
  2279. self.assertEqual(
  2280. len(serialized),
  2281. second_proto.MergeFromString(serialized))
  2282. self.assertEqual([3, 1, 2], second_proto.packed_int32)
  2283. self.assertEqual([1.0, 2.0, 3.0], second_proto.packed_double)
  2284. self.assertEqual([4], second_proto.packed_sint32)
  2285. def testPackedFieldsWireFormat(self):
  2286. proto = unittest_pb2.TestPackedTypes()
  2287. proto.packed_int32.extend([1, 2, 150, 3]) # 1 + 1 + 2 + 1 bytes
  2288. proto.packed_double.extend([1.0, 1000.0]) # 8 + 8 bytes
  2289. proto.packed_float.append(2.0) # 4 bytes, will be before double
  2290. serialized = proto.SerializeToString()
  2291. self.assertEqual(proto.ByteSize(), len(serialized))
  2292. d = _MiniDecoder(serialized)
  2293. ReadTag = d.ReadFieldNumberAndWireType
  2294. self.assertEqual((90, wire_format.WIRETYPE_LENGTH_DELIMITED), ReadTag())
  2295. self.assertEqual(1+1+1+2, d.ReadInt32())
  2296. self.assertEqual(1, d.ReadInt32())
  2297. self.assertEqual(2, d.ReadInt32())
  2298. self.assertEqual(150, d.ReadInt32())
  2299. self.assertEqual(3, d.ReadInt32())
  2300. self.assertEqual((100, wire_format.WIRETYPE_LENGTH_DELIMITED), ReadTag())
  2301. self.assertEqual(4, d.ReadInt32())
  2302. self.assertEqual(2.0, d.ReadFloat())
  2303. self.assertEqual((101, wire_format.WIRETYPE_LENGTH_DELIMITED), ReadTag())
  2304. self.assertEqual(8+8, d.ReadInt32())
  2305. self.assertEqual(1.0, d.ReadDouble())
  2306. self.assertEqual(1000.0, d.ReadDouble())
  2307. self.assertTrue(d.EndOfStream())
  2308. def testParsePackedFromUnpacked(self):
  2309. unpacked = unittest_pb2.TestUnpackedTypes()
  2310. test_util.SetAllUnpackedFields(unpacked)
  2311. packed = unittest_pb2.TestPackedTypes()
  2312. serialized = unpacked.SerializeToString()
  2313. self.assertEqual(
  2314. len(serialized),
  2315. packed.MergeFromString(serialized))
  2316. expected = unittest_pb2.TestPackedTypes()
  2317. test_util.SetAllPackedFields(expected)
  2318. self.assertEqual(expected, packed)
  2319. def testParseUnpackedFromPacked(self):
  2320. packed = unittest_pb2.TestPackedTypes()
  2321. test_util.SetAllPackedFields(packed)
  2322. unpacked = unittest_pb2.TestUnpackedTypes()
  2323. serialized = packed.SerializeToString()
  2324. self.assertEqual(
  2325. len(serialized),
  2326. unpacked.MergeFromString(serialized))
  2327. expected = unittest_pb2.TestUnpackedTypes()
  2328. test_util.SetAllUnpackedFields(expected)
  2329. self.assertEqual(expected, unpacked)
  2330. def testFieldNumbers(self):
  2331. proto = unittest_pb2.TestAllTypes()
  2332. self.assertEqual(unittest_pb2.TestAllTypes.NestedMessage.BB_FIELD_NUMBER, 1)
  2333. self.assertEqual(unittest_pb2.TestAllTypes.OPTIONAL_INT32_FIELD_NUMBER, 1)
  2334. self.assertEqual(unittest_pb2.TestAllTypes.OPTIONALGROUP_FIELD_NUMBER, 16)
  2335. self.assertEqual(
  2336. unittest_pb2.TestAllTypes.OPTIONAL_NESTED_MESSAGE_FIELD_NUMBER, 18)
  2337. self.assertEqual(
  2338. unittest_pb2.TestAllTypes.OPTIONAL_NESTED_ENUM_FIELD_NUMBER, 21)
  2339. self.assertEqual(unittest_pb2.TestAllTypes.REPEATED_INT32_FIELD_NUMBER, 31)
  2340. self.assertEqual(unittest_pb2.TestAllTypes.REPEATEDGROUP_FIELD_NUMBER, 46)
  2341. self.assertEqual(
  2342. unittest_pb2.TestAllTypes.REPEATED_NESTED_MESSAGE_FIELD_NUMBER, 48)
  2343. self.assertEqual(
  2344. unittest_pb2.TestAllTypes.REPEATED_NESTED_ENUM_FIELD_NUMBER, 51)
  2345. def testExtensionFieldNumbers(self):
  2346. self.assertEqual(unittest_pb2.TestRequired.single.number, 1000)
  2347. self.assertEqual(unittest_pb2.TestRequired.SINGLE_FIELD_NUMBER, 1000)
  2348. self.assertEqual(unittest_pb2.TestRequired.multi.number, 1001)
  2349. self.assertEqual(unittest_pb2.TestRequired.MULTI_FIELD_NUMBER, 1001)
  2350. self.assertEqual(unittest_pb2.optional_int32_extension.number, 1)
  2351. self.assertEqual(unittest_pb2.OPTIONAL_INT32_EXTENSION_FIELD_NUMBER, 1)
  2352. self.assertEqual(unittest_pb2.optionalgroup_extension.number, 16)
  2353. self.assertEqual(unittest_pb2.OPTIONALGROUP_EXTENSION_FIELD_NUMBER, 16)
  2354. self.assertEqual(unittest_pb2.optional_nested_message_extension.number, 18)
  2355. self.assertEqual(
  2356. unittest_pb2.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18)
  2357. self.assertEqual(unittest_pb2.optional_nested_enum_extension.number, 21)
  2358. self.assertEqual(unittest_pb2.OPTIONAL_NESTED_ENUM_EXTENSION_FIELD_NUMBER,
  2359. 21)
  2360. self.assertEqual(unittest_pb2.repeated_int32_extension.number, 31)
  2361. self.assertEqual(unittest_pb2.REPEATED_INT32_EXTENSION_FIELD_NUMBER, 31)
  2362. self.assertEqual(unittest_pb2.repeatedgroup_extension.number, 46)
  2363. self.assertEqual(unittest_pb2.REPEATEDGROUP_EXTENSION_FIELD_NUMBER, 46)
  2364. self.assertEqual(unittest_pb2.repeated_nested_message_extension.number, 48)
  2365. self.assertEqual(
  2366. unittest_pb2.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48)
  2367. self.assertEqual(unittest_pb2.repeated_nested_enum_extension.number, 51)
  2368. self.assertEqual(unittest_pb2.REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER,
  2369. 51)
  2370. def testInitKwargs(self):
  2371. proto = unittest_pb2.TestAllTypes(
  2372. optional_int32=1,
  2373. optional_string='foo',
  2374. optional_bool=True,
  2375. optional_bytes=b'bar',
  2376. optional_nested_message=unittest_pb2.TestAllTypes.NestedMessage(bb=1),
  2377. optional_foreign_message=unittest_pb2.ForeignMessage(c=1),
  2378. optional_nested_enum=unittest_pb2.TestAllTypes.FOO,
  2379. optional_foreign_enum=unittest_pb2.FOREIGN_FOO,
  2380. repeated_int32=[1, 2, 3])
  2381. self.assertTrue(proto.IsInitialized())
  2382. self.assertTrue(proto.HasField('optional_int32'))
  2383. self.assertTrue(proto.HasField('optional_string'))
  2384. self.assertTrue(proto.HasField('optional_bool'))
  2385. self.assertTrue(proto.HasField('optional_bytes'))
  2386. self.assertTrue(proto.HasField('optional_nested_message'))
  2387. self.assertTrue(proto.HasField('optional_foreign_message'))
  2388. self.assertTrue(proto.HasField('optional_nested_enum'))
  2389. self.assertTrue(proto.HasField('optional_foreign_enum'))
  2390. self.assertEqual(1, proto.optional_int32)
  2391. self.assertEqual('foo', proto.optional_string)
  2392. self.assertEqual(True, proto.optional_bool)
  2393. self.assertEqual(b'bar', proto.optional_bytes)
  2394. self.assertEqual(1, proto.optional_nested_message.bb)
  2395. self.assertEqual(1, proto.optional_foreign_message.c)
  2396. self.assertEqual(unittest_pb2.TestAllTypes.FOO,
  2397. proto.optional_nested_enum)
  2398. self.assertEqual(unittest_pb2.FOREIGN_FOO, proto.optional_foreign_enum)
  2399. self.assertEqual([1, 2, 3], proto.repeated_int32)
  2400. def testInitArgsUnknownFieldName(self):
  2401. def InitalizeEmptyMessageWithExtraKeywordArg():
  2402. unused_proto = unittest_pb2.TestEmptyMessage(unknown='unknown')
  2403. self._CheckRaises(
  2404. ValueError,
  2405. InitalizeEmptyMessageWithExtraKeywordArg,
  2406. 'Protocol message TestEmptyMessage has no "unknown" field.')
  2407. def testInitRequiredKwargs(self):
  2408. proto = unittest_pb2.TestRequired(a=1, b=1, c=1)
  2409. self.assertTrue(proto.IsInitialized())
  2410. self.assertTrue(proto.HasField('a'))
  2411. self.assertTrue(proto.HasField('b'))
  2412. self.assertTrue(proto.HasField('c'))
  2413. self.assertTrue(not proto.HasField('dummy2'))
  2414. self.assertEqual(1, proto.a)
  2415. self.assertEqual(1, proto.b)
  2416. self.assertEqual(1, proto.c)
  2417. def testInitRequiredForeignKwargs(self):
  2418. proto = unittest_pb2.TestRequiredForeign(
  2419. optional_message=unittest_pb2.TestRequired(a=1, b=1, c=1))
  2420. self.assertTrue(proto.IsInitialized())
  2421. self.assertTrue(proto.HasField('optional_message'))
  2422. self.assertTrue(proto.optional_message.IsInitialized())
  2423. self.assertTrue(proto.optional_message.HasField('a'))
  2424. self.assertTrue(proto.optional_message.HasField('b'))
  2425. self.assertTrue(proto.optional_message.HasField('c'))
  2426. self.assertTrue(not proto.optional_message.HasField('dummy2'))
  2427. self.assertEqual(unittest_pb2.TestRequired(a=1, b=1, c=1),
  2428. proto.optional_message)
  2429. self.assertEqual(1, proto.optional_message.a)
  2430. self.assertEqual(1, proto.optional_message.b)
  2431. self.assertEqual(1, proto.optional_message.c)
  2432. def testInitRepeatedKwargs(self):
  2433. proto = unittest_pb2.TestAllTypes(repeated_int32=[1, 2, 3])
  2434. self.assertTrue(proto.IsInitialized())
  2435. self.assertEqual(1, proto.repeated_int32[0])
  2436. self.assertEqual(2, proto.repeated_int32[1])
  2437. self.assertEqual(3, proto.repeated_int32[2])
  2438. class OptionsTest(unittest.TestCase):
  2439. def testMessageOptions(self):
  2440. proto = message_set_extensions_pb2.TestMessageSet()
  2441. self.assertEqual(True,
  2442. proto.DESCRIPTOR.GetOptions().message_set_wire_format)
  2443. proto = unittest_pb2.TestAllTypes()
  2444. self.assertEqual(False,
  2445. proto.DESCRIPTOR.GetOptions().message_set_wire_format)
  2446. def testPackedOptions(self):
  2447. proto = unittest_pb2.TestAllTypes()
  2448. proto.optional_int32 = 1
  2449. proto.optional_double = 3.0
  2450. for field_descriptor, _ in proto.ListFields():
  2451. self.assertEqual(False, field_descriptor.GetOptions().packed)
  2452. proto = unittest_pb2.TestPackedTypes()
  2453. proto.packed_int32.append(1)
  2454. proto.packed_double.append(3.0)
  2455. for field_descriptor, _ in proto.ListFields():
  2456. self.assertEqual(True, field_descriptor.GetOptions().packed)
  2457. self.assertEqual(descriptor.FieldDescriptor.LABEL_REPEATED,
  2458. field_descriptor.label)
  2459. class ClassAPITest(unittest.TestCase):
  2460. @unittest.skipIf(
  2461. api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
  2462. 'C++ implementation requires a call to MakeDescriptor()')
  2463. def testMakeClassWithNestedDescriptor(self):
  2464. leaf_desc = descriptor.Descriptor('leaf', 'package.parent.child.leaf', '',
  2465. containing_type=None, fields=[],
  2466. nested_types=[], enum_types=[],
  2467. extensions=[])
  2468. child_desc = descriptor.Descriptor('child', 'package.parent.child', '',
  2469. containing_type=None, fields=[],
  2470. nested_types=[leaf_desc], enum_types=[],
  2471. extensions=[])
  2472. sibling_desc = descriptor.Descriptor('sibling', 'package.parent.sibling',
  2473. '', containing_type=None, fields=[],
  2474. nested_types=[], enum_types=[],
  2475. extensions=[])
  2476. parent_desc = descriptor.Descriptor('parent', 'package.parent', '',
  2477. containing_type=None, fields=[],
  2478. nested_types=[child_desc, sibling_desc],
  2479. enum_types=[], extensions=[])
  2480. message_class = reflection.MakeClass(parent_desc)
  2481. self.assertIn('child', message_class.__dict__)
  2482. self.assertIn('sibling', message_class.__dict__)
  2483. self.assertIn('leaf', message_class.child.__dict__)
  2484. def _GetSerializedFileDescriptor(self, name):
  2485. """Get a serialized representation of a test FileDescriptorProto.
  2486. Args:
  2487. name: All calls to this must use a unique message name, to avoid
  2488. collisions in the cpp descriptor pool.
  2489. Returns:
  2490. A string containing the serialized form of a test FileDescriptorProto.
  2491. """
  2492. file_descriptor_str = (
  2493. 'message_type {'
  2494. ' name: "' + name + '"'
  2495. ' field {'
  2496. ' name: "flat"'
  2497. ' number: 1'
  2498. ' label: LABEL_REPEATED'
  2499. ' type: TYPE_UINT32'
  2500. ' }'
  2501. ' field {'
  2502. ' name: "bar"'
  2503. ' number: 2'
  2504. ' label: LABEL_OPTIONAL'
  2505. ' type: TYPE_MESSAGE'
  2506. ' type_name: "Bar"'
  2507. ' }'
  2508. ' nested_type {'
  2509. ' name: "Bar"'
  2510. ' field {'
  2511. ' name: "baz"'
  2512. ' number: 3'
  2513. ' label: LABEL_OPTIONAL'
  2514. ' type: TYPE_MESSAGE'
  2515. ' type_name: "Baz"'
  2516. ' }'
  2517. ' nested_type {'
  2518. ' name: "Baz"'
  2519. ' enum_type {'
  2520. ' name: "deep_enum"'
  2521. ' value {'
  2522. ' name: "VALUE_A"'
  2523. ' number: 0'
  2524. ' }'
  2525. ' }'
  2526. ' field {'
  2527. ' name: "deep"'
  2528. ' number: 4'
  2529. ' label: LABEL_OPTIONAL'
  2530. ' type: TYPE_UINT32'
  2531. ' }'
  2532. ' }'
  2533. ' }'
  2534. '}')
  2535. file_descriptor = descriptor_pb2.FileDescriptorProto()
  2536. text_format.Merge(file_descriptor_str, file_descriptor)
  2537. return file_descriptor.SerializeToString()
  2538. def testParsingFlatClassWithExplicitClassDeclaration(self):
  2539. """Test that the generated class can parse a flat message."""
  2540. # TODO(xiaofeng): This test fails with cpp implemetnation in the call
  2541. # of six.with_metaclass(). The other two callsites of with_metaclass
  2542. # in this file are both excluded from cpp test, so it might be expected
  2543. # to fail. Need someone more familiar with the python code to take a
  2544. # look at this.
  2545. if api_implementation.Type() != 'python':
  2546. return
  2547. file_descriptor = descriptor_pb2.FileDescriptorProto()
  2548. file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
  2549. msg_descriptor = descriptor.MakeDescriptor(
  2550. file_descriptor.message_type[0])
  2551. class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
  2552. DESCRIPTOR = msg_descriptor
  2553. msg = MessageClass()
  2554. msg_str = (
  2555. 'flat: 0 '
  2556. 'flat: 1 '
  2557. 'flat: 2 ')
  2558. text_format.Merge(msg_str, msg)
  2559. self.assertEqual(msg.flat, [0, 1, 2])
  2560. def testParsingFlatClass(self):
  2561. """Test that the generated class can parse a flat message."""
  2562. file_descriptor = descriptor_pb2.FileDescriptorProto()
  2563. file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('B'))
  2564. msg_descriptor = descriptor.MakeDescriptor(
  2565. file_descriptor.message_type[0])
  2566. msg_class = reflection.MakeClass(msg_descriptor)
  2567. msg = msg_class()
  2568. msg_str = (
  2569. 'flat: 0 '
  2570. 'flat: 1 '
  2571. 'flat: 2 ')
  2572. text_format.Merge(msg_str, msg)
  2573. self.assertEqual(msg.flat, [0, 1, 2])
  2574. def testParsingNestedClass(self):
  2575. """Test that the generated class can parse a nested message."""
  2576. file_descriptor = descriptor_pb2.FileDescriptorProto()
  2577. file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('C'))
  2578. msg_descriptor = descriptor.MakeDescriptor(
  2579. file_descriptor.message_type[0])
  2580. msg_class = reflection.MakeClass(msg_descriptor)
  2581. msg = msg_class()
  2582. msg_str = (
  2583. 'bar {'
  2584. ' baz {'
  2585. ' deep: 4'
  2586. ' }'
  2587. '}')
  2588. text_format.Merge(msg_str, msg)
  2589. self.assertEqual(msg.bar.baz.deep, 4)
  2590. if __name__ == '__main__':
  2591. unittest.main()