店播爬取Python脚本

descriptor_test.py 43KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. #! /usr/bin/env python
  2. #
  3. # Protocol Buffers - Google's data interchange format
  4. # Copyright 2008 Google Inc. All rights reserved.
  5. # https://developers.google.com/protocol-buffers/
  6. #
  7. # Redistribution and use in source and binary forms, with or without
  8. # modification, are permitted provided that the following conditions are
  9. # met:
  10. #
  11. # * Redistributions of source code must retain the above copyright
  12. # notice, this list of conditions and the following disclaimer.
  13. # * Redistributions in binary form must reproduce the above
  14. # copyright notice, this list of conditions and the following disclaimer
  15. # in the documentation and/or other materials provided with the
  16. # distribution.
  17. # * Neither the name of Google Inc. nor the names of its
  18. # contributors may be used to endorse or promote products derived from
  19. # this software without specific prior written permission.
  20. #
  21. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. """Unittest for google.protobuf.internal.descriptor."""
  33. __author__ = 'robinson@google.com (Will Robinson)'
  34. import sys
  35. import warnings
  36. try:
  37. import unittest2 as unittest #PY26
  38. except ImportError:
  39. import unittest
  40. from google.protobuf import unittest_custom_options_pb2
  41. from google.protobuf import unittest_import_pb2
  42. from google.protobuf import unittest_pb2
  43. from google.protobuf import descriptor_pb2
  44. from google.protobuf.internal import api_implementation
  45. from google.protobuf.internal import test_util
  46. from google.protobuf import descriptor
  47. from google.protobuf import descriptor_pool
  48. from google.protobuf import symbol_database
  49. from google.protobuf import text_format
  50. TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII = """
  51. name: 'TestEmptyMessage'
  52. """
  53. warnings.simplefilter('error', DeprecationWarning)
  54. class DescriptorTest(unittest.TestCase):
  55. def setUp(self):
  56. file_proto = descriptor_pb2.FileDescriptorProto(
  57. name='some/filename/some.proto',
  58. package='protobuf_unittest')
  59. message_proto = file_proto.message_type.add(
  60. name='NestedMessage')
  61. message_proto.field.add(
  62. name='bb',
  63. number=1,
  64. type=descriptor_pb2.FieldDescriptorProto.TYPE_INT32,
  65. label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL)
  66. enum_proto = message_proto.enum_type.add(
  67. name='ForeignEnum')
  68. enum_proto.value.add(name='FOREIGN_FOO', number=4)
  69. enum_proto.value.add(name='FOREIGN_BAR', number=5)
  70. enum_proto.value.add(name='FOREIGN_BAZ', number=6)
  71. file_proto.message_type.add(name='ResponseMessage')
  72. service_proto = file_proto.service.add(
  73. name='Service')
  74. method_proto = service_proto.method.add(
  75. name='CallMethod',
  76. input_type='.protobuf_unittest.NestedMessage',
  77. output_type='.protobuf_unittest.ResponseMessage')
  78. # Note: Calling DescriptorPool.Add() multiple times with the same file only
  79. # works if the input is canonical; in particular, all type names must be
  80. # fully qualified.
  81. self.pool = self.GetDescriptorPool()
  82. self.pool.Add(file_proto)
  83. self.my_file = self.pool.FindFileByName(file_proto.name)
  84. self.my_message = self.my_file.message_types_by_name[message_proto.name]
  85. self.my_enum = self.my_message.enum_types_by_name[enum_proto.name]
  86. self.my_service = self.my_file.services_by_name[service_proto.name]
  87. self.my_method = self.my_service.methods_by_name[method_proto.name]
  88. def GetDescriptorPool(self):
  89. return symbol_database.Default().pool
  90. def testEnumValueName(self):
  91. self.assertEqual(self.my_message.EnumValueName('ForeignEnum', 4),
  92. 'FOREIGN_FOO')
  93. self.assertEqual(
  94. self.my_message.enum_types_by_name[
  95. 'ForeignEnum'].values_by_number[4].name,
  96. self.my_message.EnumValueName('ForeignEnum', 4))
  97. with self.assertRaises(KeyError):
  98. self.my_message.EnumValueName('ForeignEnum', 999)
  99. with self.assertRaises(KeyError):
  100. self.my_message.EnumValueName('NoneEnum', 999)
  101. with self.assertRaises(TypeError):
  102. self.my_message.EnumValueName()
  103. def testEnumFixups(self):
  104. self.assertEqual(self.my_enum, self.my_enum.values[0].type)
  105. def testContainingTypeFixups(self):
  106. self.assertEqual(self.my_message, self.my_message.fields[0].containing_type)
  107. self.assertEqual(self.my_message, self.my_enum.containing_type)
  108. def testContainingServiceFixups(self):
  109. self.assertEqual(self.my_service, self.my_method.containing_service)
  110. def testGetOptions(self):
  111. self.assertEqual(self.my_enum.GetOptions(),
  112. descriptor_pb2.EnumOptions())
  113. self.assertEqual(self.my_enum.values[0].GetOptions(),
  114. descriptor_pb2.EnumValueOptions())
  115. self.assertEqual(self.my_message.GetOptions(),
  116. descriptor_pb2.MessageOptions())
  117. self.assertEqual(self.my_message.fields[0].GetOptions(),
  118. descriptor_pb2.FieldOptions())
  119. self.assertEqual(self.my_method.GetOptions(),
  120. descriptor_pb2.MethodOptions())
  121. self.assertEqual(self.my_service.GetOptions(),
  122. descriptor_pb2.ServiceOptions())
  123. def testSimpleCustomOptions(self):
  124. file_descriptor = unittest_custom_options_pb2.DESCRIPTOR
  125. message_descriptor = (unittest_custom_options_pb2.
  126. TestMessageWithCustomOptions.DESCRIPTOR)
  127. field_descriptor = message_descriptor.fields_by_name['field1']
  128. oneof_descriptor = message_descriptor.oneofs_by_name['AnOneof']
  129. enum_descriptor = message_descriptor.enum_types_by_name['AnEnum']
  130. enum_value_descriptor = (message_descriptor.
  131. enum_values_by_name['ANENUM_VAL2'])
  132. other_enum_value_descriptor = (message_descriptor.
  133. enum_values_by_name['ANENUM_VAL1'])
  134. service_descriptor = (unittest_custom_options_pb2.
  135. TestServiceWithCustomOptions.DESCRIPTOR)
  136. method_descriptor = service_descriptor.FindMethodByName('Foo')
  137. file_options = file_descriptor.GetOptions()
  138. file_opt1 = unittest_custom_options_pb2.file_opt1
  139. self.assertEqual(9876543210, file_options.Extensions[file_opt1])
  140. message_options = message_descriptor.GetOptions()
  141. message_opt1 = unittest_custom_options_pb2.message_opt1
  142. self.assertEqual(-56, message_options.Extensions[message_opt1])
  143. field_options = field_descriptor.GetOptions()
  144. field_opt1 = unittest_custom_options_pb2.field_opt1
  145. self.assertEqual(8765432109, field_options.Extensions[field_opt1])
  146. field_opt2 = unittest_custom_options_pb2.field_opt2
  147. self.assertEqual(42, field_options.Extensions[field_opt2])
  148. oneof_options = oneof_descriptor.GetOptions()
  149. oneof_opt1 = unittest_custom_options_pb2.oneof_opt1
  150. self.assertEqual(-99, oneof_options.Extensions[oneof_opt1])
  151. enum_options = enum_descriptor.GetOptions()
  152. enum_opt1 = unittest_custom_options_pb2.enum_opt1
  153. self.assertEqual(-789, enum_options.Extensions[enum_opt1])
  154. enum_value_options = enum_value_descriptor.GetOptions()
  155. enum_value_opt1 = unittest_custom_options_pb2.enum_value_opt1
  156. self.assertEqual(123, enum_value_options.Extensions[enum_value_opt1])
  157. service_options = service_descriptor.GetOptions()
  158. service_opt1 = unittest_custom_options_pb2.service_opt1
  159. self.assertEqual(-9876543210, service_options.Extensions[service_opt1])
  160. method_options = method_descriptor.GetOptions()
  161. method_opt1 = unittest_custom_options_pb2.method_opt1
  162. self.assertEqual(unittest_custom_options_pb2.METHODOPT1_VAL2,
  163. method_options.Extensions[method_opt1])
  164. message_descriptor = (
  165. unittest_custom_options_pb2.DummyMessageContainingEnum.DESCRIPTOR)
  166. self.assertTrue(file_descriptor.has_options)
  167. self.assertFalse(message_descriptor.has_options)
  168. self.assertTrue(field_descriptor.has_options)
  169. self.assertTrue(oneof_descriptor.has_options)
  170. self.assertTrue(enum_descriptor.has_options)
  171. self.assertTrue(enum_value_descriptor.has_options)
  172. self.assertFalse(other_enum_value_descriptor.has_options)
  173. def testCustomOptionsCopyTo(self):
  174. message_descriptor = (unittest_custom_options_pb2.
  175. TestMessageWithCustomOptions.DESCRIPTOR)
  176. message_proto = descriptor_pb2.DescriptorProto()
  177. message_descriptor.CopyToProto(message_proto)
  178. self.assertEqual(len(message_proto.options.ListFields()),
  179. 2)
  180. def testDifferentCustomOptionTypes(self):
  181. kint32min = -2**31
  182. kint64min = -2**63
  183. kint32max = 2**31 - 1
  184. kint64max = 2**63 - 1
  185. kuint32max = 2**32 - 1
  186. kuint64max = 2**64 - 1
  187. message_descriptor =\
  188. unittest_custom_options_pb2.CustomOptionMinIntegerValues.DESCRIPTOR
  189. message_options = message_descriptor.GetOptions()
  190. self.assertEqual(False, message_options.Extensions[
  191. unittest_custom_options_pb2.bool_opt])
  192. self.assertEqual(kint32min, message_options.Extensions[
  193. unittest_custom_options_pb2.int32_opt])
  194. self.assertEqual(kint64min, message_options.Extensions[
  195. unittest_custom_options_pb2.int64_opt])
  196. self.assertEqual(0, message_options.Extensions[
  197. unittest_custom_options_pb2.uint32_opt])
  198. self.assertEqual(0, message_options.Extensions[
  199. unittest_custom_options_pb2.uint64_opt])
  200. self.assertEqual(kint32min, message_options.Extensions[
  201. unittest_custom_options_pb2.sint32_opt])
  202. self.assertEqual(kint64min, message_options.Extensions[
  203. unittest_custom_options_pb2.sint64_opt])
  204. self.assertEqual(0, message_options.Extensions[
  205. unittest_custom_options_pb2.fixed32_opt])
  206. self.assertEqual(0, message_options.Extensions[
  207. unittest_custom_options_pb2.fixed64_opt])
  208. self.assertEqual(kint32min, message_options.Extensions[
  209. unittest_custom_options_pb2.sfixed32_opt])
  210. self.assertEqual(kint64min, message_options.Extensions[
  211. unittest_custom_options_pb2.sfixed64_opt])
  212. message_descriptor =\
  213. unittest_custom_options_pb2.CustomOptionMaxIntegerValues.DESCRIPTOR
  214. message_options = message_descriptor.GetOptions()
  215. self.assertEqual(True, message_options.Extensions[
  216. unittest_custom_options_pb2.bool_opt])
  217. self.assertEqual(kint32max, message_options.Extensions[
  218. unittest_custom_options_pb2.int32_opt])
  219. self.assertEqual(kint64max, message_options.Extensions[
  220. unittest_custom_options_pb2.int64_opt])
  221. self.assertEqual(kuint32max, message_options.Extensions[
  222. unittest_custom_options_pb2.uint32_opt])
  223. self.assertEqual(kuint64max, message_options.Extensions[
  224. unittest_custom_options_pb2.uint64_opt])
  225. self.assertEqual(kint32max, message_options.Extensions[
  226. unittest_custom_options_pb2.sint32_opt])
  227. self.assertEqual(kint64max, message_options.Extensions[
  228. unittest_custom_options_pb2.sint64_opt])
  229. self.assertEqual(kuint32max, message_options.Extensions[
  230. unittest_custom_options_pb2.fixed32_opt])
  231. self.assertEqual(kuint64max, message_options.Extensions[
  232. unittest_custom_options_pb2.fixed64_opt])
  233. self.assertEqual(kint32max, message_options.Extensions[
  234. unittest_custom_options_pb2.sfixed32_opt])
  235. self.assertEqual(kint64max, message_options.Extensions[
  236. unittest_custom_options_pb2.sfixed64_opt])
  237. message_descriptor =\
  238. unittest_custom_options_pb2.CustomOptionOtherValues.DESCRIPTOR
  239. message_options = message_descriptor.GetOptions()
  240. self.assertEqual(-100, message_options.Extensions[
  241. unittest_custom_options_pb2.int32_opt])
  242. self.assertAlmostEqual(12.3456789, message_options.Extensions[
  243. unittest_custom_options_pb2.float_opt], 6)
  244. self.assertAlmostEqual(1.234567890123456789, message_options.Extensions[
  245. unittest_custom_options_pb2.double_opt])
  246. self.assertEqual("Hello, \"World\"", message_options.Extensions[
  247. unittest_custom_options_pb2.string_opt])
  248. self.assertEqual(b"Hello\0World", message_options.Extensions[
  249. unittest_custom_options_pb2.bytes_opt])
  250. dummy_enum = unittest_custom_options_pb2.DummyMessageContainingEnum
  251. self.assertEqual(
  252. dummy_enum.TEST_OPTION_ENUM_TYPE2,
  253. message_options.Extensions[unittest_custom_options_pb2.enum_opt])
  254. message_descriptor =\
  255. unittest_custom_options_pb2.SettingRealsFromPositiveInts.DESCRIPTOR
  256. message_options = message_descriptor.GetOptions()
  257. self.assertAlmostEqual(12, message_options.Extensions[
  258. unittest_custom_options_pb2.float_opt], 6)
  259. self.assertAlmostEqual(154, message_options.Extensions[
  260. unittest_custom_options_pb2.double_opt])
  261. message_descriptor =\
  262. unittest_custom_options_pb2.SettingRealsFromNegativeInts.DESCRIPTOR
  263. message_options = message_descriptor.GetOptions()
  264. self.assertAlmostEqual(-12, message_options.Extensions[
  265. unittest_custom_options_pb2.float_opt], 6)
  266. self.assertAlmostEqual(-154, message_options.Extensions[
  267. unittest_custom_options_pb2.double_opt])
  268. def testComplexExtensionOptions(self):
  269. descriptor =\
  270. unittest_custom_options_pb2.VariousComplexOptions.DESCRIPTOR
  271. options = descriptor.GetOptions()
  272. self.assertEqual(42, options.Extensions[
  273. unittest_custom_options_pb2.complex_opt1].foo)
  274. self.assertEqual(324, options.Extensions[
  275. unittest_custom_options_pb2.complex_opt1].Extensions[
  276. unittest_custom_options_pb2.quux])
  277. self.assertEqual(876, options.Extensions[
  278. unittest_custom_options_pb2.complex_opt1].Extensions[
  279. unittest_custom_options_pb2.corge].qux)
  280. self.assertEqual(987, options.Extensions[
  281. unittest_custom_options_pb2.complex_opt2].baz)
  282. self.assertEqual(654, options.Extensions[
  283. unittest_custom_options_pb2.complex_opt2].Extensions[
  284. unittest_custom_options_pb2.grault])
  285. self.assertEqual(743, options.Extensions[
  286. unittest_custom_options_pb2.complex_opt2].bar.foo)
  287. self.assertEqual(1999, options.Extensions[
  288. unittest_custom_options_pb2.complex_opt2].bar.Extensions[
  289. unittest_custom_options_pb2.quux])
  290. self.assertEqual(2008, options.Extensions[
  291. unittest_custom_options_pb2.complex_opt2].bar.Extensions[
  292. unittest_custom_options_pb2.corge].qux)
  293. self.assertEqual(741, options.Extensions[
  294. unittest_custom_options_pb2.complex_opt2].Extensions[
  295. unittest_custom_options_pb2.garply].foo)
  296. self.assertEqual(1998, options.Extensions[
  297. unittest_custom_options_pb2.complex_opt2].Extensions[
  298. unittest_custom_options_pb2.garply].Extensions[
  299. unittest_custom_options_pb2.quux])
  300. self.assertEqual(2121, options.Extensions[
  301. unittest_custom_options_pb2.complex_opt2].Extensions[
  302. unittest_custom_options_pb2.garply].Extensions[
  303. unittest_custom_options_pb2.corge].qux)
  304. self.assertEqual(1971, options.Extensions[
  305. unittest_custom_options_pb2.ComplexOptionType2
  306. .ComplexOptionType4.complex_opt4].waldo)
  307. self.assertEqual(321, options.Extensions[
  308. unittest_custom_options_pb2.complex_opt2].fred.waldo)
  309. self.assertEqual(9, options.Extensions[
  310. unittest_custom_options_pb2.complex_opt3].qux)
  311. self.assertEqual(22, options.Extensions[
  312. unittest_custom_options_pb2.complex_opt3].complexoptiontype5.plugh)
  313. self.assertEqual(24, options.Extensions[
  314. unittest_custom_options_pb2.complexopt6].xyzzy)
  315. # Check that aggregate options were parsed and saved correctly in
  316. # the appropriate descriptors.
  317. def testAggregateOptions(self):
  318. file_descriptor = unittest_custom_options_pb2.DESCRIPTOR
  319. message_descriptor =\
  320. unittest_custom_options_pb2.AggregateMessage.DESCRIPTOR
  321. field_descriptor = message_descriptor.fields_by_name["fieldname"]
  322. enum_descriptor = unittest_custom_options_pb2.AggregateEnum.DESCRIPTOR
  323. enum_value_descriptor = enum_descriptor.values_by_name["VALUE"]
  324. service_descriptor =\
  325. unittest_custom_options_pb2.AggregateService.DESCRIPTOR
  326. method_descriptor = service_descriptor.FindMethodByName("Method")
  327. # Tests for the different types of data embedded in fileopt
  328. file_options = file_descriptor.GetOptions().Extensions[
  329. unittest_custom_options_pb2.fileopt]
  330. self.assertEqual(100, file_options.i)
  331. self.assertEqual("FileAnnotation", file_options.s)
  332. self.assertEqual("NestedFileAnnotation", file_options.sub.s)
  333. self.assertEqual("FileExtensionAnnotation", file_options.file.Extensions[
  334. unittest_custom_options_pb2.fileopt].s)
  335. self.assertEqual("EmbeddedMessageSetElement", file_options.mset.Extensions[
  336. unittest_custom_options_pb2.AggregateMessageSetElement
  337. .message_set_extension].s)
  338. # Simple tests for all the other types of annotations
  339. self.assertEqual(
  340. "MessageAnnotation",
  341. message_descriptor.GetOptions().Extensions[
  342. unittest_custom_options_pb2.msgopt].s)
  343. self.assertEqual(
  344. "FieldAnnotation",
  345. field_descriptor.GetOptions().Extensions[
  346. unittest_custom_options_pb2.fieldopt].s)
  347. self.assertEqual(
  348. "EnumAnnotation",
  349. enum_descriptor.GetOptions().Extensions[
  350. unittest_custom_options_pb2.enumopt].s)
  351. self.assertEqual(
  352. "EnumValueAnnotation",
  353. enum_value_descriptor.GetOptions().Extensions[
  354. unittest_custom_options_pb2.enumvalopt].s)
  355. self.assertEqual(
  356. "ServiceAnnotation",
  357. service_descriptor.GetOptions().Extensions[
  358. unittest_custom_options_pb2.serviceopt].s)
  359. self.assertEqual(
  360. "MethodAnnotation",
  361. method_descriptor.GetOptions().Extensions[
  362. unittest_custom_options_pb2.methodopt].s)
  363. def testNestedOptions(self):
  364. nested_message =\
  365. unittest_custom_options_pb2.NestedOptionType.NestedMessage.DESCRIPTOR
  366. self.assertEqual(1001, nested_message.GetOptions().Extensions[
  367. unittest_custom_options_pb2.message_opt1])
  368. nested_field = nested_message.fields_by_name["nested_field"]
  369. self.assertEqual(1002, nested_field.GetOptions().Extensions[
  370. unittest_custom_options_pb2.field_opt1])
  371. outer_message =\
  372. unittest_custom_options_pb2.NestedOptionType.DESCRIPTOR
  373. nested_enum = outer_message.enum_types_by_name["NestedEnum"]
  374. self.assertEqual(1003, nested_enum.GetOptions().Extensions[
  375. unittest_custom_options_pb2.enum_opt1])
  376. nested_enum_value = outer_message.enum_values_by_name["NESTED_ENUM_VALUE"]
  377. self.assertEqual(1004, nested_enum_value.GetOptions().Extensions[
  378. unittest_custom_options_pb2.enum_value_opt1])
  379. nested_extension = outer_message.extensions_by_name["nested_extension"]
  380. self.assertEqual(1005, nested_extension.GetOptions().Extensions[
  381. unittest_custom_options_pb2.field_opt2])
  382. def testFileDescriptorReferences(self):
  383. self.assertEqual(self.my_enum.file, self.my_file)
  384. self.assertEqual(self.my_message.file, self.my_file)
  385. def testFileDescriptor(self):
  386. self.assertEqual(self.my_file.name, 'some/filename/some.proto')
  387. self.assertEqual(self.my_file.package, 'protobuf_unittest')
  388. self.assertEqual(self.my_file.pool, self.pool)
  389. self.assertFalse(self.my_file.has_options)
  390. self.assertEqual('proto2', self.my_file.syntax)
  391. file_proto = descriptor_pb2.FileDescriptorProto()
  392. self.my_file.CopyToProto(file_proto)
  393. self.assertEqual(self.my_file.serialized_pb,
  394. file_proto.SerializeToString())
  395. # Generated modules also belong to the default pool.
  396. self.assertEqual(unittest_pb2.DESCRIPTOR.pool, descriptor_pool.Default())
  397. @unittest.skipIf(
  398. api_implementation.Type() != 'cpp' or api_implementation.Version() != 2,
  399. 'Immutability of descriptors is only enforced in v2 implementation')
  400. def testImmutableCppDescriptor(self):
  401. file_descriptor = unittest_pb2.DESCRIPTOR
  402. message_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
  403. field_descriptor = message_descriptor.fields_by_name['optional_int32']
  404. enum_descriptor = message_descriptor.enum_types_by_name['NestedEnum']
  405. oneof_descriptor = message_descriptor.oneofs_by_name['oneof_field']
  406. with self.assertRaises(AttributeError):
  407. message_descriptor.fields_by_name = None
  408. with self.assertRaises(TypeError):
  409. message_descriptor.fields_by_name['Another'] = None
  410. with self.assertRaises(TypeError):
  411. message_descriptor.fields.append(None)
  412. with self.assertRaises(AttributeError):
  413. field_descriptor.containing_type = message_descriptor
  414. with self.assertRaises(AttributeError):
  415. file_descriptor.has_options = False
  416. with self.assertRaises(AttributeError):
  417. field_descriptor.has_options = False
  418. with self.assertRaises(AttributeError):
  419. oneof_descriptor.has_options = False
  420. with self.assertRaises(AttributeError):
  421. enum_descriptor.has_options = False
  422. with self.assertRaises(AttributeError) as e:
  423. message_descriptor.has_options = True
  424. self.assertEqual('attribute is not writable: has_options',
  425. str(e.exception))
  426. def testDefault(self):
  427. message_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
  428. field = message_descriptor.fields_by_name['repeated_int32']
  429. self.assertEqual(field.default_value, [])
  430. field = message_descriptor.fields_by_name['repeated_nested_message']
  431. self.assertEqual(field.default_value, [])
  432. field = message_descriptor.fields_by_name['optionalgroup']
  433. self.assertEqual(field.default_value, None)
  434. field = message_descriptor.fields_by_name['optional_nested_message']
  435. self.assertEqual(field.default_value, None)
  436. class NewDescriptorTest(DescriptorTest):
  437. """Redo the same tests as above, but with a separate DescriptorPool."""
  438. def GetDescriptorPool(self):
  439. return descriptor_pool.DescriptorPool()
  440. class GeneratedDescriptorTest(unittest.TestCase):
  441. """Tests for the properties of descriptors in generated code."""
  442. def CheckMessageDescriptor(self, message_descriptor):
  443. # Basic properties
  444. self.assertEqual(message_descriptor.name, 'TestAllTypes')
  445. self.assertEqual(message_descriptor.full_name,
  446. 'protobuf_unittest.TestAllTypes')
  447. # Test equality and hashability
  448. self.assertEqual(message_descriptor, message_descriptor)
  449. self.assertEqual(message_descriptor.fields[0].containing_type,
  450. message_descriptor)
  451. self.assertIn(message_descriptor, [message_descriptor])
  452. self.assertIn(message_descriptor, {message_descriptor: None})
  453. # Test field containers
  454. self.CheckDescriptorSequence(message_descriptor.fields)
  455. self.CheckDescriptorMapping(message_descriptor.fields_by_name)
  456. self.CheckDescriptorMapping(message_descriptor.fields_by_number)
  457. self.CheckDescriptorMapping(message_descriptor.fields_by_camelcase_name)
  458. self.CheckDescriptorMapping(message_descriptor.enum_types_by_name)
  459. self.CheckDescriptorMapping(message_descriptor.enum_values_by_name)
  460. self.CheckDescriptorMapping(message_descriptor.oneofs_by_name)
  461. self.CheckDescriptorMapping(message_descriptor.enum_types[0].values_by_name)
  462. # Test extension range
  463. self.assertEqual(message_descriptor.extension_ranges, [])
  464. def CheckFieldDescriptor(self, field_descriptor):
  465. # Basic properties
  466. self.assertEqual(field_descriptor.name, 'optional_int32')
  467. self.assertEqual(field_descriptor.camelcase_name, 'optionalInt32')
  468. self.assertEqual(field_descriptor.full_name,
  469. 'protobuf_unittest.TestAllTypes.optional_int32')
  470. self.assertEqual(field_descriptor.containing_type.name, 'TestAllTypes')
  471. self.assertEqual(field_descriptor.file, unittest_pb2.DESCRIPTOR)
  472. # Test equality and hashability
  473. self.assertEqual(field_descriptor, field_descriptor)
  474. self.assertEqual(
  475. field_descriptor.containing_type.fields_by_name['optional_int32'],
  476. field_descriptor)
  477. self.assertEqual(
  478. field_descriptor.containing_type.fields_by_camelcase_name[
  479. 'optionalInt32'],
  480. field_descriptor)
  481. self.assertIn(field_descriptor, [field_descriptor])
  482. self.assertIn(field_descriptor, {field_descriptor: None})
  483. self.assertEqual(None, field_descriptor.extension_scope)
  484. self.assertEqual(None, field_descriptor.enum_type)
  485. if api_implementation.Type() == 'cpp':
  486. # For test coverage only
  487. self.assertEqual(field_descriptor.id, field_descriptor.id)
  488. def CheckDescriptorSequence(self, sequence):
  489. # Verifies that a property like 'messageDescriptor.fields' has all the
  490. # properties of an immutable abc.Sequence.
  491. self.assertNotEqual(sequence,
  492. unittest_pb2.TestAllExtensions.DESCRIPTOR.fields)
  493. self.assertNotEqual(sequence, [])
  494. self.assertNotEqual(sequence, 1)
  495. self.assertFalse(sequence == 1) # Only for cpp test coverage
  496. self.assertEqual(sequence, sequence)
  497. expected_list = list(sequence)
  498. self.assertEqual(expected_list, sequence)
  499. self.assertGreater(len(sequence), 0) # Sized
  500. self.assertEqual(len(sequence), len(expected_list)) # Iterable
  501. self.assertEqual(sequence[len(sequence) -1], sequence[-1])
  502. item = sequence[0]
  503. self.assertEqual(item, sequence[0])
  504. self.assertIn(item, sequence) # Container
  505. self.assertEqual(sequence.index(item), 0)
  506. self.assertEqual(sequence.count(item), 1)
  507. other_item = unittest_pb2.NestedTestAllTypes.DESCRIPTOR.fields[0]
  508. self.assertNotIn(other_item, sequence)
  509. self.assertEqual(sequence.count(other_item), 0)
  510. self.assertRaises(ValueError, sequence.index, other_item)
  511. self.assertRaises(ValueError, sequence.index, [])
  512. reversed_iterator = reversed(sequence)
  513. self.assertEqual(list(reversed_iterator), list(sequence)[::-1])
  514. self.assertRaises(StopIteration, next, reversed_iterator)
  515. expected_list[0] = 'change value'
  516. self.assertNotEqual(expected_list, sequence)
  517. # TODO(jieluo): Change __repr__ support for DescriptorSequence.
  518. if api_implementation.Type() == 'python':
  519. self.assertEqual(str(list(sequence)), str(sequence))
  520. else:
  521. self.assertEqual(str(sequence)[0], '<')
  522. def CheckDescriptorMapping(self, mapping):
  523. # Verifies that a property like 'messageDescriptor.fields' has all the
  524. # properties of an immutable abc.Mapping.
  525. self.assertNotEqual(
  526. mapping, unittest_pb2.TestAllExtensions.DESCRIPTOR.fields_by_name)
  527. self.assertNotEqual(mapping, {})
  528. self.assertNotEqual(mapping, 1)
  529. self.assertFalse(mapping == 1) # Only for cpp test coverage
  530. excepted_dict = dict(mapping.items())
  531. self.assertEqual(mapping, excepted_dict)
  532. self.assertEqual(mapping, mapping)
  533. self.assertGreater(len(mapping), 0) # Sized
  534. self.assertEqual(len(mapping), len(excepted_dict)) # Iterable
  535. if sys.version_info >= (3,):
  536. key, item = next(iter(mapping.items()))
  537. else:
  538. key, item = mapping.items()[0]
  539. self.assertIn(key, mapping) # Container
  540. self.assertEqual(mapping.get(key), item)
  541. with self.assertRaises(TypeError):
  542. mapping.get()
  543. # TODO(jieluo): Fix python and cpp extension diff.
  544. if api_implementation.Type() == 'python':
  545. self.assertRaises(TypeError, mapping.get, [])
  546. else:
  547. self.assertEqual(None, mapping.get([]))
  548. # keys(), iterkeys() &co
  549. item = (next(iter(mapping.keys())), next(iter(mapping.values())))
  550. self.assertEqual(item, next(iter(mapping.items())))
  551. if sys.version_info < (3,):
  552. def CheckItems(seq, iterator):
  553. self.assertEqual(next(iterator), seq[0])
  554. self.assertEqual(list(iterator), seq[1:])
  555. CheckItems(mapping.keys(), mapping.iterkeys())
  556. CheckItems(mapping.values(), mapping.itervalues())
  557. CheckItems(mapping.items(), mapping.iteritems())
  558. excepted_dict[key] = 'change value'
  559. self.assertNotEqual(mapping, excepted_dict)
  560. del excepted_dict[key]
  561. excepted_dict['new_key'] = 'new'
  562. self.assertNotEqual(mapping, excepted_dict)
  563. self.assertRaises(KeyError, mapping.__getitem__, 'key_error')
  564. self.assertRaises(KeyError, mapping.__getitem__, len(mapping) + 1)
  565. # TODO(jieluo): Add __repr__ support for DescriptorMapping.
  566. if api_implementation.Type() == 'python':
  567. self.assertEqual(len(str(dict(mapping.items()))), len(str(mapping)))
  568. else:
  569. self.assertEqual(str(mapping)[0], '<')
  570. def testDescriptor(self):
  571. message_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
  572. self.CheckMessageDescriptor(message_descriptor)
  573. field_descriptor = message_descriptor.fields_by_name['optional_int32']
  574. self.CheckFieldDescriptor(field_descriptor)
  575. field_descriptor = message_descriptor.fields_by_camelcase_name[
  576. 'optionalInt32']
  577. self.CheckFieldDescriptor(field_descriptor)
  578. enum_descriptor = unittest_pb2.DESCRIPTOR.enum_types_by_name[
  579. 'ForeignEnum']
  580. self.assertEqual(None, enum_descriptor.containing_type)
  581. # Test extension range
  582. self.assertEqual(
  583. unittest_pb2.TestAllExtensions.DESCRIPTOR.extension_ranges,
  584. [(1, 536870912)])
  585. self.assertEqual(
  586. unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR.extension_ranges,
  587. [(42, 43), (4143, 4244), (65536, 536870912)])
  588. def testCppDescriptorContainer(self):
  589. containing_file = unittest_pb2.DESCRIPTOR
  590. self.CheckDescriptorSequence(containing_file.dependencies)
  591. self.CheckDescriptorMapping(containing_file.message_types_by_name)
  592. self.CheckDescriptorMapping(containing_file.enum_types_by_name)
  593. self.CheckDescriptorMapping(containing_file.services_by_name)
  594. self.CheckDescriptorMapping(containing_file.extensions_by_name)
  595. self.CheckDescriptorMapping(
  596. unittest_pb2.TestNestedExtension.DESCRIPTOR.extensions_by_name)
  597. def testCppDescriptorContainer_Iterator(self):
  598. # Same test with the iterator
  599. enum = unittest_pb2.TestAllTypes.DESCRIPTOR.enum_types_by_name['NestedEnum']
  600. values_iter = iter(enum.values)
  601. del enum
  602. self.assertEqual('FOO', next(values_iter).name)
  603. def testDescriptorNestedTypesContainer(self):
  604. message_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
  605. nested_message_descriptor = unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR
  606. self.assertEqual(len(message_descriptor.nested_types), 3)
  607. self.assertFalse(None in message_descriptor.nested_types)
  608. self.assertTrue(
  609. nested_message_descriptor in message_descriptor.nested_types)
  610. def testServiceDescriptor(self):
  611. service_descriptor = unittest_pb2.DESCRIPTOR.services_by_name['TestService']
  612. self.assertEqual(service_descriptor.name, 'TestService')
  613. self.assertEqual(service_descriptor.methods[0].name, 'Foo')
  614. self.assertIs(service_descriptor.file, unittest_pb2.DESCRIPTOR)
  615. self.assertEqual(service_descriptor.index, 0)
  616. self.CheckDescriptorMapping(service_descriptor.methods_by_name)
  617. def testOneofDescriptor(self):
  618. message_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
  619. oneof_descriptor = message_descriptor.oneofs_by_name['oneof_field']
  620. self.assertFalse(oneof_descriptor.has_options)
  621. self.assertEqual(message_descriptor, oneof_descriptor.containing_type)
  622. self.assertEqual('oneof_field', oneof_descriptor.name)
  623. self.assertEqual('protobuf_unittest.TestAllTypes.oneof_field',
  624. oneof_descriptor.full_name)
  625. self.assertEqual(0, oneof_descriptor.index)
  626. class DescriptorCopyToProtoTest(unittest.TestCase):
  627. """Tests for CopyTo functions of Descriptor."""
  628. def _AssertProtoEqual(self, actual_proto, expected_class, expected_ascii):
  629. expected_proto = expected_class()
  630. text_format.Merge(expected_ascii, expected_proto)
  631. self.assertEqual(
  632. actual_proto, expected_proto,
  633. 'Not equal,\nActual:\n%s\nExpected:\n%s\n'
  634. % (str(actual_proto), str(expected_proto)))
  635. def _InternalTestCopyToProto(self, desc, expected_proto_class,
  636. expected_proto_ascii):
  637. actual = expected_proto_class()
  638. desc.CopyToProto(actual)
  639. self._AssertProtoEqual(
  640. actual, expected_proto_class, expected_proto_ascii)
  641. def testCopyToProto_EmptyMessage(self):
  642. self._InternalTestCopyToProto(
  643. unittest_pb2.TestEmptyMessage.DESCRIPTOR,
  644. descriptor_pb2.DescriptorProto,
  645. TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII)
  646. def testCopyToProto_NestedMessage(self):
  647. TEST_NESTED_MESSAGE_ASCII = """
  648. name: 'NestedMessage'
  649. field: <
  650. name: 'bb'
  651. number: 1
  652. label: 1 # Optional
  653. type: 5 # TYPE_INT32
  654. >
  655. """
  656. self._InternalTestCopyToProto(
  657. unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR,
  658. descriptor_pb2.DescriptorProto,
  659. TEST_NESTED_MESSAGE_ASCII)
  660. def testCopyToProto_ForeignNestedMessage(self):
  661. TEST_FOREIGN_NESTED_ASCII = """
  662. name: 'TestForeignNested'
  663. field: <
  664. name: 'foreign_nested'
  665. number: 1
  666. label: 1 # Optional
  667. type: 11 # TYPE_MESSAGE
  668. type_name: '.protobuf_unittest.TestAllTypes.NestedMessage'
  669. >
  670. """
  671. self._InternalTestCopyToProto(
  672. unittest_pb2.TestForeignNested.DESCRIPTOR,
  673. descriptor_pb2.DescriptorProto,
  674. TEST_FOREIGN_NESTED_ASCII)
  675. def testCopyToProto_ForeignEnum(self):
  676. TEST_FOREIGN_ENUM_ASCII = """
  677. name: 'ForeignEnum'
  678. value: <
  679. name: 'FOREIGN_FOO'
  680. number: 4
  681. >
  682. value: <
  683. name: 'FOREIGN_BAR'
  684. number: 5
  685. >
  686. value: <
  687. name: 'FOREIGN_BAZ'
  688. number: 6
  689. >
  690. """
  691. self._InternalTestCopyToProto(
  692. unittest_pb2.ForeignEnum.DESCRIPTOR,
  693. descriptor_pb2.EnumDescriptorProto,
  694. TEST_FOREIGN_ENUM_ASCII)
  695. def testCopyToProto_Options(self):
  696. TEST_DEPRECATED_FIELDS_ASCII = """
  697. name: 'TestDeprecatedFields'
  698. field: <
  699. name: 'deprecated_int32'
  700. number: 1
  701. label: 1 # Optional
  702. type: 5 # TYPE_INT32
  703. options: <
  704. deprecated: true
  705. >
  706. >
  707. field {
  708. name: "deprecated_int32_in_oneof"
  709. number: 2
  710. label: LABEL_OPTIONAL
  711. type: TYPE_INT32
  712. options {
  713. deprecated: true
  714. }
  715. oneof_index: 0
  716. }
  717. oneof_decl {
  718. name: "oneof_fields"
  719. }
  720. """
  721. self._InternalTestCopyToProto(
  722. unittest_pb2.TestDeprecatedFields.DESCRIPTOR,
  723. descriptor_pb2.DescriptorProto,
  724. TEST_DEPRECATED_FIELDS_ASCII)
  725. def testCopyToProto_AllExtensions(self):
  726. TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII = """
  727. name: 'TestEmptyMessageWithExtensions'
  728. extension_range: <
  729. start: 1
  730. end: 536870912
  731. >
  732. """
  733. self._InternalTestCopyToProto(
  734. unittest_pb2.TestEmptyMessageWithExtensions.DESCRIPTOR,
  735. descriptor_pb2.DescriptorProto,
  736. TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII)
  737. def testCopyToProto_SeveralExtensions(self):
  738. TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII = """
  739. name: 'TestMultipleExtensionRanges'
  740. extension_range: <
  741. start: 42
  742. end: 43
  743. >
  744. extension_range: <
  745. start: 4143
  746. end: 4244
  747. >
  748. extension_range: <
  749. start: 65536
  750. end: 536870912
  751. >
  752. """
  753. self._InternalTestCopyToProto(
  754. unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR,
  755. descriptor_pb2.DescriptorProto,
  756. TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII)
  757. def testCopyToProto_FileDescriptor(self):
  758. UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII = ("""
  759. name: 'google/protobuf/unittest_import.proto'
  760. package: 'protobuf_unittest_import'
  761. dependency: 'google/protobuf/unittest_import_public.proto'
  762. message_type: <
  763. name: 'ImportMessage'
  764. field: <
  765. name: 'd'
  766. number: 1
  767. label: 1 # Optional
  768. type: 5 # TYPE_INT32
  769. >
  770. >
  771. """ +
  772. """enum_type: <
  773. name: 'ImportEnum'
  774. value: <
  775. name: 'IMPORT_FOO'
  776. number: 7
  777. >
  778. value: <
  779. name: 'IMPORT_BAR'
  780. number: 8
  781. >
  782. value: <
  783. name: 'IMPORT_BAZ'
  784. number: 9
  785. >
  786. >
  787. enum_type: <
  788. name: 'ImportEnumForMap'
  789. value: <
  790. name: 'UNKNOWN'
  791. number: 0
  792. >
  793. value: <
  794. name: 'FOO'
  795. number: 1
  796. >
  797. value: <
  798. name: 'BAR'
  799. number: 2
  800. >
  801. >
  802. options: <
  803. java_package: 'com.google.protobuf.test'
  804. optimize_for: 1 # SPEED
  805. """ +
  806. """
  807. cc_enable_arenas: true
  808. >
  809. public_dependency: 0
  810. """)
  811. self._InternalTestCopyToProto(
  812. unittest_import_pb2.DESCRIPTOR,
  813. descriptor_pb2.FileDescriptorProto,
  814. UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII)
  815. def testCopyToProto_ServiceDescriptor(self):
  816. TEST_SERVICE_ASCII = """
  817. name: 'TestService'
  818. method: <
  819. name: 'Foo'
  820. input_type: '.protobuf_unittest.FooRequest'
  821. output_type: '.protobuf_unittest.FooResponse'
  822. >
  823. method: <
  824. name: 'Bar'
  825. input_type: '.protobuf_unittest.BarRequest'
  826. output_type: '.protobuf_unittest.BarResponse'
  827. >
  828. """
  829. self._InternalTestCopyToProto(
  830. unittest_pb2.TestService.DESCRIPTOR,
  831. descriptor_pb2.ServiceDescriptorProto,
  832. TEST_SERVICE_ASCII)
  833. def testCopyToProto_MethodDescriptor(self):
  834. expected_ascii = """
  835. name: 'Foo'
  836. input_type: '.protobuf_unittest.FooRequest'
  837. output_type: '.protobuf_unittest.FooResponse'
  838. """
  839. method_descriptor = unittest_pb2.TestService.DESCRIPTOR.FindMethodByName(
  840. 'Foo')
  841. self._InternalTestCopyToProto(
  842. method_descriptor,
  843. descriptor_pb2.MethodDescriptorProto,
  844. expected_ascii)
  845. @unittest.skipIf(
  846. api_implementation.Type() == 'python',
  847. 'Pure python does not raise error.')
  848. # TODO(jieluo): Fix pure python to check with the proto type.
  849. def testCopyToProto_TypeError(self):
  850. file_proto = descriptor_pb2.FileDescriptorProto()
  851. self.assertRaises(TypeError,
  852. unittest_pb2.TestEmptyMessage.DESCRIPTOR.CopyToProto,
  853. file_proto)
  854. self.assertRaises(TypeError,
  855. unittest_pb2.ForeignEnum.DESCRIPTOR.CopyToProto,
  856. file_proto)
  857. self.assertRaises(TypeError,
  858. unittest_pb2.TestService.DESCRIPTOR.CopyToProto,
  859. file_proto)
  860. proto = descriptor_pb2.DescriptorProto()
  861. self.assertRaises(TypeError,
  862. unittest_import_pb2.DESCRIPTOR.CopyToProto,
  863. proto)
  864. class MakeDescriptorTest(unittest.TestCase):
  865. def testMakeDescriptorWithNestedFields(self):
  866. file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
  867. file_descriptor_proto.name = 'Foo2'
  868. message_type = file_descriptor_proto.message_type.add()
  869. message_type.name = file_descriptor_proto.name
  870. nested_type = message_type.nested_type.add()
  871. nested_type.name = 'Sub'
  872. enum_type = nested_type.enum_type.add()
  873. enum_type.name = 'FOO'
  874. enum_type_val = enum_type.value.add()
  875. enum_type_val.name = 'BAR'
  876. enum_type_val.number = 3
  877. field = message_type.field.add()
  878. field.number = 1
  879. field.name = 'uint64_field'
  880. field.label = descriptor.FieldDescriptor.LABEL_REQUIRED
  881. field.type = descriptor.FieldDescriptor.TYPE_UINT64
  882. field = message_type.field.add()
  883. field.number = 2
  884. field.name = 'nested_message_field'
  885. field.label = descriptor.FieldDescriptor.LABEL_REQUIRED
  886. field.type = descriptor.FieldDescriptor.TYPE_MESSAGE
  887. field.type_name = 'Sub'
  888. enum_field = nested_type.field.add()
  889. enum_field.number = 2
  890. enum_field.name = 'bar_field'
  891. enum_field.label = descriptor.FieldDescriptor.LABEL_REQUIRED
  892. enum_field.type = descriptor.FieldDescriptor.TYPE_ENUM
  893. enum_field.type_name = 'Foo2.Sub.FOO'
  894. result = descriptor.MakeDescriptor(message_type)
  895. self.assertEqual(result.fields[0].cpp_type,
  896. descriptor.FieldDescriptor.CPPTYPE_UINT64)
  897. self.assertEqual(result.fields[1].cpp_type,
  898. descriptor.FieldDescriptor.CPPTYPE_MESSAGE)
  899. self.assertEqual(result.fields[1].message_type.containing_type,
  900. result)
  901. self.assertEqual(result.nested_types[0].fields[0].full_name,
  902. 'Foo2.Sub.bar_field')
  903. self.assertEqual(result.nested_types[0].fields[0].enum_type,
  904. result.nested_types[0].enum_types[0])
  905. self.assertFalse(result.has_options)
  906. self.assertFalse(result.fields[0].has_options)
  907. if api_implementation.Type() == 'cpp':
  908. with self.assertRaises(AttributeError):
  909. result.fields[0].has_options = False
  910. def testMakeDescriptorWithUnsignedIntField(self):
  911. file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
  912. file_descriptor_proto.name = 'Foo'
  913. message_type = file_descriptor_proto.message_type.add()
  914. message_type.name = file_descriptor_proto.name
  915. enum_type = message_type.enum_type.add()
  916. enum_type.name = 'FOO'
  917. enum_type_val = enum_type.value.add()
  918. enum_type_val.name = 'BAR'
  919. enum_type_val.number = 3
  920. field = message_type.field.add()
  921. field.number = 1
  922. field.name = 'uint64_field'
  923. field.label = descriptor.FieldDescriptor.LABEL_REQUIRED
  924. field.type = descriptor.FieldDescriptor.TYPE_UINT64
  925. enum_field = message_type.field.add()
  926. enum_field.number = 2
  927. enum_field.name = 'bar_field'
  928. enum_field.label = descriptor.FieldDescriptor.LABEL_REQUIRED
  929. enum_field.type = descriptor.FieldDescriptor.TYPE_ENUM
  930. enum_field.type_name = 'Foo.FOO'
  931. result = descriptor.MakeDescriptor(message_type)
  932. self.assertEqual(result.fields[0].cpp_type,
  933. descriptor.FieldDescriptor.CPPTYPE_UINT64)
  934. def testMakeDescriptorWithOptions(self):
  935. descriptor_proto = descriptor_pb2.DescriptorProto()
  936. aggregate_message = unittest_custom_options_pb2.AggregateMessage
  937. aggregate_message.DESCRIPTOR.CopyToProto(descriptor_proto)
  938. reformed_descriptor = descriptor.MakeDescriptor(descriptor_proto)
  939. options = reformed_descriptor.GetOptions()
  940. self.assertEqual(101,
  941. options.Extensions[unittest_custom_options_pb2.msgopt].i)
  942. def testCamelcaseName(self):
  943. descriptor_proto = descriptor_pb2.DescriptorProto()
  944. descriptor_proto.name = 'Bar'
  945. names = ['foo_foo', 'FooBar', 'fooBaz', 'fooFoo', 'foobar']
  946. camelcase_names = ['fooFoo', 'fooBar', 'fooBaz', 'fooFoo', 'foobar']
  947. for index in range(len(names)):
  948. field = descriptor_proto.field.add()
  949. field.number = index + 1
  950. field.name = names[index]
  951. result = descriptor.MakeDescriptor(descriptor_proto)
  952. for index in range(len(camelcase_names)):
  953. self.assertEqual(result.fields[index].camelcase_name,
  954. camelcase_names[index])
  955. def testJsonName(self):
  956. descriptor_proto = descriptor_pb2.DescriptorProto()
  957. descriptor_proto.name = 'TestJsonName'
  958. names = ['field_name', 'fieldName', 'FieldName',
  959. '_field_name', 'FIELD_NAME', 'json_name']
  960. json_names = ['fieldName', 'fieldName', 'FieldName',
  961. 'FieldName', 'FIELDNAME', '@type']
  962. for index in range(len(names)):
  963. field = descriptor_proto.field.add()
  964. field.number = index + 1
  965. field.name = names[index]
  966. field.json_name = '@type'
  967. result = descriptor.MakeDescriptor(descriptor_proto)
  968. for index in range(len(json_names)):
  969. self.assertEqual(result.fields[index].json_name,
  970. json_names[index])
  971. if __name__ == '__main__':
  972. unittest.main()