PageRenderTime 56ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/thirdparty/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/reflection_test.py

http://github.com/tomahawk-player/tomahawk
Python | 1590 lines | 1519 code | 6 blank | 65 comment | 0 complexity | f6a12b3dfbdfb99bf9f89eaad6a8c3f9 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, GPL-3.0, GPL-2.0
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Protocol Buffers - Google's data interchange format
  5. # Copyright 2008 Google Inc. All rights reserved.
  6. # http://code.google.com/p/protobuf/
  7. #
  8. # Redistribution and use in source and binary forms, with or without
  9. # modification, are permitted provided that the following conditions are
  10. # met:
  11. #
  12. # * Redistributions of source code must retain the above copyright
  13. # notice, this list of conditions and the following disclaimer.
  14. # * Redistributions in binary form must reproduce the above
  15. # copyright notice, this list of conditions and the following disclaimer
  16. # in the documentation and/or other materials provided with the
  17. # distribution.
  18. # * Neither the name of Google Inc. nor the names of its
  19. # contributors may be used to endorse or promote products derived from
  20. # this software without specific prior written permission.
  21. #
  22. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. """Unittest for reflection.py, which also indirectly tests the output of the
  34. pure-Python protocol compiler.
  35. """
  36. __author__ = 'robinson@google.com (Will Robinson)'
  37. import operator
  38. import struct
  39. import unittest
  40. from google.protobuf import unittest_import_pb2
  41. from google.protobuf import unittest_mset_pb2
  42. from google.protobuf import unittest_pb2
  43. from google.protobuf import descriptor_pb2
  44. from google.protobuf import descriptor
  45. from google.protobuf import message
  46. from google.protobuf import reflection
  47. from google.protobuf.internal import api_implementation
  48. from google.protobuf.internal import more_extensions_pb2
  49. from google.protobuf.internal import more_messages_pb2
  50. from google.protobuf.internal import wire_format
  51. from google.protobuf.internal import test_util
  52. from google.protobuf.internal import decoder
  53. class _MiniDecoder(object):
  54. """Decodes a stream of values from a string.
  55. Once upon a time we actually had a class called decoder.Decoder. Then we
  56. got rid of it during a redesign that made decoding much, much faster overall.
  57. But a couple tests in this file used it to check that the serialized form of
  58. a message was correct. So, this class implements just the methods that were
  59. used by said tests, so that we don't have to rewrite the tests.
  60. """
  61. def __init__(self, bytes):
  62. self._bytes = bytes
  63. self._pos = 0
  64. def ReadVarint(self):
  65. result, self._pos = decoder._DecodeVarint(self._bytes, self._pos)
  66. return result
  67. ReadInt32 = ReadVarint
  68. ReadInt64 = ReadVarint
  69. ReadUInt32 = ReadVarint
  70. ReadUInt64 = ReadVarint
  71. def ReadSInt64(self):
  72. return wire_format.ZigZagDecode(self.ReadVarint())
  73. ReadSInt32 = ReadSInt64
  74. def ReadFieldNumberAndWireType(self):
  75. return wire_format.UnpackTag(self.ReadVarint())
  76. def ReadFloat(self):
  77. result = struct.unpack("<f", self._bytes[self._pos:self._pos+4])[0]
  78. self._pos += 4
  79. return result
  80. def ReadDouble(self):
  81. result = struct.unpack("<d", self._bytes[self._pos:self._pos+8])[0]
  82. self._pos += 8
  83. return result
  84. def EndOfStream(self):
  85. return self._pos == len(self._bytes)
  86. class ReflectionTest(unittest.TestCase):
  87. def assertListsEqual(self, values, others):
  88. self.assertEqual(len(values), len(others))
  89. for i in range(len(values)):
  90. self.assertEqual(values[i], others[i])
  91. def testScalarConstructor(self):
  92. # Constructor with only scalar types should succeed.
  93. proto = unittest_pb2.TestAllTypes(
  94. optional_int32=24,
  95. optional_double=54.321,
  96. optional_string='optional_string')
  97. self.assertEqual(24, proto.optional_int32)
  98. self.assertEqual(54.321, proto.optional_double)
  99. self.assertEqual('optional_string', proto.optional_string)
  100. def testRepeatedScalarConstructor(self):
  101. # Constructor with only repeated scalar types should succeed.
  102. proto = unittest_pb2.TestAllTypes(
  103. repeated_int32=[1, 2, 3, 4],
  104. repeated_double=[1.23, 54.321],
  105. repeated_bool=[True, False, False],
  106. repeated_string=["optional_string"])
  107. self.assertEquals([1, 2, 3, 4], list(proto.repeated_int32))
  108. self.assertEquals([1.23, 54.321], list(proto.repeated_double))
  109. self.assertEquals([True, False, False], list(proto.repeated_bool))
  110. self.assertEquals(["optional_string"], list(proto.repeated_string))
  111. def testRepeatedCompositeConstructor(self):
  112. # Constructor with only repeated composite types should succeed.
  113. proto = unittest_pb2.TestAllTypes(
  114. repeated_nested_message=[
  115. unittest_pb2.TestAllTypes.NestedMessage(
  116. bb=unittest_pb2.TestAllTypes.FOO),
  117. unittest_pb2.TestAllTypes.NestedMessage(
  118. bb=unittest_pb2.TestAllTypes.BAR)],
  119. repeated_foreign_message=[
  120. unittest_pb2.ForeignMessage(c=-43),
  121. unittest_pb2.ForeignMessage(c=45324),
  122. unittest_pb2.ForeignMessage(c=12)],
  123. repeatedgroup=[
  124. unittest_pb2.TestAllTypes.RepeatedGroup(),
  125. unittest_pb2.TestAllTypes.RepeatedGroup(a=1),
  126. unittest_pb2.TestAllTypes.RepeatedGroup(a=2)])
  127. self.assertEquals(
  128. [unittest_pb2.TestAllTypes.NestedMessage(
  129. bb=unittest_pb2.TestAllTypes.FOO),
  130. unittest_pb2.TestAllTypes.NestedMessage(
  131. bb=unittest_pb2.TestAllTypes.BAR)],
  132. list(proto.repeated_nested_message))
  133. self.assertEquals(
  134. [unittest_pb2.ForeignMessage(c=-43),
  135. unittest_pb2.ForeignMessage(c=45324),
  136. unittest_pb2.ForeignMessage(c=12)],
  137. list(proto.repeated_foreign_message))
  138. self.assertEquals(
  139. [unittest_pb2.TestAllTypes.RepeatedGroup(),
  140. unittest_pb2.TestAllTypes.RepeatedGroup(a=1),
  141. unittest_pb2.TestAllTypes.RepeatedGroup(a=2)],
  142. list(proto.repeatedgroup))
  143. def testMixedConstructor(self):
  144. # Constructor with only mixed types should succeed.
  145. proto = unittest_pb2.TestAllTypes(
  146. optional_int32=24,
  147. optional_string='optional_string',
  148. repeated_double=[1.23, 54.321],
  149. repeated_bool=[True, False, False],
  150. repeated_nested_message=[
  151. unittest_pb2.TestAllTypes.NestedMessage(
  152. bb=unittest_pb2.TestAllTypes.FOO),
  153. unittest_pb2.TestAllTypes.NestedMessage(
  154. bb=unittest_pb2.TestAllTypes.BAR)],
  155. repeated_foreign_message=[
  156. unittest_pb2.ForeignMessage(c=-43),
  157. unittest_pb2.ForeignMessage(c=45324),
  158. unittest_pb2.ForeignMessage(c=12)])
  159. self.assertEqual(24, proto.optional_int32)
  160. self.assertEqual('optional_string', proto.optional_string)
  161. self.assertEquals([1.23, 54.321], list(proto.repeated_double))
  162. self.assertEquals([True, False, False], list(proto.repeated_bool))
  163. self.assertEquals(
  164. [unittest_pb2.TestAllTypes.NestedMessage(
  165. bb=unittest_pb2.TestAllTypes.FOO),
  166. unittest_pb2.TestAllTypes.NestedMessage(
  167. bb=unittest_pb2.TestAllTypes.BAR)],
  168. list(proto.repeated_nested_message))
  169. self.assertEquals(
  170. [unittest_pb2.ForeignMessage(c=-43),
  171. unittest_pb2.ForeignMessage(c=45324),
  172. unittest_pb2.ForeignMessage(c=12)],
  173. list(proto.repeated_foreign_message))
  174. def testConstructorTypeError(self):
  175. self.assertRaises(
  176. TypeError, unittest_pb2.TestAllTypes, optional_int32="foo")
  177. self.assertRaises(
  178. TypeError, unittest_pb2.TestAllTypes, optional_string=1234)
  179. self.assertRaises(
  180. TypeError, unittest_pb2.TestAllTypes, optional_nested_message=1234)
  181. self.assertRaises(
  182. TypeError, unittest_pb2.TestAllTypes, repeated_int32=1234)
  183. self.assertRaises(
  184. TypeError, unittest_pb2.TestAllTypes, repeated_int32=["foo"])
  185. self.assertRaises(
  186. TypeError, unittest_pb2.TestAllTypes, repeated_string=1234)
  187. self.assertRaises(
  188. TypeError, unittest_pb2.TestAllTypes, repeated_string=[1234])
  189. self.assertRaises(
  190. TypeError, unittest_pb2.TestAllTypes, repeated_nested_message=1234)
  191. self.assertRaises(
  192. TypeError, unittest_pb2.TestAllTypes, repeated_nested_message=[1234])
  193. def testConstructorInvalidatesCachedByteSize(self):
  194. message = unittest_pb2.TestAllTypes(optional_int32 = 12)
  195. self.assertEquals(2, message.ByteSize())
  196. message = unittest_pb2.TestAllTypes(
  197. optional_nested_message = unittest_pb2.TestAllTypes.NestedMessage())
  198. self.assertEquals(3, message.ByteSize())
  199. message = unittest_pb2.TestAllTypes(repeated_int32 = [12])
  200. self.assertEquals(3, message.ByteSize())
  201. message = unittest_pb2.TestAllTypes(
  202. repeated_nested_message = [unittest_pb2.TestAllTypes.NestedMessage()])
  203. self.assertEquals(3, message.ByteSize())
  204. def testSimpleHasBits(self):
  205. # Test a scalar.
  206. proto = unittest_pb2.TestAllTypes()
  207. self.assertTrue(not proto.HasField('optional_int32'))
  208. self.assertEqual(0, proto.optional_int32)
  209. # HasField() shouldn't be true if all we've done is
  210. # read the default value.
  211. self.assertTrue(not proto.HasField('optional_int32'))
  212. proto.optional_int32 = 1
  213. # Setting a value however *should* set the "has" bit.
  214. self.assertTrue(proto.HasField('optional_int32'))
  215. proto.ClearField('optional_int32')
  216. # And clearing that value should unset the "has" bit.
  217. self.assertTrue(not proto.HasField('optional_int32'))
  218. def testHasBitsWithSinglyNestedScalar(self):
  219. # Helper used to test foreign messages and groups.
  220. #
  221. # composite_field_name should be the name of a non-repeated
  222. # composite (i.e., foreign or group) field in TestAllTypes,
  223. # and scalar_field_name should be the name of an integer-valued
  224. # scalar field within that composite.
  225. #
  226. # I never thought I'd miss C++ macros and templates so much. :(
  227. # This helper is semantically just:
  228. #
  229. # assert proto.composite_field.scalar_field == 0
  230. # assert not proto.composite_field.HasField('scalar_field')
  231. # assert not proto.HasField('composite_field')
  232. #
  233. # proto.composite_field.scalar_field = 10
  234. # old_composite_field = proto.composite_field
  235. #
  236. # assert proto.composite_field.scalar_field == 10
  237. # assert proto.composite_field.HasField('scalar_field')
  238. # assert proto.HasField('composite_field')
  239. #
  240. # proto.ClearField('composite_field')
  241. #
  242. # assert not proto.composite_field.HasField('scalar_field')
  243. # assert not proto.HasField('composite_field')
  244. # assert proto.composite_field.scalar_field == 0
  245. #
  246. # # Now ensure that ClearField('composite_field') disconnected
  247. # # the old field object from the object tree...
  248. # assert old_composite_field is not proto.composite_field
  249. # old_composite_field.scalar_field = 20
  250. # assert not proto.composite_field.HasField('scalar_field')
  251. # assert not proto.HasField('composite_field')
  252. def TestCompositeHasBits(composite_field_name, scalar_field_name):
  253. proto = unittest_pb2.TestAllTypes()
  254. # First, check that we can get the scalar value, and see that it's the
  255. # default (0), but that proto.HasField('omposite') and
  256. # proto.composite.HasField('scalar') will still return False.
  257. composite_field = getattr(proto, composite_field_name)
  258. original_scalar_value = getattr(composite_field, scalar_field_name)
  259. self.assertEqual(0, original_scalar_value)
  260. # Assert that the composite object does not "have" the scalar.
  261. self.assertTrue(not composite_field.HasField(scalar_field_name))
  262. # Assert that proto does not "have" the composite field.
  263. self.assertTrue(not proto.HasField(composite_field_name))
  264. # Now set the scalar within the composite field. Ensure that the setting
  265. # is reflected, and that proto.HasField('composite') and
  266. # proto.composite.HasField('scalar') now both return True.
  267. new_val = 20
  268. setattr(composite_field, scalar_field_name, new_val)
  269. self.assertEqual(new_val, getattr(composite_field, scalar_field_name))
  270. # Hold on to a reference to the current composite_field object.
  271. old_composite_field = composite_field
  272. # Assert that the has methods now return true.
  273. self.assertTrue(composite_field.HasField(scalar_field_name))
  274. self.assertTrue(proto.HasField(composite_field_name))
  275. # Now call the clear method...
  276. proto.ClearField(composite_field_name)
  277. # ...and ensure that the "has" bits are all back to False...
  278. composite_field = getattr(proto, composite_field_name)
  279. self.assertTrue(not composite_field.HasField(scalar_field_name))
  280. self.assertTrue(not proto.HasField(composite_field_name))
  281. # ...and ensure that the scalar field has returned to its default.
  282. self.assertEqual(0, getattr(composite_field, scalar_field_name))
  283. # Finally, ensure that modifications to the old composite field object
  284. # don't have any effect on the parent. Possible only with the pure-python
  285. # implementation of the API.
  286. #
  287. # (NOTE that when we clear the composite field in the parent, we actually
  288. # don't recursively clear down the tree. Instead, we just disconnect the
  289. # cleared composite from the tree.)
  290. if api_implementation.Type() != 'python':
  291. return
  292. self.assertTrue(old_composite_field is not composite_field)
  293. setattr(old_composite_field, scalar_field_name, new_val)
  294. self.assertTrue(not composite_field.HasField(scalar_field_name))
  295. self.assertTrue(not proto.HasField(composite_field_name))
  296. self.assertEqual(0, getattr(composite_field, scalar_field_name))
  297. # Test simple, single-level nesting when we set a scalar.
  298. TestCompositeHasBits('optionalgroup', 'a')
  299. TestCompositeHasBits('optional_nested_message', 'bb')
  300. TestCompositeHasBits('optional_foreign_message', 'c')
  301. TestCompositeHasBits('optional_import_message', 'd')
  302. def testReferencesToNestedMessage(self):
  303. proto = unittest_pb2.TestAllTypes()
  304. nested = proto.optional_nested_message
  305. del proto
  306. # A previous version had a bug where this would raise an exception when
  307. # hitting a now-dead weak reference.
  308. nested.bb = 23
  309. def testDisconnectingNestedMessageBeforeSettingField(self):
  310. if api_implementation.Type() != 'python':
  311. return
  312. proto = unittest_pb2.TestAllTypes()
  313. nested = proto.optional_nested_message
  314. proto.ClearField('optional_nested_message') # Should disconnect from parent
  315. self.assertTrue(nested is not proto.optional_nested_message)
  316. nested.bb = 23
  317. self.assertTrue(not proto.HasField('optional_nested_message'))
  318. self.assertEqual(0, proto.optional_nested_message.bb)
  319. def testHasBitsWhenModifyingRepeatedFields(self):
  320. # Test nesting when we add an element to a repeated field in a submessage.
  321. proto = unittest_pb2.TestNestedMessageHasBits()
  322. proto.optional_nested_message.nestedmessage_repeated_int32.append(5)
  323. self.assertEqual(
  324. [5], proto.optional_nested_message.nestedmessage_repeated_int32)
  325. self.assertTrue(proto.HasField('optional_nested_message'))
  326. # Do the same test, but with a repeated composite field within the
  327. # submessage.
  328. proto.ClearField('optional_nested_message')
  329. self.assertTrue(not proto.HasField('optional_nested_message'))
  330. proto.optional_nested_message.nestedmessage_repeated_foreignmessage.add()
  331. self.assertTrue(proto.HasField('optional_nested_message'))
  332. def testHasBitsForManyLevelsOfNesting(self):
  333. # Test nesting many levels deep.
  334. recursive_proto = unittest_pb2.TestMutualRecursionA()
  335. self.assertTrue(not recursive_proto.HasField('bb'))
  336. self.assertEqual(0, recursive_proto.bb.a.bb.a.bb.optional_int32)
  337. self.assertTrue(not recursive_proto.HasField('bb'))
  338. recursive_proto.bb.a.bb.a.bb.optional_int32 = 5
  339. self.assertEqual(5, recursive_proto.bb.a.bb.a.bb.optional_int32)
  340. self.assertTrue(recursive_proto.HasField('bb'))
  341. self.assertTrue(recursive_proto.bb.HasField('a'))
  342. self.assertTrue(recursive_proto.bb.a.HasField('bb'))
  343. self.assertTrue(recursive_proto.bb.a.bb.HasField('a'))
  344. self.assertTrue(recursive_proto.bb.a.bb.a.HasField('bb'))
  345. self.assertTrue(not recursive_proto.bb.a.bb.a.bb.HasField('a'))
  346. self.assertTrue(recursive_proto.bb.a.bb.a.bb.HasField('optional_int32'))
  347. def testSingularListFields(self):
  348. proto = unittest_pb2.TestAllTypes()
  349. proto.optional_fixed32 = 1
  350. proto.optional_int32 = 5
  351. proto.optional_string = 'foo'
  352. # Access sub-message but don't set it yet.
  353. nested_message = proto.optional_nested_message
  354. self.assertEqual(
  355. [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 5),
  356. (proto.DESCRIPTOR.fields_by_name['optional_fixed32'], 1),
  357. (proto.DESCRIPTOR.fields_by_name['optional_string' ], 'foo') ],
  358. proto.ListFields())
  359. proto.optional_nested_message.bb = 123
  360. self.assertEqual(
  361. [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 5),
  362. (proto.DESCRIPTOR.fields_by_name['optional_fixed32'], 1),
  363. (proto.DESCRIPTOR.fields_by_name['optional_string' ], 'foo'),
  364. (proto.DESCRIPTOR.fields_by_name['optional_nested_message' ],
  365. nested_message) ],
  366. proto.ListFields())
  367. def testRepeatedListFields(self):
  368. proto = unittest_pb2.TestAllTypes()
  369. proto.repeated_fixed32.append(1)
  370. proto.repeated_int32.append(5)
  371. proto.repeated_int32.append(11)
  372. proto.repeated_string.extend(['foo', 'bar'])
  373. proto.repeated_string.extend([])
  374. proto.repeated_string.append('baz')
  375. proto.repeated_string.extend(str(x) for x in xrange(2))
  376. proto.optional_int32 = 21
  377. proto.repeated_bool # Access but don't set anything; should not be listed.
  378. self.assertEqual(
  379. [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 21),
  380. (proto.DESCRIPTOR.fields_by_name['repeated_int32' ], [5, 11]),
  381. (proto.DESCRIPTOR.fields_by_name['repeated_fixed32'], [1]),
  382. (proto.DESCRIPTOR.fields_by_name['repeated_string' ],
  383. ['foo', 'bar', 'baz', '0', '1']) ],
  384. proto.ListFields())
  385. def testSingularListExtensions(self):
  386. proto = unittest_pb2.TestAllExtensions()
  387. proto.Extensions[unittest_pb2.optional_fixed32_extension] = 1
  388. proto.Extensions[unittest_pb2.optional_int32_extension ] = 5
  389. proto.Extensions[unittest_pb2.optional_string_extension ] = 'foo'
  390. self.assertEqual(
  391. [ (unittest_pb2.optional_int32_extension , 5),
  392. (unittest_pb2.optional_fixed32_extension, 1),
  393. (unittest_pb2.optional_string_extension , 'foo') ],
  394. proto.ListFields())
  395. def testRepeatedListExtensions(self):
  396. proto = unittest_pb2.TestAllExtensions()
  397. proto.Extensions[unittest_pb2.repeated_fixed32_extension].append(1)
  398. proto.Extensions[unittest_pb2.repeated_int32_extension ].append(5)
  399. proto.Extensions[unittest_pb2.repeated_int32_extension ].append(11)
  400. proto.Extensions[unittest_pb2.repeated_string_extension ].append('foo')
  401. proto.Extensions[unittest_pb2.repeated_string_extension ].append('bar')
  402. proto.Extensions[unittest_pb2.repeated_string_extension ].append('baz')
  403. proto.Extensions[unittest_pb2.optional_int32_extension ] = 21
  404. self.assertEqual(
  405. [ (unittest_pb2.optional_int32_extension , 21),
  406. (unittest_pb2.repeated_int32_extension , [5, 11]),
  407. (unittest_pb2.repeated_fixed32_extension, [1]),
  408. (unittest_pb2.repeated_string_extension , ['foo', 'bar', 'baz']) ],
  409. proto.ListFields())
  410. def testListFieldsAndExtensions(self):
  411. proto = unittest_pb2.TestFieldOrderings()
  412. test_util.SetAllFieldsAndExtensions(proto)
  413. unittest_pb2.my_extension_int
  414. self.assertEqual(
  415. [ (proto.DESCRIPTOR.fields_by_name['my_int' ], 1),
  416. (unittest_pb2.my_extension_int , 23),
  417. (proto.DESCRIPTOR.fields_by_name['my_string'], 'foo'),
  418. (unittest_pb2.my_extension_string , 'bar'),
  419. (proto.DESCRIPTOR.fields_by_name['my_float' ], 1.0) ],
  420. proto.ListFields())
  421. def testDefaultValues(self):
  422. proto = unittest_pb2.TestAllTypes()
  423. self.assertEqual(0, proto.optional_int32)
  424. self.assertEqual(0, proto.optional_int64)
  425. self.assertEqual(0, proto.optional_uint32)
  426. self.assertEqual(0, proto.optional_uint64)
  427. self.assertEqual(0, proto.optional_sint32)
  428. self.assertEqual(0, proto.optional_sint64)
  429. self.assertEqual(0, proto.optional_fixed32)
  430. self.assertEqual(0, proto.optional_fixed64)
  431. self.assertEqual(0, proto.optional_sfixed32)
  432. self.assertEqual(0, proto.optional_sfixed64)
  433. self.assertEqual(0.0, proto.optional_float)
  434. self.assertEqual(0.0, proto.optional_double)
  435. self.assertEqual(False, proto.optional_bool)
  436. self.assertEqual('', proto.optional_string)
  437. self.assertEqual('', proto.optional_bytes)
  438. self.assertEqual(41, proto.default_int32)
  439. self.assertEqual(42, proto.default_int64)
  440. self.assertEqual(43, proto.default_uint32)
  441. self.assertEqual(44, proto.default_uint64)
  442. self.assertEqual(-45, proto.default_sint32)
  443. self.assertEqual(46, proto.default_sint64)
  444. self.assertEqual(47, proto.default_fixed32)
  445. self.assertEqual(48, proto.default_fixed64)
  446. self.assertEqual(49, proto.default_sfixed32)
  447. self.assertEqual(-50, proto.default_sfixed64)
  448. self.assertEqual(51.5, proto.default_float)
  449. self.assertEqual(52e3, proto.default_double)
  450. self.assertEqual(True, proto.default_bool)
  451. self.assertEqual('hello', proto.default_string)
  452. self.assertEqual('world', proto.default_bytes)
  453. self.assertEqual(unittest_pb2.TestAllTypes.BAR, proto.default_nested_enum)
  454. self.assertEqual(unittest_pb2.FOREIGN_BAR, proto.default_foreign_enum)
  455. self.assertEqual(unittest_import_pb2.IMPORT_BAR,
  456. proto.default_import_enum)
  457. proto = unittest_pb2.TestExtremeDefaultValues()
  458. self.assertEqual(u'\u1234', proto.utf8_string)
  459. def testHasFieldWithUnknownFieldName(self):
  460. proto = unittest_pb2.TestAllTypes()
  461. self.assertRaises(ValueError, proto.HasField, 'nonexistent_field')
  462. def testClearFieldWithUnknownFieldName(self):
  463. proto = unittest_pb2.TestAllTypes()
  464. self.assertRaises(ValueError, proto.ClearField, 'nonexistent_field')
  465. def testDisallowedAssignments(self):
  466. # It's illegal to assign values directly to repeated fields
  467. # or to nonrepeated composite fields. Ensure that this fails.
  468. proto = unittest_pb2.TestAllTypes()
  469. # Repeated fields.
  470. self.assertRaises(AttributeError, setattr, proto, 'repeated_int32', 10)
  471. # Lists shouldn't work, either.
  472. self.assertRaises(AttributeError, setattr, proto, 'repeated_int32', [10])
  473. # Composite fields.
  474. self.assertRaises(AttributeError, setattr, proto,
  475. 'optional_nested_message', 23)
  476. # Assignment to a repeated nested message field without specifying
  477. # the index in the array of nested messages.
  478. self.assertRaises(AttributeError, setattr, proto.repeated_nested_message,
  479. 'bb', 34)
  480. # Assignment to an attribute of a repeated field.
  481. self.assertRaises(AttributeError, setattr, proto.repeated_float,
  482. 'some_attribute', 34)
  483. # proto.nonexistent_field = 23 should fail as well.
  484. self.assertRaises(AttributeError, setattr, proto, 'nonexistent_field', 23)
  485. def testSingleScalarTypeSafety(self):
  486. proto = unittest_pb2.TestAllTypes()
  487. self.assertRaises(TypeError, setattr, proto, 'optional_int32', 1.1)
  488. self.assertRaises(TypeError, setattr, proto, 'optional_int32', 'foo')
  489. self.assertRaises(TypeError, setattr, proto, 'optional_string', 10)
  490. self.assertRaises(TypeError, setattr, proto, 'optional_bytes', 10)
  491. def testSingleScalarBoundsChecking(self):
  492. def TestMinAndMaxIntegers(field_name, expected_min, expected_max):
  493. pb = unittest_pb2.TestAllTypes()
  494. setattr(pb, field_name, expected_min)
  495. self.assertEqual(expected_min, getattr(pb, field_name))
  496. setattr(pb, field_name, expected_max)
  497. self.assertEqual(expected_max, getattr(pb, field_name))
  498. self.assertRaises(ValueError, setattr, pb, field_name, expected_min - 1)
  499. self.assertRaises(ValueError, setattr, pb, field_name, expected_max + 1)
  500. TestMinAndMaxIntegers('optional_int32', -(1 << 31), (1 << 31) - 1)
  501. TestMinAndMaxIntegers('optional_uint32', 0, 0xffffffff)
  502. TestMinAndMaxIntegers('optional_int64', -(1 << 63), (1 << 63) - 1)
  503. TestMinAndMaxIntegers('optional_uint64', 0, 0xffffffffffffffff)
  504. pb = unittest_pb2.TestAllTypes()
  505. pb.optional_nested_enum = 1
  506. self.assertEqual(1, pb.optional_nested_enum)
  507. # Invalid enum values.
  508. pb.optional_nested_enum = 0
  509. self.assertEqual(0, pb.optional_nested_enum)
  510. bytes_size_before = pb.ByteSize()
  511. pb.optional_nested_enum = 4
  512. self.assertEqual(4, pb.optional_nested_enum)
  513. pb.optional_nested_enum = 0
  514. self.assertEqual(0, pb.optional_nested_enum)
  515. # Make sure that setting the same enum field doesn't just add unknown
  516. # fields (but overwrites them).
  517. self.assertEqual(bytes_size_before, pb.ByteSize())
  518. # Is the invalid value preserved after serialization?
  519. serialized = pb.SerializeToString()
  520. pb2 = unittest_pb2.TestAllTypes()
  521. pb2.ParseFromString(serialized)
  522. self.assertEqual(0, pb2.optional_nested_enum)
  523. self.assertEqual(pb, pb2)
  524. def testRepeatedScalarTypeSafety(self):
  525. proto = unittest_pb2.TestAllTypes()
  526. self.assertRaises(TypeError, proto.repeated_int32.append, 1.1)
  527. self.assertRaises(TypeError, proto.repeated_int32.append, 'foo')
  528. self.assertRaises(TypeError, proto.repeated_string, 10)
  529. self.assertRaises(TypeError, proto.repeated_bytes, 10)
  530. proto.repeated_int32.append(10)
  531. proto.repeated_int32[0] = 23
  532. self.assertRaises(IndexError, proto.repeated_int32.__setitem__, 500, 23)
  533. self.assertRaises(TypeError, proto.repeated_int32.__setitem__, 0, 'abc')
  534. # Repeated enums tests.
  535. #proto.repeated_nested_enum.append(0)
  536. def testSingleScalarGettersAndSetters(self):
  537. proto = unittest_pb2.TestAllTypes()
  538. self.assertEqual(0, proto.optional_int32)
  539. proto.optional_int32 = 1
  540. self.assertEqual(1, proto.optional_int32)
  541. proto.optional_uint64 = 0xffffffffffff
  542. self.assertEqual(0xffffffffffff, proto.optional_uint64)
  543. proto.optional_uint64 = 0xffffffffffffffff
  544. self.assertEqual(0xffffffffffffffff, proto.optional_uint64)
  545. # TODO(robinson): Test all other scalar field types.
  546. def testSingleScalarClearField(self):
  547. proto = unittest_pb2.TestAllTypes()
  548. # Should be allowed to clear something that's not there (a no-op).
  549. proto.ClearField('optional_int32')
  550. proto.optional_int32 = 1
  551. self.assertTrue(proto.HasField('optional_int32'))
  552. proto.ClearField('optional_int32')
  553. self.assertEqual(0, proto.optional_int32)
  554. self.assertTrue(not proto.HasField('optional_int32'))
  555. # TODO(robinson): Test all other scalar field types.
  556. def testEnums(self):
  557. proto = unittest_pb2.TestAllTypes()
  558. self.assertEqual(1, proto.FOO)
  559. self.assertEqual(1, unittest_pb2.TestAllTypes.FOO)
  560. self.assertEqual(2, proto.BAR)
  561. self.assertEqual(2, unittest_pb2.TestAllTypes.BAR)
  562. self.assertEqual(3, proto.BAZ)
  563. self.assertEqual(3, unittest_pb2.TestAllTypes.BAZ)
  564. def testRepeatedScalars(self):
  565. proto = unittest_pb2.TestAllTypes()
  566. self.assertTrue(not proto.repeated_int32)
  567. self.assertEqual(0, len(proto.repeated_int32))
  568. proto.repeated_int32.append(5)
  569. proto.repeated_int32.append(10)
  570. proto.repeated_int32.append(15)
  571. self.assertTrue(proto.repeated_int32)
  572. self.assertEqual(3, len(proto.repeated_int32))
  573. self.assertEqual([5, 10, 15], proto.repeated_int32)
  574. # Test single retrieval.
  575. self.assertEqual(5, proto.repeated_int32[0])
  576. self.assertEqual(15, proto.repeated_int32[-1])
  577. # Test out-of-bounds indices.
  578. self.assertRaises(IndexError, proto.repeated_int32.__getitem__, 1234)
  579. self.assertRaises(IndexError, proto.repeated_int32.__getitem__, -1234)
  580. # Test incorrect types passed to __getitem__.
  581. self.assertRaises(TypeError, proto.repeated_int32.__getitem__, 'foo')
  582. self.assertRaises(TypeError, proto.repeated_int32.__getitem__, None)
  583. # Test single assignment.
  584. proto.repeated_int32[1] = 20
  585. self.assertEqual([5, 20, 15], proto.repeated_int32)
  586. # Test insertion.
  587. proto.repeated_int32.insert(1, 25)
  588. self.assertEqual([5, 25, 20, 15], proto.repeated_int32)
  589. # Test slice retrieval.
  590. proto.repeated_int32.append(30)
  591. self.assertEqual([25, 20, 15], proto.repeated_int32[1:4])
  592. self.assertEqual([5, 25, 20, 15, 30], proto.repeated_int32[:])
  593. # Test slice assignment with an iterator
  594. proto.repeated_int32[1:4] = (i for i in xrange(3))
  595. self.assertEqual([5, 0, 1, 2, 30], proto.repeated_int32)
  596. # Test slice assignment.
  597. proto.repeated_int32[1:4] = [35, 40, 45]
  598. self.assertEqual([5, 35, 40, 45, 30], proto.repeated_int32)
  599. # Test that we can use the field as an iterator.
  600. result = []
  601. for i in proto.repeated_int32:
  602. result.append(i)
  603. self.assertEqual([5, 35, 40, 45, 30], result)
  604. # Test single deletion.
  605. del proto.repeated_int32[2]
  606. self.assertEqual([5, 35, 45, 30], proto.repeated_int32)
  607. # Test slice deletion.
  608. del proto.repeated_int32[2:]
  609. self.assertEqual([5, 35], proto.repeated_int32)
  610. # Test extending.
  611. proto.repeated_int32.extend([3, 13])
  612. self.assertEqual([5, 35, 3, 13], proto.repeated_int32)
  613. # Test clearing.
  614. proto.ClearField('repeated_int32')
  615. self.assertTrue(not proto.repeated_int32)
  616. self.assertEqual(0, len(proto.repeated_int32))
  617. proto.repeated_int32.append(1)
  618. self.assertEqual(1, proto.repeated_int32[-1])
  619. # Test assignment to a negative index.
  620. proto.repeated_int32[-1] = 2
  621. self.assertEqual(2, proto.repeated_int32[-1])
  622. # Test deletion at negative indices.
  623. proto.repeated_int32[:] = [0, 1, 2, 3]
  624. del proto.repeated_int32[-1]
  625. self.assertEqual([0, 1, 2], proto.repeated_int32)
  626. del proto.repeated_int32[-2]
  627. self.assertEqual([0, 2], proto.repeated_int32)
  628. self.assertRaises(IndexError, proto.repeated_int32.__delitem__, -3)
  629. self.assertRaises(IndexError, proto.repeated_int32.__delitem__, 300)
  630. del proto.repeated_int32[-2:-1]
  631. self.assertEqual([2], proto.repeated_int32)
  632. del proto.repeated_int32[100:10000]
  633. self.assertEqual([2], proto.repeated_int32)
  634. def testRepeatedScalarsRemove(self):
  635. proto = unittest_pb2.TestAllTypes()
  636. self.assertTrue(not proto.repeated_int32)
  637. self.assertEqual(0, len(proto.repeated_int32))
  638. proto.repeated_int32.append(5)
  639. proto.repeated_int32.append(10)
  640. proto.repeated_int32.append(5)
  641. proto.repeated_int32.append(5)
  642. self.assertEqual(4, len(proto.repeated_int32))
  643. proto.repeated_int32.remove(5)
  644. self.assertEqual(3, len(proto.repeated_int32))
  645. self.assertEqual(10, proto.repeated_int32[0])
  646. self.assertEqual(5, proto.repeated_int32[1])
  647. self.assertEqual(5, proto.repeated_int32[2])
  648. proto.repeated_int32.remove(5)
  649. self.assertEqual(2, len(proto.repeated_int32))
  650. self.assertEqual(10, proto.repeated_int32[0])
  651. self.assertEqual(5, proto.repeated_int32[1])
  652. proto.repeated_int32.remove(10)
  653. self.assertEqual(1, len(proto.repeated_int32))
  654. self.assertEqual(5, proto.repeated_int32[0])
  655. # Remove a non-existent element.
  656. self.assertRaises(ValueError, proto.repeated_int32.remove, 123)
  657. def testRepeatedComposites(self):
  658. proto = unittest_pb2.TestAllTypes()
  659. self.assertTrue(not proto.repeated_nested_message)
  660. self.assertEqual(0, len(proto.repeated_nested_message))
  661. m0 = proto.repeated_nested_message.add()
  662. m1 = proto.repeated_nested_message.add()
  663. self.assertTrue(proto.repeated_nested_message)
  664. self.assertEqual(2, len(proto.repeated_nested_message))
  665. self.assertListsEqual([m0, m1], proto.repeated_nested_message)
  666. self.assertTrue(isinstance(m0, unittest_pb2.TestAllTypes.NestedMessage))
  667. # Test out-of-bounds indices.
  668. self.assertRaises(IndexError, proto.repeated_nested_message.__getitem__,
  669. 1234)
  670. self.assertRaises(IndexError, proto.repeated_nested_message.__getitem__,
  671. -1234)
  672. # Test incorrect types passed to __getitem__.
  673. self.assertRaises(TypeError, proto.repeated_nested_message.__getitem__,
  674. 'foo')
  675. self.assertRaises(TypeError, proto.repeated_nested_message.__getitem__,
  676. None)
  677. # Test slice retrieval.
  678. m2 = proto.repeated_nested_message.add()
  679. m3 = proto.repeated_nested_message.add()
  680. m4 = proto.repeated_nested_message.add()
  681. self.assertListsEqual(
  682. [m1, m2, m3], proto.repeated_nested_message[1:4])
  683. self.assertListsEqual(
  684. [m0, m1, m2, m3, m4], proto.repeated_nested_message[:])
  685. self.assertListsEqual(
  686. [m0, m1], proto.repeated_nested_message[:2])
  687. self.assertListsEqual(
  688. [m2, m3, m4], proto.repeated_nested_message[2:])
  689. self.assertEqual(
  690. m0, proto.repeated_nested_message[0])
  691. self.assertListsEqual(
  692. [m0], proto.repeated_nested_message[:1])
  693. # Test that we can use the field as an iterator.
  694. result = []
  695. for i in proto.repeated_nested_message:
  696. result.append(i)
  697. self.assertListsEqual([m0, m1, m2, m3, m4], result)
  698. # Test single deletion.
  699. del proto.repeated_nested_message[2]
  700. self.assertListsEqual([m0, m1, m3, m4], proto.repeated_nested_message)
  701. # Test slice deletion.
  702. del proto.repeated_nested_message[2:]
  703. self.assertListsEqual([m0, m1], proto.repeated_nested_message)
  704. # Test extending.
  705. n1 = unittest_pb2.TestAllTypes.NestedMessage(bb=1)
  706. n2 = unittest_pb2.TestAllTypes.NestedMessage(bb=2)
  707. proto.repeated_nested_message.extend([n1,n2])
  708. self.assertEqual(4, len(proto.repeated_nested_message))
  709. self.assertEqual(n1, proto.repeated_nested_message[2])
  710. self.assertEqual(n2, proto.repeated_nested_message[3])
  711. # Test clearing.
  712. proto.ClearField('repeated_nested_message')
  713. self.assertTrue(not proto.repeated_nested_message)
  714. self.assertEqual(0, len(proto.repeated_nested_message))
  715. # Test constructing an element while adding it.
  716. proto.repeated_nested_message.add(bb=23)
  717. self.assertEqual(1, len(proto.repeated_nested_message))
  718. self.assertEqual(23, proto.repeated_nested_message[0].bb)
  719. def testHandWrittenReflection(self):
  720. # Hand written extensions are only supported by the pure-Python
  721. # implementation of the API.
  722. if api_implementation.Type() != 'python':
  723. return
  724. FieldDescriptor = descriptor.FieldDescriptor
  725. foo_field_descriptor = FieldDescriptor(
  726. name='foo_field', full_name='MyProto.foo_field',
  727. index=0, number=1, type=FieldDescriptor.TYPE_INT64,
  728. cpp_type=FieldDescriptor.CPPTYPE_INT64,
  729. label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
  730. containing_type=None, message_type=None, enum_type=None,
  731. is_extension=False, extension_scope=None,
  732. options=descriptor_pb2.FieldOptions())
  733. mydescriptor = descriptor.Descriptor(
  734. name='MyProto', full_name='MyProto', filename='ignored',
  735. containing_type=None, nested_types=[], enum_types=[],
  736. fields=[foo_field_descriptor], extensions=[],
  737. options=descriptor_pb2.MessageOptions())
  738. class MyProtoClass(message.Message):
  739. DESCRIPTOR = mydescriptor
  740. __metaclass__ = reflection.GeneratedProtocolMessageType
  741. myproto_instance = MyProtoClass()
  742. self.assertEqual(0, myproto_instance.foo_field)
  743. self.assertTrue(not myproto_instance.HasField('foo_field'))
  744. myproto_instance.foo_field = 23
  745. self.assertEqual(23, myproto_instance.foo_field)
  746. self.assertTrue(myproto_instance.HasField('foo_field'))
  747. def testTopLevelExtensionsForOptionalScalar(self):
  748. extendee_proto = unittest_pb2.TestAllExtensions()
  749. extension = unittest_pb2.optional_int32_extension
  750. self.assertTrue(not extendee_proto.HasExtension(extension))
  751. self.assertEqual(0, extendee_proto.Extensions[extension])
  752. # As with normal scalar fields, just doing a read doesn't actually set the
  753. # "has" bit.
  754. self.assertTrue(not extendee_proto.HasExtension(extension))
  755. # Actually set the thing.
  756. extendee_proto.Extensions[extension] = 23
  757. self.assertEqual(23, extendee_proto.Extensions[extension])
  758. self.assertTrue(extendee_proto.HasExtension(extension))
  759. # Ensure that clearing works as well.
  760. extendee_proto.ClearExtension(extension)
  761. self.assertEqual(0, extendee_proto.Extensions[extension])
  762. self.assertTrue(not extendee_proto.HasExtension(extension))
  763. def testTopLevelExtensionsForRepeatedScalar(self):
  764. extendee_proto = unittest_pb2.TestAllExtensions()
  765. extension = unittest_pb2.repeated_string_extension
  766. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  767. extendee_proto.Extensions[extension].append('foo')
  768. self.assertEqual(['foo'], extendee_proto.Extensions[extension])
  769. string_list = extendee_proto.Extensions[extension]
  770. extendee_proto.ClearExtension(extension)
  771. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  772. self.assertTrue(string_list is not extendee_proto.Extensions[extension])
  773. # Shouldn't be allowed to do Extensions[extension] = 'a'
  774. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  775. extension, 'a')
  776. def testTopLevelExtensionsForOptionalMessage(self):
  777. extendee_proto = unittest_pb2.TestAllExtensions()
  778. extension = unittest_pb2.optional_foreign_message_extension
  779. self.assertTrue(not extendee_proto.HasExtension(extension))
  780. self.assertEqual(0, extendee_proto.Extensions[extension].c)
  781. # As with normal (non-extension) fields, merely reading from the
  782. # thing shouldn't set the "has" bit.
  783. self.assertTrue(not extendee_proto.HasExtension(extension))
  784. extendee_proto.Extensions[extension].c = 23
  785. self.assertEqual(23, extendee_proto.Extensions[extension].c)
  786. self.assertTrue(extendee_proto.HasExtension(extension))
  787. # Save a reference here.
  788. foreign_message = extendee_proto.Extensions[extension]
  789. extendee_proto.ClearExtension(extension)
  790. self.assertTrue(foreign_message is not extendee_proto.Extensions[extension])
  791. # Setting a field on foreign_message now shouldn't set
  792. # any "has" bits on extendee_proto.
  793. foreign_message.c = 42
  794. self.assertEqual(42, foreign_message.c)
  795. self.assertTrue(foreign_message.HasField('c'))
  796. self.assertTrue(not extendee_proto.HasExtension(extension))
  797. # Shouldn't be allowed to do Extensions[extension] = 'a'
  798. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  799. extension, 'a')
  800. def testTopLevelExtensionsForRepeatedMessage(self):
  801. extendee_proto = unittest_pb2.TestAllExtensions()
  802. extension = unittest_pb2.repeatedgroup_extension
  803. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  804. group = extendee_proto.Extensions[extension].add()
  805. group.a = 23
  806. self.assertEqual(23, extendee_proto.Extensions[extension][0].a)
  807. group.a = 42
  808. self.assertEqual(42, extendee_proto.Extensions[extension][0].a)
  809. group_list = extendee_proto.Extensions[extension]
  810. extendee_proto.ClearExtension(extension)
  811. self.assertEqual(0, len(extendee_proto.Extensions[extension]))
  812. self.assertTrue(group_list is not extendee_proto.Extensions[extension])
  813. # Shouldn't be allowed to do Extensions[extension] = 'a'
  814. self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions,
  815. extension, 'a')
  816. def testNestedExtensions(self):
  817. extendee_proto = unittest_pb2.TestAllExtensions()
  818. extension = unittest_pb2.TestRequired.single
  819. # We just test the non-repeated case.
  820. self.assertTrue(not extendee_proto.HasExtension(extension))
  821. required = extendee_proto.Extensions[extension]
  822. self.assertEqual(0, required.a)
  823. self.assertTrue(not extendee_proto.HasExtension(extension))
  824. required.a = 23
  825. self.assertEqual(23, extendee_proto.Extensions[extension].a)
  826. self.assertTrue(extendee_proto.HasExtension(extension))
  827. extendee_proto.ClearExtension(extension)
  828. self.assertTrue(required is not extendee_proto.Extensions[extension])
  829. self.assertTrue(not extendee_proto.HasExtension(extension))
  830. # If message A directly contains message B, and
  831. # a.HasField('b') is currently False, then mutating any
  832. # extension in B should change a.HasField('b') to True
  833. # (and so on up the object tree).
  834. def testHasBitsForAncestorsOfExtendedMessage(self):
  835. # Optional scalar extension.
  836. toplevel = more_extensions_pb2.TopLevelMessage()
  837. self.assertTrue(not toplevel.HasField('submessage'))
  838. self.assertEqual(0, toplevel.submessage.Extensions[
  839. more_extensions_pb2.optional_int_extension])
  840. self.assertTrue(not toplevel.HasField('submessage'))
  841. toplevel.submessage.Extensions[
  842. more_extensions_pb2.optional_int_extension] = 23
  843. self.assertEqual(23, toplevel.submessage.Extensions[
  844. more_extensions_pb2.optional_int_extension])
  845. self.assertTrue(toplevel.HasField('submessage'))
  846. # Repeated scalar extension.
  847. toplevel = more_extensions_pb2.TopLevelMessage()
  848. self.assertTrue(not toplevel.HasField('submessage'))
  849. self.assertEqual([], toplevel.submessage.Extensions[
  850. more_extensions_pb2.repeated_int_extension])
  851. self.assertTrue(not toplevel.HasField('submessage'))
  852. toplevel.submessage.Extensions[
  853. more_extensions_pb2.repeated_int_extension].append(23)
  854. self.assertEqual([23], toplevel.submessage.Extensions[
  855. more_extensions_pb2.repeated_int_extension])
  856. self.assertTrue(toplevel.HasField('submessage'))
  857. # Optional message extension.
  858. toplevel = more_extensions_pb2.TopLevelMessage()
  859. self.assertTrue(not toplevel.HasField('submessage'))
  860. self.assertEqual(0, toplevel.submessage.Extensions[
  861. more_extensions_pb2.optional_message_extension].foreign_message_int)
  862. self.assertTrue(not toplevel.HasField('submessage'))
  863. toplevel.submessage.Extensions[
  864. more_extensions_pb2.optional_message_extension].foreign_message_int = 23
  865. self.assertEqual(23, toplevel.submessage.Extensions[
  866. more_extensions_pb2.optional_message_extension].foreign_message_int)
  867. self.assertTrue(toplevel.HasField('submessage'))
  868. # Repeated message extension.
  869. toplevel = more_extensions_pb2.TopLevelMessage()
  870. self.assertTrue(not toplevel.HasField('submessage'))
  871. self.assertEqual(0, len(toplevel.submessage.Extensions[
  872. more_extensions_pb2.repeated_message_extension]))
  873. self.assertTrue(not toplevel.HasField('submessage'))
  874. foreign = toplevel.submessage.Extensions[
  875. more_extensions_pb2.repeated_message_extension].add()
  876. self.assertEqual(foreign, toplevel.submessage.Extensions[
  877. more_extensions_pb2.repeated_message_extension][0])
  878. self.assertTrue(toplevel.HasField('submessage'))
  879. def testDisconnectionAfterClearingEmptyMessage(self):
  880. toplevel = more_extensions_pb2.TopLevelMessage()
  881. extendee_proto = toplevel.submessage
  882. extension = more_extensions_pb2.optional_message_extension
  883. extension_proto = extendee_proto.Extensions[extension]
  884. extendee_proto.ClearExtension(extension)
  885. extension_proto.foreign_message_int = 23
  886. self.assertTrue(extension_proto is not extendee_proto.Extensions[extension])
  887. def testExtensionFailureModes(self):
  888. extendee_proto = unittest_pb2.TestAllExtensions()
  889. # Try non-extension-handle arguments to HasExtension,
  890. # ClearExtension(), and Extensions[]...
  891. self.assertRaises(KeyError, extendee_proto.HasExtension, 1234)
  892. self.assertRaises(KeyError, extendee_proto.ClearExtension, 1234)
  893. self.assertRaises(KeyError, extendee_proto.Extensions.__getitem__, 1234)
  894. self.assertRaises(KeyError, extendee_proto.Extensions.__setitem__, 1234, 5)
  895. # Try something that *is* an extension handle, just not for
  896. # this message...
  897. unknown_handle = more_extensions_pb2.optional_int_extension
  898. self.assertRaises(KeyError, extendee_proto.HasExtension,
  899. unknown_handle)
  900. self.assertRaises(KeyError, extendee_proto.ClearExtension,
  901. unknown_handle)
  902. self.assertRaises(KeyError, extendee_proto.Extensions.__getitem__,
  903. unknown_handle)
  904. self.assertRaises(KeyError, extendee_proto.Extensions.__setitem__,
  905. unknown_handle, 5)
  906. # Try call HasExtension() with a valid handle, but for a
  907. # *repeated* field. (Just as with non-extension repeated
  908. # fields, Has*() isn't supported for extension repeated fields).
  909. self.assertRaises(KeyError, extendee_proto.HasExtension,
  910. unittest_pb2.repeated_string_extension)
  911. def testStaticParseFrom(self):
  912. proto1 = unittest_pb2.TestAllTypes()
  913. test_util.SetAllFields(proto1)
  914. string1 = proto1.SerializeToString()
  915. proto2 = unittest_pb2.TestAllTypes.FromString(string1)
  916. # Messages should be equal.
  917. self.assertEqual(proto2, proto1)
  918. def testMergeFromSingularField(self):
  919. # Test merge with just a singular field.
  920. proto1 = unittest_pb2.TestAllTypes()
  921. proto1.optional_int32 = 1
  922. proto2 = unittest_pb2.TestAllTypes()
  923. # This shouldn't get overwritten.
  924. proto2.optional_string = 'value'
  925. proto2.MergeFrom(proto1)
  926. self.assertEqual(1, proto2.optional_int32)
  927. self.assertEqual('value', proto2.optional_string)
  928. def testMergeFromRepeatedField(self):
  929. # Test merge with just a repeated field.
  930. proto1 = unittest_pb2.TestAllTypes()
  931. proto1.repeated_int32.append(1)
  932. proto1.repeated_int32.append(2)
  933. proto2 = unittest_pb2.TestAllTypes()
  934. proto2.repeated_int32.append(0)
  935. proto2.MergeFrom(proto1)
  936. self.assertEqual(0, proto2.repeated_int32[0])
  937. self.assertEqual(1, proto2.repeated_int32[1])
  938. self.assertEqual(2, proto2.repeated_int32[2])
  939. def testMergeFromOptionalGroup(self):
  940. # Test merge with an optional group.
  941. proto1 = unittest_pb2.TestAllTypes()
  942. proto1.optionalgroup.a = 12
  943. proto2 = unittest_pb2.TestAllTypes()
  944. proto2.MergeFrom(proto1)
  945. self.assertEqual(12, proto2.optionalgroup.a)
  946. def testMergeFromRepeatedNestedMessage(self):
  947. # Test merge with a repeated nested message.
  948. proto1 = unittest_pb2.TestAllTypes()
  949. m = proto1.repeated_nested_message.add()
  950. m.bb = 123
  951. m = proto1.repeated_nested_message.add()
  952. m.bb = 321
  953. proto2 = unittest_pb2.TestAllTypes()
  954. m = proto2.repeated_nested_message.add()
  955. m.bb = 999
  956. proto2.MergeFrom(proto1)
  957. self.assertEqual(999, proto2.repeated_nested_message[0].bb)
  958. self.assertEqual(123, proto2.repeated_nested_message[1].bb)
  959. self.assertEqual(321, proto2.repeated_nested_message[2].bb)
  960. proto3 = unittest_pb2.TestAllTypes()
  961. proto3.repeated_nested_message.MergeFrom(proto2.repeated_nested_message)
  962. self.assertEqual(999, proto3.repeated_nested_message[0].bb)
  963. self.assertEqual(123, proto3.repeated_nested_message[1].bb)
  964. self.assertEqual(321, proto3.repeated_nested_message[2].bb)
  965. def testMergeFromAllFields(self):
  966. # With all fields set.
  967. proto1 = unittest_pb2.TestAllTypes()
  968. test_util.SetAllFields(proto1)
  969. proto2 = unittest_pb2.TestAllTypes()
  970. proto2.MergeFrom(proto1)
  971. # Messages should be equal.
  972. self.assertEqual(proto2, proto1)
  973. # Serialized string should be equal too.
  974. string1 = proto1.SerializeToString()
  975. string2 = proto2.SerializeToString()
  976. self.assertEqual(string1, string2)
  977. def testMergeFromExtensionsSingular(self):
  978. proto1 = unittest_pb2.TestAllExtensions()
  979. proto1.Extensions[unittest_pb2.optional_int32_extension] = 1
  980. proto2 = unittest_pb2.TestAllExtensions()
  981. proto2.MergeFrom(proto1)
  982. self.assertEqual(
  983. 1, proto2.Extensions[unittest_pb2.optional_int32_extension])
  984. def testMergeFromExtensionsRepeated(self):
  985. proto1 = unittest_pb2.TestAllExtensions()
  986. proto1.Extensions[unittest_pb2.repeated_int32_extension].append(1)
  987. proto1.Extensions[unittest_pb2.repeated_int32_extension].append(2)
  988. proto2 = unittest_pb2.TestAllExtensions()
  989. proto2.Extensions[unittest_pb2.repeated_int32_extension].append(0)
  990. proto2.MergeFrom(proto1)
  991. self.assertEqual(
  992. 3, len(proto2.Extensions[unittest_pb2.repeated_int32_extension]))
  993. self.assertEqual(
  994. 0, proto2.Extensions[unittest_pb2.repeated_int32_extension][0])
  995. self.assertEqual(
  996. 1, proto2.Extensions[unittest_pb2.repeated_int32_extension][1])
  997. self.assertEqual(
  998. 2, proto2.Extensions[unittest_pb2.repeated_int32_extension][2])
  999. def testMergeFromExtensionsNestedMessage(self):
  1000. proto1 = unittest_pb2.TestAllExtensions()
  1001. ext1 = proto1.Extensions[
  1002. unittest_pb2.repeated_nested_message_extension]
  1003. m = ext1.add()
  1004. m.bb = 222
  1005. m = ext1.add()
  1006. m.bb = 333
  1007. proto2 = unittest_pb2.TestAllExtensions()
  1008. ext2 = proto2.Extensions[
  1009. unittest_pb2.repeated_nested_message_extension]
  1010. m = ext2.add()
  1011. m.bb = 111
  1012. proto2.MergeFrom(proto1)
  1013. ext2 = proto2.Extensions[
  1014. unittest_pb2.repeated_nested_message_extension]
  1015. self.assertEqual(3, len(ext2))
  1016. self.assertEqual(111, ext2[0].bb)
  1017. self.assertEqual(222, ext2[1].bb)
  1018. self.assertEqual(333, ext2[2].bb)
  1019. def testMergeFromBug(self):
  1020. message1 = unittest_pb2.TestAllTypes()
  1021. message2 = unittest_pb2.TestAllTypes()
  1022. # Cause optional_nested_message to be instantiated within message1, even
  1023. # though it is not considered to be "present".
  1024. message1.optional_nested_message
  1025. self.assertFalse(message1.HasField('optional_nested_message'))
  1026. # Merge into message2. This should not instantiate the field is message2.
  1027. message2.MergeFrom(message1)
  1028. self.assertFalse(message2.HasField('optional_nested_message'))
  1029. def testCopyFromSingularField(self):
  1030. # Test copy with just a singular field.
  1031. proto1 = unittest_pb2.TestAllTypes()
  1032. proto1.optional_int32 = 1
  1033. proto1.optional_string = 'important-text'
  1034. proto2 = unittest_pb2.TestAllTypes()
  1035. proto2.optional_string = 'value'
  1036. proto2.CopyFrom(proto1)
  1037. self.assertEqual(1, proto2.optional_int32)
  1038. self.assertEqual('important-text', proto2.optional_string)
  1039. def testCopyFromRepeatedField(self):
  1040. # Test copy with a repeated field.
  1041. proto1 = unittest_pb2.TestAllTypes()
  1042. proto1.repeated_int32.append(1)
  1043. proto1.repeated_int32.append(2)
  1044. proto2 = unittest_pb2.TestAllTypes()
  1045. proto2.repeated_int32.append(0)
  1046. proto2.CopyFrom(proto1)
  1047. self.assertEqual(1, proto2.repeated_int32[0])
  1048. self.assertEqual(2, proto2.repeated_int32[1])
  1049. def testCopyFromAllFields(self):
  1050. # With all fields set.
  1051. proto1 = unittest_pb2.TestAllTypes()
  1052. test_util.SetAllFields(proto1)
  1053. proto2 = unittest_pb2.TestAllTypes()
  1054. proto2.CopyFrom(proto1)
  1055. # Messages should be equal.
  1056. self.assertEqual(proto2, proto1)
  1057. # Serialized string should be equal too.
  1058. string1 = proto1.SerializeToString()
  1059. string2 = proto2.SerializeToString()
  1060. self.assertEqual(string1, string2)
  1061. def testCopyFromSelf(self):
  1062. proto1 = unittest_pb2.TestAllTypes()
  1063. proto1.repeated_int32.append(1)
  1064. proto1.optional_int32 = 2
  1065. proto1.optional_string = 'important-text'
  1066. proto1.CopyFrom(proto1)
  1067. self.assertEqual(1, proto1.repeated_int32[0])
  1068. self.assertEqual(2, proto1.optional_int32)
  1069. self.assertEqual('important-text', proto1.optional_string)
  1070. def testCopyFromBadType(self):
  1071. # The python implementation doesn't raise an exception in this
  1072. # case. In theory it should.
  1073. if api_implementation.Type() == 'python':
  1074. return
  1075. proto1 = unittest_pb2.TestAllTypes()
  1076. proto2 = unittest_pb2.TestAllExtensions()
  1077. self.assertRaises(TypeError, proto1.CopyFrom, proto2)
  1078. def testClear(self):
  1079. proto = unittest_pb2.TestAllTypes()
  1080. test_util.SetAllFields(proto)
  1081. # Clear the message.
  1082. proto.Clear()
  1083. self.assertEquals(proto.ByteSize(), 0)
  1084. empty_proto = unittest_pb2.TestAllTypes()
  1085. self.assertEquals(proto, empty_proto)
  1086. # Test if extensions which were set are cleared.
  1087. proto = unittest_pb2.TestAllExtensions()
  1088. test_util.SetAllExtensions(proto)
  1089. # Clear the message.
  1090. proto.Clear()
  1091. self.assertEquals(proto.ByteSize(), 0)
  1092. empty_proto = unittest_pb2.TestAllExtensions()
  1093. self.assertEquals(proto, empty_proto)
  1094. def assertInitialized(self, proto):
  1095. self.assertTrue(proto.IsInitialized())
  1096. # Neither method should raise an exception.
  1097. proto.SerializeToString()
  1098. proto.SerializePartialToString()
  1099. def assertNotInitialized(self, proto):
  1100. self.assertFalse(proto.IsInitialized())
  1101. self.assertRaises(message.EncodeError, proto.SerializeToString)
  1102. # "Partial" serialization doesn't care if message is uninitialized.
  1103. proto.SerializePartialToString()
  1104. def testIsInitialized(self):
  1105. # Trivial cases - all optional fields and extensions.
  1106. proto = unittest_pb2.TestAllTypes()
  1107. self.assertInitialized(proto)
  1108. proto = unittest_pb2.TestAllExtensions()
  1109. self.assertInitialized(proto)
  1110. # The case of uninitialized required fields.
  1111. proto = unittest_pb2.TestRequired()
  1112. self.assertNotInitialized(proto)
  1113. proto.a = proto.b = proto.c = 2
  1114. self.assertInitialized(proto)
  1115. # The case of uninitialized submessage.
  1116. proto = unittest_pb2.TestRequiredForeign()
  1117. self.assertInitialized(proto)
  1118. proto.optional_message.a = 1
  1119. self.assertNotInitialized(proto)
  1120. proto.optional_message.b = 0
  1121. proto.optional_message.c = 0
  1122. self.assertInitialized(proto)
  1123. # Uninitialized repeated submessage.
  1124. message1 = proto.repeated_message.add()
  1125. self.assertNotInitialized(proto)
  1126. message1.a = message1.b = message1.c = 0
  1127. self.assertInitialized(proto)
  1128. # Uninitialized repeated group in an extension.
  1129. proto = unittest_pb2.TestAllExtensions()
  1130. extension = unittest_pb2.TestRequired.multi
  1131. message1 = proto.Extensions[extension].add()
  1132. message2 = proto.Extensions[extension].add()
  1133. self.assertNotInitialized(proto)
  1134. message1.a = 1
  1135. message1.b = 1
  1136. message1.c = 1
  1137. self.assertNotInitialized(proto)
  1138. message2.a = 2
  1139. message2.b = 2
  1140. message2.c = 2
  1141. self.assertInitialized(proto)
  1142. # Uninitialized nonrepeated message in an extension.
  1143. proto = unittest_pb2.TestAllExtensions()
  1144. extension = unittest_pb2.TestRequired.single
  1145. proto.Extensions[extension].a = 1
  1146. self.assertNotInitialized(proto)
  1147. proto.Extensions[extension].b = 2
  1148. proto.Extensions[extension].c = 3
  1149. self.assertInitialized(proto)
  1150. # Try passing an errors list.
  1151. errors = []
  1152. proto = unittest_pb2.TestRequired()
  1153. self.assertFalse(proto.IsInitialized(errors))
  1154. self.assertEqual(errors, ['a', 'b', 'c'])
  1155. def testStringUTF8Encoding(self):
  1156. proto = unittest_pb2.TestAllTypes()
  1157. # Assignment of a unicode object to a field of type 'bytes' is not allowed.
  1158. self.assertRaises(TypeError,
  1159. setattr, proto, 'optional_bytes', u'unicode object')
  1160. # Check that the default value is of python's 'unicode' type.
  1161. self.assertEqual(type(proto.optional_string), unicode)
  1162. proto.optional_string = unicode('Testing')
  1163. self.assertEqual(proto.optional_string, str('Testing'))
  1164. # Assign a value of type 'str' which can be encoded in UTF-8.
  1165. proto.optional_string = str('Testing')
  1166. self.assertEqual(proto.optional_string, unicode('Testing'))
  1167. if api_implementation.Type() == 'python':
  1168. # Values of type 'str' are also accepted as long as they can be
  1169. # encoded in UTF-8.
  1170. self.assertEqual(type(proto.optional_string), str)
  1171. # Try to assign a 'str' value which contains bytes that aren't 7-bit ASCII.
  1172. self.assertRaises(ValueError,
  1173. setattr, proto, 'optional_string', str('a\x80a'))
  1174. # Assign a 'str' object which contains a UTF-8 encoded string.
  1175. self.assertRaises(ValueError,
  1176. setattr, proto, 'optional_string', '????')
  1177. # No exception thrown.
  1178. proto.optional_string = 'abc'
  1179. def testStringUTF8Serialization(self):
  1180. proto = unittest_mset_pb2.TestMessageSet()
  1181. extension_message = unittest_mset_pb2.TestMessageSetExtension2
  1182. extension = extension_message.message_set_extension
  1183. test_utf8 = u'????'
  1184. test_utf8_bytes = test_utf8.encode('utf-8')
  1185. # 'Test' in another language, using UTF-8 charset.
  1186. proto.Extensions[extension].str = test_utf8
  1187. # Serialize using the MessageSet wire format (this is specified in the
  1188. # .proto file).
  1189. serialized = proto.SerializeToString()
  1190. # Check byte size.
  1191. self.assertEqual(proto.ByteSize(), len(serialized))
  1192. raw = unittest_mset_pb2.RawMessageSet()
  1193. raw.MergeFromString(serialized)
  1194. message2 = unittest_mset_pb2.TestMessageSetExtension2()
  1195. self.assertEqual(1, len(raw.item))
  1196. # Check that the type_id is the same as the tag ID in the .proto file.
  1197. self.assertEqual(raw.item[0].type_id, 1547769)
  1198. # Check the actual bytes on the wire.
  1199. self.assertTrue(
  1200. raw.item[0].message.endswith(test_utf8_bytes))
  1201. message2.MergeFromString(raw.item[0].message)
  1202. self.assertEqual(type(message2.str), unicode)
  1203. self.assertEqual(message2.str, test_utf8)
  1204. # The pure Python API throws an exception on MergeFromString(),
  1205. # if any of the string fields of the message can't be UTF-8 decoded.
  1206. # The C++ implementation of the API has no way to check that on
  1207. # MergeFromString and thus has no way to throw the exception.
  1208. #
  1209. # The pure Python API always returns objects of type 'unicode' (UTF-8
  1210. # encoded), or 'str' (in 7 bit ASCII).
  1211. bytes = raw.item[0].message.replace(
  1212. test_utf8_bytes, len(test_utf8_bytes) * '\xff')
  1213. unicode_decode_failed = False
  1214. try:
  1215. message2.MergeFromString(bytes)
  1216. except UnicodeDecodeError, e:
  1217. unicode_decode_failed = True
  1218. string_field = message2.str
  1219. self.assertTrue(unicode_decode_failed or type(string_field) == str)
  1220. def testEmptyNestedMessage(self):
  1221. proto = unittest_pb2.TestAllTypes()
  1222. proto.optional_nested_message.MergeFrom(
  1223. unittest_pb2.TestAllTypes.NestedMessage())
  1224. self.assertTrue(proto.HasField('optional_nested_message'))
  1225. proto = unittest_pb2.TestAllTypes()
  1226. proto.optional_nested_message.CopyFrom(
  1227. unittest_pb2.TestAllTypes.NestedMessage())
  1228. self.assertTrue(proto.HasField('optional_nested_message'))
  1229. proto = unittest_pb2.TestAllTypes()
  1230. proto.optional_nested_message.MergeFromString('')
  1231. self.assertTrue(proto.HasField('optional_nested_message'))
  1232. proto = unittest_pb2.TestAllTypes()
  1233. proto.optional_nested_message.ParseFromString('')
  1234. self.assertTrue(proto.HasField('optional_nested_message'))
  1235. serialized = proto.SerializeToString()
  1236. proto2 = unittest_pb2.TestAllTypes()
  1237. proto2.MergeFromString(serialized)
  1238. self.assertTrue(proto2.HasField('optional_nested_message'))
  1239. def testSetInParent(self):
  1240. proto = unittest_pb2.TestAllTypes()
  1241. self.assertFalse(proto.HasField('optionalgroup'))
  1242. proto.optionalgroup.SetInParent()
  1243. self.assertTrue(proto.HasField('optionalgroup'))
  1244. # Since we had so many tests for protocol buffer equality, we broke these out
  1245. # into separate TestCase classes.
  1246. class TestAllTypesEqualityTest(unittest.TestCase):
  1247. def setUp(self):
  1248. self.first_proto = unittest_pb2.TestAllTypes()
  1249. self.second_proto = unittest_pb2.TestAllTypes()
  1250. def testNotHashable(self):
  1251. self.assertRaises(TypeError, hash, self.first_proto)
  1252. def testSelfEquality(self):
  1253. self.assertEqual(self.first_proto, self.first_proto)
  1254. def testEmptyProtosEqual(self):
  1255. self.assertEqual(self.first_proto, self.second_proto)
  1256. class FullProtosEqualityTest(unittest.TestCase):
  1257. """Equality tests using completely-full protos as a starting point."""
  1258. def setUp(self):
  1259. self.first_proto = unittest_pb2.TestAllTypes()
  1260. self.second_proto = unittest_pb2.TestAllTypes()
  1261. test_util.SetAllFields(self.first_proto)
  1262. test_util.SetAllFields(self.second_proto)
  1263. def testNotHashable(self):
  1264. self.assertRaises(TypeError, hash, self.first_proto)
  1265. def testNoneNotEqual(self):
  1266. self.assertNotEqual(self.first_proto, None)
  1267. self.assertNotEqual(None, self.second_proto)
  1268. def testNotEqualToOtherMessage(self):
  1269. third_proto = unittest_pb2.TestRequired()
  1270. self.assertNotEqual(self.first_proto, third_proto)
  1271. self.assertNotEqual(third_proto, self.second_proto)
  1272. def testAllFieldsFilledEquality(self):
  1273. self.assertEqual(self.first_proto, self.second_proto)
  1274. def testNonRepeatedScalar(self):
  1275. # Nonrepeated scalar field change should cause inequality.
  1276. self.first_proto.optional_int32 += 1
  1277. self.assertNotEqual(self.first_proto, self.second_proto)
  1278. # ...as should clearing a field.
  1279. self.first_proto.ClearField('optional_int32')
  1280. self.assertNotEqual(self.first_proto, self.second_proto)
  1281. def testNonRepeatedComposite(self):
  1282. # Change a nonrepeated composite field.
  1283. self.first_proto.optional_nested_message.bb += 1
  1284. self.assertNotEqual(self.first_proto, self.second_proto)
  1285. self.first_proto.optional_nested_message.bb -= 1
  1286. self.assertEqual(self.first_proto, self.second_proto)
  1287. # Clear a field in the nested message.
  1288. self.first_proto.optional_nested_message.ClearField('bb')
  1289. self.assertNotEqual(self.first_proto, self.second_proto)
  1290. self.first_proto.optional_nested_message.bb = (
  1291. self.second_proto.optional_nested_message.bb)
  1292. self.assertEqual(self.first_proto, self.second_proto)
  1293. # Remove the nested message entirely.
  1294. self.first_proto.ClearField('optional_nested_message')
  1295. self.assertNotEqual(self.first_proto, self.second_proto)
  1296. def testRepeatedScalar(self):
  1297. # Change a repeated scalar field.
  1298. self.first_proto.repeated_int32.append(5)
  1299. self.assertNotEqual(self.first_proto, self.second_proto)
  1300. self.first_proto.ClearField('repeated_int32')
  1301. self.assertNotEqual(self.first_proto, self.second_proto)
  1302. def testRepeatedComposite(self):
  1303. # Change value within a repeated composite field.
  1304. self.first_proto.repeated_nested_message[0].bb += 1
  1305. self.assertNotEqual(self.first_proto, self.second_proto)
  1306. self.first_proto.repeated_nested_message[0].bb -= 1
  1307. self.assertEqual(self.first_proto, self.second_proto)
  1308. # Add a value to a repeated composite field.
  1309. self.first_proto.repeated_nested_message.add()
  1310. self.assertNotEqual(self.first_proto, self.second_proto)
  1311. self.second_proto.repeated_nested_message.add()
  1312. self.assertEqual(self.first_proto, self.second_proto)
  1313. def testNonRepeatedScalarHasBits(self):
  1314. # Ensure that we test "has" bits as well as value for
  1315. # nonrepeated scalar field.
  1316. self.first_proto.ClearField('optional_int32')
  1317. self.second_proto.optional_int32 = 0
  1318. self.assertNotEqual(self.first_proto, self.second_proto)
  1319. def testNonRepeatedCompositeHasBits(self):
  1320. # Ensure that we test "has" bits as well as value for
  1321. # nonrepeated composite field.
  1322. self.first_proto.ClearField('optional_nested_message')
  1323. self.second_proto.optional_nested_message.ClearField('bb')
  1324. self.assertNotEqual(self.first_proto, self.second_proto)
  1325. self.first_proto.optional_nested_message.bb = 0
  1326. self.first_proto.optional_nested_message.ClearField('bb')
  1327. self.assertEqual(self.first_proto, self.second_proto)
  1328. class ExtensionEqualityTest(unittest.TestCase):
  1329. def testExtensionEquality(self):
  1330. first_proto = unittest_pb2.TestAllExtensions()
  1331. second_proto = unittest_pb2.TestAllExtensions()
  1332. self.assertEqual(first_proto, second_proto)
  1333. test_util.SetAllExtensions(first_proto)
  1334. self.assertNotEqual(first_proto, second_proto)
  1335. test_util.SetAllExtensions(second_proto)
  1336. self.assertEqual(first_proto, second_proto)
  1337. # Ensure that we check value equality.
  1338. first_proto.Extensions[unittest_pb2.optional_int32_extension] += 1
  1339. self.assertNotEqual(first_proto, second_proto)
  1340. first_proto.Extensions[unittest_pb2.optional_int32_extension] -= 1
  1341. self.assertEqual(first_proto, second_proto)
  1342. # Ensure that we also look at "has" bits.
  1343. first_proto.ClearExtension(unittest_pb2.optional_int32_extension)
  1344. second_proto.Extensions[unittest_pb2.optional_int32_extension] = 0
  1345. self.assertNotEqual(first_proto, second_proto)
  1346. first_proto.Extensions[unittest_pb2.optional_int32_extension] = 0
  1347. self.assertEqual(first_proto, second_proto)
  1348. # Ensure that differences in cached values
  1349. # don't matter if "has" bits are both false.
  1350. first_proto = unittest_pb2.TestAllExtensions()
  1351. second_proto = unittest_pb2.TestAllExtensions()
  1352. self.assertEqual(
  1353. 0, first_proto.Extensions[unittest_pb2.optional_int32_extension])
  1354. self.assertEqual(first_proto, second_proto)
  1355. class MutualRecursionEqualityTest(unittest.TestCase):
  1356. def testEqualityWithMutualRecursion(self):
  1357. first_proto = unittest_pb2.TestMutualRecursionA()
  1358. second_proto = unittest_pb2.Tes