店播爬取Python脚本

generator_test.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. # TODO(robinson): Flesh this out considerably. We focused on reflection_test.py
  33. # first, since it's testing the subtler code, and since it provides decent
  34. # indirect testing of the protocol compiler output.
  35. """Unittest that directly tests the output of the pure-Python protocol
  36. compiler. See //google/protobuf/internal/reflection_test.py for a test which
  37. further ensures that we can use Python protocol message objects as we expect.
  38. """
  39. __author__ = 'robinson@google.com (Will Robinson)'
  40. try:
  41. import unittest2 as unittest #PY26
  42. except ImportError:
  43. import unittest
  44. from google.protobuf.internal import test_bad_identifiers_pb2
  45. from google.protobuf import unittest_custom_options_pb2
  46. from google.protobuf import unittest_import_pb2
  47. from google.protobuf import unittest_import_public_pb2
  48. from google.protobuf import unittest_mset_pb2
  49. from google.protobuf import unittest_mset_wire_format_pb2
  50. from google.protobuf import unittest_no_generic_services_pb2
  51. from google.protobuf import unittest_pb2
  52. from google.protobuf import service
  53. from google.protobuf import symbol_database
  54. MAX_EXTENSION = 536870912
  55. class GeneratorTest(unittest.TestCase):
  56. def testNestedMessageDescriptor(self):
  57. field_name = 'optional_nested_message'
  58. proto_type = unittest_pb2.TestAllTypes
  59. self.assertEqual(
  60. proto_type.NestedMessage.DESCRIPTOR,
  61. proto_type.DESCRIPTOR.fields_by_name[field_name].message_type)
  62. def testEnums(self):
  63. # We test only module-level enums here.
  64. # TODO(robinson): Examine descriptors directly to check
  65. # enum descriptor output.
  66. self.assertEqual(4, unittest_pb2.FOREIGN_FOO)
  67. self.assertEqual(5, unittest_pb2.FOREIGN_BAR)
  68. self.assertEqual(6, unittest_pb2.FOREIGN_BAZ)
  69. proto = unittest_pb2.TestAllTypes()
  70. self.assertEqual(1, proto.FOO)
  71. self.assertEqual(1, unittest_pb2.TestAllTypes.FOO)
  72. self.assertEqual(2, proto.BAR)
  73. self.assertEqual(2, unittest_pb2.TestAllTypes.BAR)
  74. self.assertEqual(3, proto.BAZ)
  75. self.assertEqual(3, unittest_pb2.TestAllTypes.BAZ)
  76. def testExtremeDefaultValues(self):
  77. message = unittest_pb2.TestExtremeDefaultValues()
  78. # Python pre-2.6 does not have isinf() or isnan() functions, so we have
  79. # to provide our own.
  80. def isnan(val):
  81. # NaN is never equal to itself.
  82. return val != val
  83. def isinf(val):
  84. # Infinity times zero equals NaN.
  85. return not isnan(val) and isnan(val * 0)
  86. self.assertTrue(isinf(message.inf_double))
  87. self.assertTrue(message.inf_double > 0)
  88. self.assertTrue(isinf(message.neg_inf_double))
  89. self.assertTrue(message.neg_inf_double < 0)
  90. self.assertTrue(isnan(message.nan_double))
  91. self.assertTrue(isinf(message.inf_float))
  92. self.assertTrue(message.inf_float > 0)
  93. self.assertTrue(isinf(message.neg_inf_float))
  94. self.assertTrue(message.neg_inf_float < 0)
  95. self.assertTrue(isnan(message.nan_float))
  96. self.assertEqual("? ? ?? ?? ??? ??/ ??-", message.cpp_trigraph)
  97. def testHasDefaultValues(self):
  98. desc = unittest_pb2.TestAllTypes.DESCRIPTOR
  99. expected_has_default_by_name = {
  100. 'optional_int32': False,
  101. 'repeated_int32': False,
  102. 'optional_nested_message': False,
  103. 'default_int32': True,
  104. }
  105. has_default_by_name = dict(
  106. [(f.name, f.has_default_value)
  107. for f in desc.fields
  108. if f.name in expected_has_default_by_name])
  109. self.assertEqual(expected_has_default_by_name, has_default_by_name)
  110. def testContainingTypeBehaviorForExtensions(self):
  111. self.assertEqual(unittest_pb2.optional_int32_extension.containing_type,
  112. unittest_pb2.TestAllExtensions.DESCRIPTOR)
  113. self.assertEqual(unittest_pb2.TestRequired.single.containing_type,
  114. unittest_pb2.TestAllExtensions.DESCRIPTOR)
  115. def testExtensionScope(self):
  116. self.assertEqual(unittest_pb2.optional_int32_extension.extension_scope,
  117. None)
  118. self.assertEqual(unittest_pb2.TestRequired.single.extension_scope,
  119. unittest_pb2.TestRequired.DESCRIPTOR)
  120. def testIsExtension(self):
  121. self.assertTrue(unittest_pb2.optional_int32_extension.is_extension)
  122. self.assertTrue(unittest_pb2.TestRequired.single.is_extension)
  123. message_descriptor = unittest_pb2.TestRequired.DESCRIPTOR
  124. non_extension_descriptor = message_descriptor.fields_by_name['a']
  125. self.assertTrue(not non_extension_descriptor.is_extension)
  126. def testOptions(self):
  127. proto = unittest_mset_wire_format_pb2.TestMessageSet()
  128. self.assertTrue(proto.DESCRIPTOR.GetOptions().message_set_wire_format)
  129. def testMessageWithCustomOptions(self):
  130. proto = unittest_custom_options_pb2.TestMessageWithCustomOptions()
  131. enum_options = proto.DESCRIPTOR.enum_types_by_name['AnEnum'].GetOptions()
  132. self.assertTrue(enum_options is not None)
  133. # TODO(gps): We really should test for the presence of the enum_opt1
  134. # extension and for its value to be set to -789.
  135. def testNestedTypes(self):
  136. self.assertEqual(
  137. set(unittest_pb2.TestAllTypes.DESCRIPTOR.nested_types),
  138. set([
  139. unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR,
  140. unittest_pb2.TestAllTypes.OptionalGroup.DESCRIPTOR,
  141. unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR,
  142. ]))
  143. self.assertEqual(unittest_pb2.TestEmptyMessage.DESCRIPTOR.nested_types, [])
  144. self.assertEqual(
  145. unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.nested_types, [])
  146. def testContainingType(self):
  147. self.assertTrue(
  148. unittest_pb2.TestEmptyMessage.DESCRIPTOR.containing_type is None)
  149. self.assertTrue(
  150. unittest_pb2.TestAllTypes.DESCRIPTOR.containing_type is None)
  151. self.assertEqual(
  152. unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type,
  153. unittest_pb2.TestAllTypes.DESCRIPTOR)
  154. self.assertEqual(
  155. unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type,
  156. unittest_pb2.TestAllTypes.DESCRIPTOR)
  157. self.assertEqual(
  158. unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR.containing_type,
  159. unittest_pb2.TestAllTypes.DESCRIPTOR)
  160. def testContainingTypeInEnumDescriptor(self):
  161. self.assertTrue(unittest_pb2._FOREIGNENUM.containing_type is None)
  162. self.assertEqual(unittest_pb2._TESTALLTYPES_NESTEDENUM.containing_type,
  163. unittest_pb2.TestAllTypes.DESCRIPTOR)
  164. def testPackage(self):
  165. self.assertEqual(
  166. unittest_pb2.TestAllTypes.DESCRIPTOR.file.package,
  167. 'protobuf_unittest')
  168. desc = unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR
  169. self.assertEqual(desc.file.package, 'protobuf_unittest')
  170. self.assertEqual(
  171. unittest_import_pb2.ImportMessage.DESCRIPTOR.file.package,
  172. 'protobuf_unittest_import')
  173. self.assertEqual(
  174. unittest_pb2._FOREIGNENUM.file.package, 'protobuf_unittest')
  175. self.assertEqual(
  176. unittest_pb2._TESTALLTYPES_NESTEDENUM.file.package,
  177. 'protobuf_unittest')
  178. self.assertEqual(
  179. unittest_import_pb2._IMPORTENUM.file.package,
  180. 'protobuf_unittest_import')
  181. def testExtensionRange(self):
  182. self.assertEqual(
  183. unittest_pb2.TestAllTypes.DESCRIPTOR.extension_ranges, [])
  184. self.assertEqual(
  185. unittest_pb2.TestAllExtensions.DESCRIPTOR.extension_ranges,
  186. [(1, MAX_EXTENSION)])
  187. self.assertEqual(
  188. unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR.extension_ranges,
  189. [(42, 43), (4143, 4244), (65536, MAX_EXTENSION)])
  190. def testFileDescriptor(self):
  191. self.assertEqual(unittest_pb2.DESCRIPTOR.name,
  192. 'google/protobuf/unittest.proto')
  193. self.assertEqual(unittest_pb2.DESCRIPTOR.package, 'protobuf_unittest')
  194. self.assertFalse(unittest_pb2.DESCRIPTOR.serialized_pb is None)
  195. self.assertEqual(unittest_pb2.DESCRIPTOR.dependencies,
  196. [unittest_import_pb2.DESCRIPTOR])
  197. self.assertEqual(unittest_import_pb2.DESCRIPTOR.dependencies,
  198. [unittest_import_public_pb2.DESCRIPTOR])
  199. self.assertEqual(unittest_import_pb2.DESCRIPTOR.public_dependencies,
  200. [unittest_import_public_pb2.DESCRIPTOR])
  201. def testNoGenericServices(self):
  202. self.assertTrue(hasattr(unittest_no_generic_services_pb2, "TestMessage"))
  203. self.assertTrue(hasattr(unittest_no_generic_services_pb2, "FOO"))
  204. self.assertTrue(hasattr(unittest_no_generic_services_pb2, "test_extension"))
  205. # Make sure unittest_no_generic_services_pb2 has no services subclassing
  206. # Proto2 Service class.
  207. if hasattr(unittest_no_generic_services_pb2, "TestService"):
  208. self.assertFalse(issubclass(unittest_no_generic_services_pb2.TestService,
  209. service.Service))
  210. def testMessageTypesByName(self):
  211. file_type = unittest_pb2.DESCRIPTOR
  212. self.assertEqual(
  213. unittest_pb2._TESTALLTYPES,
  214. file_type.message_types_by_name[unittest_pb2._TESTALLTYPES.name])
  215. # Nested messages shouldn't be included in the message_types_by_name
  216. # dictionary (like in the C++ API).
  217. self.assertFalse(
  218. unittest_pb2._TESTALLTYPES_NESTEDMESSAGE.name in
  219. file_type.message_types_by_name)
  220. def testEnumTypesByName(self):
  221. file_type = unittest_pb2.DESCRIPTOR
  222. self.assertEqual(
  223. unittest_pb2._FOREIGNENUM,
  224. file_type.enum_types_by_name[unittest_pb2._FOREIGNENUM.name])
  225. def testExtensionsByName(self):
  226. file_type = unittest_pb2.DESCRIPTOR
  227. self.assertEqual(
  228. unittest_pb2.my_extension_string,
  229. file_type.extensions_by_name[unittest_pb2.my_extension_string.name])
  230. def testPublicImports(self):
  231. # Test public imports as embedded message.
  232. all_type_proto = unittest_pb2.TestAllTypes()
  233. self.assertEqual(0, all_type_proto.optional_public_import_message.e)
  234. # PublicImportMessage is actually defined in unittest_import_public_pb2
  235. # module, and is public imported by unittest_import_pb2 module.
  236. public_import_proto = unittest_import_pb2.PublicImportMessage()
  237. self.assertEqual(0, public_import_proto.e)
  238. self.assertTrue(unittest_import_public_pb2.PublicImportMessage is
  239. unittest_import_pb2.PublicImportMessage)
  240. def testBadIdentifiers(self):
  241. # We're just testing that the code was imported without problems.
  242. message = test_bad_identifiers_pb2.TestBadIdentifiers()
  243. self.assertEqual(message.Extensions[test_bad_identifiers_pb2.message],
  244. "foo")
  245. self.assertEqual(message.Extensions[test_bad_identifiers_pb2.descriptor],
  246. "bar")
  247. self.assertEqual(message.Extensions[test_bad_identifiers_pb2.reflection],
  248. "baz")
  249. self.assertEqual(message.Extensions[test_bad_identifiers_pb2.service],
  250. "qux")
  251. def testOneof(self):
  252. desc = unittest_pb2.TestAllTypes.DESCRIPTOR
  253. self.assertEqual(1, len(desc.oneofs))
  254. self.assertEqual('oneof_field', desc.oneofs[0].name)
  255. self.assertEqual(0, desc.oneofs[0].index)
  256. self.assertIs(desc, desc.oneofs[0].containing_type)
  257. self.assertIs(desc.oneofs[0], desc.oneofs_by_name['oneof_field'])
  258. nested_names = set(['oneof_uint32', 'oneof_nested_message',
  259. 'oneof_string', 'oneof_bytes'])
  260. self.assertEqual(
  261. nested_names,
  262. set([field.name for field in desc.oneofs[0].fields]))
  263. for field_name, field_desc in desc.fields_by_name.items():
  264. if field_name in nested_names:
  265. self.assertIs(desc.oneofs[0], field_desc.containing_oneof)
  266. else:
  267. self.assertIsNone(field_desc.containing_oneof)
  268. def testEnumWithDupValue(self):
  269. self.assertEqual('FOO1',
  270. unittest_pb2.TestEnumWithDupValue.Name(unittest_pb2.FOO1))
  271. self.assertEqual('FOO1',
  272. unittest_pb2.TestEnumWithDupValue.Name(unittest_pb2.FOO2))
  273. self.assertEqual('BAR1',
  274. unittest_pb2.TestEnumWithDupValue.Name(unittest_pb2.BAR1))
  275. self.assertEqual('BAR1',
  276. unittest_pb2.TestEnumWithDupValue.Name(unittest_pb2.BAR2))
  277. class SymbolDatabaseRegistrationTest(unittest.TestCase):
  278. """Checks that messages, enums and files are correctly registered."""
  279. def testGetSymbol(self):
  280. self.assertEqual(
  281. unittest_pb2.TestAllTypes, symbol_database.Default().GetSymbol(
  282. 'protobuf_unittest.TestAllTypes'))
  283. self.assertEqual(
  284. unittest_pb2.TestAllTypes.NestedMessage,
  285. symbol_database.Default().GetSymbol(
  286. 'protobuf_unittest.TestAllTypes.NestedMessage'))
  287. with self.assertRaises(KeyError):
  288. symbol_database.Default().GetSymbol('protobuf_unittest.NestedMessage')
  289. self.assertEqual(
  290. unittest_pb2.TestAllTypes.OptionalGroup,
  291. symbol_database.Default().GetSymbol(
  292. 'protobuf_unittest.TestAllTypes.OptionalGroup'))
  293. self.assertEqual(
  294. unittest_pb2.TestAllTypes.RepeatedGroup,
  295. symbol_database.Default().GetSymbol(
  296. 'protobuf_unittest.TestAllTypes.RepeatedGroup'))
  297. def testEnums(self):
  298. self.assertEqual(
  299. 'protobuf_unittest.ForeignEnum',
  300. symbol_database.Default().pool.FindEnumTypeByName(
  301. 'protobuf_unittest.ForeignEnum').full_name)
  302. self.assertEqual(
  303. 'protobuf_unittest.TestAllTypes.NestedEnum',
  304. symbol_database.Default().pool.FindEnumTypeByName(
  305. 'protobuf_unittest.TestAllTypes.NestedEnum').full_name)
  306. def testFindFileByName(self):
  307. self.assertEqual(
  308. 'google/protobuf/unittest.proto',
  309. symbol_database.Default().pool.FindFileByName(
  310. 'google/protobuf/unittest.proto').name)
  311. if __name__ == '__main__':
  312. unittest.main()