PageRenderTime 23ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 0ms

/python/google/protobuf/internal/generator_test.py

https://gitlab.com/admin-github-cloud/protobuf
Python | 348 lines | 245 code | 47 blank | 56 comment | 12 complexity | 1b6aedb678d3e73c28960cb202551a20 MD5 | raw file
  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. def testNoGenericServices(self):
  200. self.assertTrue(hasattr(unittest_no_generic_services_pb2, "TestMessage"))
  201. self.assertTrue(hasattr(unittest_no_generic_services_pb2, "FOO"))
  202. self.assertTrue(hasattr(unittest_no_generic_services_pb2, "test_extension"))
  203. # Make sure unittest_no_generic_services_pb2 has no services subclassing
  204. # Proto2 Service class.
  205. if hasattr(unittest_no_generic_services_pb2, "TestService"):
  206. self.assertFalse(issubclass(unittest_no_generic_services_pb2.TestService,
  207. service.Service))
  208. def testMessageTypesByName(self):
  209. file_type = unittest_pb2.DESCRIPTOR
  210. self.assertEqual(
  211. unittest_pb2._TESTALLTYPES,
  212. file_type.message_types_by_name[unittest_pb2._TESTALLTYPES.name])
  213. # Nested messages shouldn't be included in the message_types_by_name
  214. # dictionary (like in the C++ API).
  215. self.assertFalse(
  216. unittest_pb2._TESTALLTYPES_NESTEDMESSAGE.name in
  217. file_type.message_types_by_name)
  218. def testEnumTypesByName(self):
  219. file_type = unittest_pb2.DESCRIPTOR
  220. self.assertEqual(
  221. unittest_pb2._FOREIGNENUM,
  222. file_type.enum_types_by_name[unittest_pb2._FOREIGNENUM.name])
  223. def testExtensionsByName(self):
  224. file_type = unittest_pb2.DESCRIPTOR
  225. self.assertEqual(
  226. unittest_pb2.my_extension_string,
  227. file_type.extensions_by_name[unittest_pb2.my_extension_string.name])
  228. def testPublicImports(self):
  229. # Test public imports as embedded message.
  230. all_type_proto = unittest_pb2.TestAllTypes()
  231. self.assertEqual(0, all_type_proto.optional_public_import_message.e)
  232. # PublicImportMessage is actually defined in unittest_import_public_pb2
  233. # module, and is public imported by unittest_import_pb2 module.
  234. public_import_proto = unittest_import_pb2.PublicImportMessage()
  235. self.assertEqual(0, public_import_proto.e)
  236. self.assertTrue(unittest_import_public_pb2.PublicImportMessage is
  237. unittest_import_pb2.PublicImportMessage)
  238. def testBadIdentifiers(self):
  239. # We're just testing that the code was imported without problems.
  240. message = test_bad_identifiers_pb2.TestBadIdentifiers()
  241. self.assertEqual(message.Extensions[test_bad_identifiers_pb2.message],
  242. "foo")
  243. self.assertEqual(message.Extensions[test_bad_identifiers_pb2.descriptor],
  244. "bar")
  245. self.assertEqual(message.Extensions[test_bad_identifiers_pb2.reflection],
  246. "baz")
  247. self.assertEqual(message.Extensions[test_bad_identifiers_pb2.service],
  248. "qux")
  249. def testOneof(self):
  250. desc = unittest_pb2.TestAllTypes.DESCRIPTOR
  251. self.assertEqual(1, len(desc.oneofs))
  252. self.assertEqual('oneof_field', desc.oneofs[0].name)
  253. self.assertEqual(0, desc.oneofs[0].index)
  254. self.assertIs(desc, desc.oneofs[0].containing_type)
  255. self.assertIs(desc.oneofs[0], desc.oneofs_by_name['oneof_field'])
  256. nested_names = set(['oneof_uint32', 'oneof_nested_message',
  257. 'oneof_string', 'oneof_bytes'])
  258. self.assertEqual(
  259. nested_names,
  260. set([field.name for field in desc.oneofs[0].fields]))
  261. for field_name, field_desc in desc.fields_by_name.items():
  262. if field_name in nested_names:
  263. self.assertIs(desc.oneofs[0], field_desc.containing_oneof)
  264. else:
  265. self.assertIsNone(field_desc.containing_oneof)
  266. class SymbolDatabaseRegistrationTest(unittest.TestCase):
  267. """Checks that messages, enums and files are correctly registered."""
  268. def testGetSymbol(self):
  269. self.assertEqual(
  270. unittest_pb2.TestAllTypes, symbol_database.Default().GetSymbol(
  271. 'protobuf_unittest.TestAllTypes'))
  272. self.assertEqual(
  273. unittest_pb2.TestAllTypes.NestedMessage,
  274. symbol_database.Default().GetSymbol(
  275. 'protobuf_unittest.TestAllTypes.NestedMessage'))
  276. with self.assertRaises(KeyError):
  277. symbol_database.Default().GetSymbol('protobuf_unittest.NestedMessage')
  278. self.assertEqual(
  279. unittest_pb2.TestAllTypes.OptionalGroup,
  280. symbol_database.Default().GetSymbol(
  281. 'protobuf_unittest.TestAllTypes.OptionalGroup'))
  282. self.assertEqual(
  283. unittest_pb2.TestAllTypes.RepeatedGroup,
  284. symbol_database.Default().GetSymbol(
  285. 'protobuf_unittest.TestAllTypes.RepeatedGroup'))
  286. def testEnums(self):
  287. self.assertEqual(
  288. 'protobuf_unittest.ForeignEnum',
  289. symbol_database.Default().pool.FindEnumTypeByName(
  290. 'protobuf_unittest.ForeignEnum').full_name)
  291. self.assertEqual(
  292. 'protobuf_unittest.TestAllTypes.NestedEnum',
  293. symbol_database.Default().pool.FindEnumTypeByName(
  294. 'protobuf_unittest.TestAllTypes.NestedEnum').full_name)
  295. def testFindFileByName(self):
  296. self.assertEqual(
  297. 'google/protobuf/unittest.proto',
  298. symbol_database.Default().pool.FindFileByName(
  299. 'google/protobuf/unittest.proto').name)
  300. if __name__ == '__main__':
  301. unittest.main()