reflection_test.py 119 KB

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