reflection_test.py 119 KB

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