店播爬取Python脚本

reflection_test.py 136KB

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