blob: 9956da59b44697b171b1cef80fb495953c0fde78 [file] [log] [blame]
Tamir Duberstein9d9d0b72015-04-11 20:23:45 -07001#! /usr/bin/env python
kenton@google.com26bd9ee2008-11-21 00:06:27 +00002#
temporal40ee5512008-07-10 02:12:20 +00003# Protocol Buffers - Google's data interchange format
kenton@google.com24bf56f2008-09-24 20:31:01 +00004# Copyright 2008 Google Inc. All rights reserved.
Feng Xiaoe4288622014-10-01 16:26:23 -07005# https://developers.google.com/protocol-buffers/
temporal40ee5512008-07-10 02:12:20 +00006#
kenton@google.com24bf56f2008-09-24 20:31:01 +00007# Redistribution and use in source and binary forms, with or without
8# modification, are permitted provided that the following conditions are
9# met:
temporal40ee5512008-07-10 02:12:20 +000010#
kenton@google.com24bf56f2008-09-24 20:31:01 +000011# * 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.
temporal40ee5512008-07-10 02:12:20 +000020#
kenton@google.com24bf56f2008-09-24 20:31:01 +000021# 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.
temporal40ee5512008-07-10 02:12:20 +000032
33# TODO(robinson): Flesh this out considerably. We focused on reflection_test.py
34# first, since it's testing the subtler code, and since it provides decent
35# indirect testing of the protocol compiler output.
36
37"""Unittest that directly tests the output of the pure-Python protocol
Feng Xiao6ef984a2014-11-10 17:34:54 -080038compiler. See //google/protobuf/internal/reflection_test.py for a test which
temporal40ee5512008-07-10 02:12:20 +000039further ensures that we can use Python protocol message objects as we expect.
40"""
41
42__author__ = 'robinson@google.com (Will Robinson)'
43
Dan O'Reilly2621c8a2015-08-14 22:54:53 -040044try:
45 import unittest2 as unittest
46except ImportError:
47 import unittest
xiaofeng@google.comb55a20f2012-09-22 02:40:50 +000048from google.protobuf.internal import test_bad_identifiers_pb2
liujisi@google.com33165fe2010-11-02 13:14:58 +000049from google.protobuf import unittest_custom_options_pb2
kenton@google.comfccb1462009-12-18 02:11:36 +000050from google.protobuf import unittest_import_pb2
xiaofeng@google.comb55a20f2012-09-22 02:40:50 +000051from google.protobuf import unittest_import_public_pb2
temporal40ee5512008-07-10 02:12:20 +000052from google.protobuf import unittest_mset_pb2
Feng Xiaoeee38b02015-08-22 18:25:48 -070053from google.protobuf import unittest_mset_wire_format_pb2
kenton@google.comfccb1462009-12-18 02:11:36 +000054from google.protobuf import unittest_no_generic_services_pb2
jieluo@google.combde4a322014-08-12 21:10:30 +000055from google.protobuf import unittest_pb2
liujisi@google.com33165fe2010-11-02 13:14:58 +000056from google.protobuf import service
jieluo@google.combde4a322014-08-12 21:10:30 +000057from google.protobuf import symbol_database
kenton@google.comfccb1462009-12-18 02:11:36 +000058
59MAX_EXTENSION = 536870912
temporal40ee5512008-07-10 02:12:20 +000060
61
Tamir Duberstein9f42f5f2015-01-13 14:47:32 -050062class GeneratorTest(unittest.TestCase):
temporal40ee5512008-07-10 02:12:20 +000063
64 def testNestedMessageDescriptor(self):
65 field_name = 'optional_nested_message'
66 proto_type = unittest_pb2.TestAllTypes
67 self.assertEqual(
68 proto_type.NestedMessage.DESCRIPTOR,
69 proto_type.DESCRIPTOR.fields_by_name[field_name].message_type)
70
71 def testEnums(self):
72 # We test only module-level enums here.
73 # TODO(robinson): Examine descriptors directly to check
74 # enum descriptor output.
75 self.assertEqual(4, unittest_pb2.FOREIGN_FOO)
76 self.assertEqual(5, unittest_pb2.FOREIGN_BAR)
77 self.assertEqual(6, unittest_pb2.FOREIGN_BAZ)
78
79 proto = unittest_pb2.TestAllTypes()
80 self.assertEqual(1, proto.FOO)
81 self.assertEqual(1, unittest_pb2.TestAllTypes.FOO)
82 self.assertEqual(2, proto.BAR)
83 self.assertEqual(2, unittest_pb2.TestAllTypes.BAR)
84 self.assertEqual(3, proto.BAZ)
85 self.assertEqual(3, unittest_pb2.TestAllTypes.BAZ)
86
kenton@google.comfccb1462009-12-18 02:11:36 +000087 def testExtremeDefaultValues(self):
88 message = unittest_pb2.TestExtremeDefaultValues()
kenton@google.comd0047c42009-12-23 02:01:01 +000089
90 # Python pre-2.6 does not have isinf() or isnan() functions, so we have
91 # to provide our own.
92 def isnan(val):
93 # NaN is never equal to itself.
94 return val != val
95 def isinf(val):
96 # Infinity times zero equals NaN.
97 return not isnan(val) and isnan(val * 0)
98
99 self.assertTrue(isinf(message.inf_double))
100 self.assertTrue(message.inf_double > 0)
101 self.assertTrue(isinf(message.neg_inf_double))
102 self.assertTrue(message.neg_inf_double < 0)
103 self.assertTrue(isnan(message.nan_double))
104
105 self.assertTrue(isinf(message.inf_float))
106 self.assertTrue(message.inf_float > 0)
107 self.assertTrue(isinf(message.neg_inf_float))
108 self.assertTrue(message.neg_inf_float < 0)
109 self.assertTrue(isnan(message.nan_float))
liujisi@google.com5c20ca12010-12-21 05:33:13 +0000110 self.assertEqual("? ? ?? ?? ??? ??/ ??-", message.cpp_trigraph)
kenton@google.comfccb1462009-12-18 02:11:36 +0000111
112 def testHasDefaultValues(self):
113 desc = unittest_pb2.TestAllTypes.DESCRIPTOR
114
115 expected_has_default_by_name = {
116 'optional_int32': False,
117 'repeated_int32': False,
118 'optional_nested_message': False,
119 'default_int32': True,
120 }
121
122 has_default_by_name = dict(
123 [(f.name, f.has_default_value)
124 for f in desc.fields
125 if f.name in expected_has_default_by_name])
126 self.assertEqual(expected_has_default_by_name, has_default_by_name)
127
temporal40ee5512008-07-10 02:12:20 +0000128 def testContainingTypeBehaviorForExtensions(self):
129 self.assertEqual(unittest_pb2.optional_int32_extension.containing_type,
130 unittest_pb2.TestAllExtensions.DESCRIPTOR)
131 self.assertEqual(unittest_pb2.TestRequired.single.containing_type,
132 unittest_pb2.TestAllExtensions.DESCRIPTOR)
133
134 def testExtensionScope(self):
135 self.assertEqual(unittest_pb2.optional_int32_extension.extension_scope,
136 None)
137 self.assertEqual(unittest_pb2.TestRequired.single.extension_scope,
138 unittest_pb2.TestRequired.DESCRIPTOR)
139
140 def testIsExtension(self):
141 self.assertTrue(unittest_pb2.optional_int32_extension.is_extension)
142 self.assertTrue(unittest_pb2.TestRequired.single.is_extension)
143
144 message_descriptor = unittest_pb2.TestRequired.DESCRIPTOR
145 non_extension_descriptor = message_descriptor.fields_by_name['a']
146 self.assertTrue(not non_extension_descriptor.is_extension)
147
148 def testOptions(self):
Feng Xiaoeee38b02015-08-22 18:25:48 -0700149 proto = unittest_mset_wire_format_pb2.TestMessageSet()
temporal40ee5512008-07-10 02:12:20 +0000150 self.assertTrue(proto.DESCRIPTOR.GetOptions().message_set_wire_format)
151
liujisi@google.com33165fe2010-11-02 13:14:58 +0000152 def testMessageWithCustomOptions(self):
153 proto = unittest_custom_options_pb2.TestMessageWithCustomOptions()
154 enum_options = proto.DESCRIPTOR.enum_types_by_name['AnEnum'].GetOptions()
155 self.assertTrue(enum_options is not None)
Veres Lajosc7680722014-11-08 22:59:34 +0000156 # TODO(gps): We really should test for the presence of the enum_opt1
liujisi@google.com33165fe2010-11-02 13:14:58 +0000157 # extension and for its value to be set to -789.
158
kenton@google.comfccb1462009-12-18 02:11:36 +0000159 def testNestedTypes(self):
Dan O'Reilly2621c8a2015-08-14 22:54:53 -0400160 self.assertEqual(
kenton@google.comfccb1462009-12-18 02:11:36 +0000161 set(unittest_pb2.TestAllTypes.DESCRIPTOR.nested_types),
162 set([
163 unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR,
164 unittest_pb2.TestAllTypes.OptionalGroup.DESCRIPTOR,
165 unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR,
166 ]))
167 self.assertEqual(unittest_pb2.TestEmptyMessage.DESCRIPTOR.nested_types, [])
168 self.assertEqual(
169 unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.nested_types, [])
170
171 def testContainingType(self):
172 self.assertTrue(
173 unittest_pb2.TestEmptyMessage.DESCRIPTOR.containing_type is None)
174 self.assertTrue(
175 unittest_pb2.TestAllTypes.DESCRIPTOR.containing_type is None)
176 self.assertEqual(
177 unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type,
178 unittest_pb2.TestAllTypes.DESCRIPTOR)
179 self.assertEqual(
180 unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type,
181 unittest_pb2.TestAllTypes.DESCRIPTOR)
182 self.assertEqual(
183 unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR.containing_type,
184 unittest_pb2.TestAllTypes.DESCRIPTOR)
185
186 def testContainingTypeInEnumDescriptor(self):
187 self.assertTrue(unittest_pb2._FOREIGNENUM.containing_type is None)
188 self.assertEqual(unittest_pb2._TESTALLTYPES_NESTEDENUM.containing_type,
189 unittest_pb2.TestAllTypes.DESCRIPTOR)
190
191 def testPackage(self):
192 self.assertEqual(
193 unittest_pb2.TestAllTypes.DESCRIPTOR.file.package,
194 'protobuf_unittest')
195 desc = unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR
196 self.assertEqual(desc.file.package, 'protobuf_unittest')
197 self.assertEqual(
198 unittest_import_pb2.ImportMessage.DESCRIPTOR.file.package,
199 'protobuf_unittest_import')
200
201 self.assertEqual(
202 unittest_pb2._FOREIGNENUM.file.package, 'protobuf_unittest')
203 self.assertEqual(
204 unittest_pb2._TESTALLTYPES_NESTEDENUM.file.package,
205 'protobuf_unittest')
206 self.assertEqual(
207 unittest_import_pb2._IMPORTENUM.file.package,
208 'protobuf_unittest_import')
209
210 def testExtensionRange(self):
211 self.assertEqual(
212 unittest_pb2.TestAllTypes.DESCRIPTOR.extension_ranges, [])
213 self.assertEqual(
214 unittest_pb2.TestAllExtensions.DESCRIPTOR.extension_ranges,
215 [(1, MAX_EXTENSION)])
216 self.assertEqual(
217 unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR.extension_ranges,
218 [(42, 43), (4143, 4244), (65536, MAX_EXTENSION)])
219
220 def testFileDescriptor(self):
221 self.assertEqual(unittest_pb2.DESCRIPTOR.name,
222 'google/protobuf/unittest.proto')
223 self.assertEqual(unittest_pb2.DESCRIPTOR.package, 'protobuf_unittest')
224 self.assertFalse(unittest_pb2.DESCRIPTOR.serialized_pb is None)
jieluo@google.combde4a322014-08-12 21:10:30 +0000225 self.assertEqual(unittest_pb2.DESCRIPTOR.dependencies,
226 [unittest_import_pb2.DESCRIPTOR])
227 self.assertEqual(unittest_import_pb2.DESCRIPTOR.dependencies,
228 [unittest_import_public_pb2.DESCRIPTOR])
kenton@google.comfccb1462009-12-18 02:11:36 +0000229
230 def testNoGenericServices(self):
kenton@google.comfccb1462009-12-18 02:11:36 +0000231 self.assertTrue(hasattr(unittest_no_generic_services_pb2, "TestMessage"))
232 self.assertTrue(hasattr(unittest_no_generic_services_pb2, "FOO"))
233 self.assertTrue(hasattr(unittest_no_generic_services_pb2, "test_extension"))
liujisi@google.com33165fe2010-11-02 13:14:58 +0000234
235 # Make sure unittest_no_generic_services_pb2 has no services subclassing
236 # Proto2 Service class.
237 if hasattr(unittest_no_generic_services_pb2, "TestService"):
238 self.assertFalse(issubclass(unittest_no_generic_services_pb2.TestService,
239 service.Service))
240
241 def testMessageTypesByName(self):
242 file_type = unittest_pb2.DESCRIPTOR
243 self.assertEqual(
244 unittest_pb2._TESTALLTYPES,
245 file_type.message_types_by_name[unittest_pb2._TESTALLTYPES.name])
246
247 # Nested messages shouldn't be included in the message_types_by_name
248 # dictionary (like in the C++ API).
249 self.assertFalse(
250 unittest_pb2._TESTALLTYPES_NESTEDMESSAGE.name in
251 file_type.message_types_by_name)
kenton@google.comfccb1462009-12-18 02:11:36 +0000252
jieluo@google.combde4a322014-08-12 21:10:30 +0000253 def testEnumTypesByName(self):
254 file_type = unittest_pb2.DESCRIPTOR
255 self.assertEqual(
256 unittest_pb2._FOREIGNENUM,
257 file_type.enum_types_by_name[unittest_pb2._FOREIGNENUM.name])
258
259 def testExtensionsByName(self):
260 file_type = unittest_pb2.DESCRIPTOR
261 self.assertEqual(
262 unittest_pb2.my_extension_string,
263 file_type.extensions_by_name[unittest_pb2.my_extension_string.name])
264
xiaofeng@google.comb55a20f2012-09-22 02:40:50 +0000265 def testPublicImports(self):
266 # Test public imports as embedded message.
267 all_type_proto = unittest_pb2.TestAllTypes()
268 self.assertEqual(0, all_type_proto.optional_public_import_message.e)
269
270 # PublicImportMessage is actually defined in unittest_import_public_pb2
271 # module, and is public imported by unittest_import_pb2 module.
272 public_import_proto = unittest_import_pb2.PublicImportMessage()
273 self.assertEqual(0, public_import_proto.e)
274 self.assertTrue(unittest_import_public_pb2.PublicImportMessage is
275 unittest_import_pb2.PublicImportMessage)
276
277 def testBadIdentifiers(self):
278 # We're just testing that the code was imported without problems.
279 message = test_bad_identifiers_pb2.TestBadIdentifiers()
280 self.assertEqual(message.Extensions[test_bad_identifiers_pb2.message],
281 "foo")
282 self.assertEqual(message.Extensions[test_bad_identifiers_pb2.descriptor],
283 "bar")
284 self.assertEqual(message.Extensions[test_bad_identifiers_pb2.reflection],
285 "baz")
286 self.assertEqual(message.Extensions[test_bad_identifiers_pb2.service],
287 "qux")
temporal40ee5512008-07-10 02:12:20 +0000288
jieluo@google.combde4a322014-08-12 21:10:30 +0000289 def testOneof(self):
290 desc = unittest_pb2.TestAllTypes.DESCRIPTOR
291 self.assertEqual(1, len(desc.oneofs))
292 self.assertEqual('oneof_field', desc.oneofs[0].name)
293 self.assertEqual(0, desc.oneofs[0].index)
294 self.assertIs(desc, desc.oneofs[0].containing_type)
295 self.assertIs(desc.oneofs[0], desc.oneofs_by_name['oneof_field'])
296 nested_names = set(['oneof_uint32', 'oneof_nested_message',
297 'oneof_string', 'oneof_bytes'])
Dan O'Reillyd06adbd2015-08-14 16:16:00 -0400298 self.assertEqual(
jieluo@google.combde4a322014-08-12 21:10:30 +0000299 nested_names,
Dan O'Reillyd06adbd2015-08-14 16:16:00 -0400300 set([field.name for field in desc.oneofs[0].fields]))
Tres Seaverf336d4b2015-01-13 14:21:29 -0500301 for field_name, field_desc in desc.fields_by_name.items():
jieluo@google.combde4a322014-08-12 21:10:30 +0000302 if field_name in nested_names:
303 self.assertIs(desc.oneofs[0], field_desc.containing_oneof)
304 else:
305 self.assertIsNone(field_desc.containing_oneof)
306
307
Tamir Duberstein9f42f5f2015-01-13 14:47:32 -0500308class SymbolDatabaseRegistrationTest(unittest.TestCase):
jieluo@google.combde4a322014-08-12 21:10:30 +0000309 """Checks that messages, enums and files are correctly registered."""
310
311 def testGetSymbol(self):
Tres Seavera2abc942015-01-13 15:47:55 -0500312 self.assertEqual(
jieluo@google.combde4a322014-08-12 21:10:30 +0000313 unittest_pb2.TestAllTypes, symbol_database.Default().GetSymbol(
314 'protobuf_unittest.TestAllTypes'))
Tres Seavera2abc942015-01-13 15:47:55 -0500315 self.assertEqual(
jieluo@google.combde4a322014-08-12 21:10:30 +0000316 unittest_pb2.TestAllTypes.NestedMessage,
317 symbol_database.Default().GetSymbol(
318 'protobuf_unittest.TestAllTypes.NestedMessage'))
319 with self.assertRaises(KeyError):
320 symbol_database.Default().GetSymbol('protobuf_unittest.NestedMessage')
Tres Seavera2abc942015-01-13 15:47:55 -0500321 self.assertEqual(
jieluo@google.combde4a322014-08-12 21:10:30 +0000322 unittest_pb2.TestAllTypes.OptionalGroup,
323 symbol_database.Default().GetSymbol(
324 'protobuf_unittest.TestAllTypes.OptionalGroup'))
Tres Seavera2abc942015-01-13 15:47:55 -0500325 self.assertEqual(
jieluo@google.combde4a322014-08-12 21:10:30 +0000326 unittest_pb2.TestAllTypes.RepeatedGroup,
327 symbol_database.Default().GetSymbol(
328 'protobuf_unittest.TestAllTypes.RepeatedGroup'))
329
330 def testEnums(self):
Tres Seavera2abc942015-01-13 15:47:55 -0500331 self.assertEqual(
jieluo@google.combde4a322014-08-12 21:10:30 +0000332 'protobuf_unittest.ForeignEnum',
333 symbol_database.Default().pool.FindEnumTypeByName(
334 'protobuf_unittest.ForeignEnum').full_name)
Tres Seavera2abc942015-01-13 15:47:55 -0500335 self.assertEqual(
jieluo@google.combde4a322014-08-12 21:10:30 +0000336 'protobuf_unittest.TestAllTypes.NestedEnum',
337 symbol_database.Default().pool.FindEnumTypeByName(
338 'protobuf_unittest.TestAllTypes.NestedEnum').full_name)
339
340 def testFindFileByName(self):
Tres Seavera2abc942015-01-13 15:47:55 -0500341 self.assertEqual(
jieluo@google.combde4a322014-08-12 21:10:30 +0000342 'google/protobuf/unittest.proto',
343 symbol_database.Default().pool.FindFileByName(
344 'google/protobuf/unittest.proto').name)
345
temporal40ee5512008-07-10 02:12:20 +0000346if __name__ == '__main__':
Tamir Duberstein9f42f5f2015-01-13 14:47:32 -0500347 unittest.main()