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

/thrift-0.8.0/test/py/SerializationTest.py

https://gitlab.com/sudarsunkannan/mapkeeper
Python | 357 lines | 328 code | 9 blank | 20 comment | 0 complexity | 5d461bfad46e94cf45c602704f2bf1b8 MD5 | raw file
  1. #!/usr/bin/env python
  2. #
  3. # Licensed to the Apache Software Foundation (ASF) under one
  4. # or more contributor license agreements. See the NOTICE file
  5. # distributed with this work for additional information
  6. # regarding copyright ownership. The ASF licenses this file
  7. # to you under the Apache License, Version 2.0 (the
  8. # "License"); you may not use this file except in compliance
  9. # with the License. You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing,
  14. # software distributed under the License is distributed on an
  15. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. # KIND, either express or implied. See the License for the
  17. # specific language governing permissions and limitations
  18. # under the License.
  19. #
  20. import sys, glob
  21. from optparse import OptionParser
  22. parser = OptionParser()
  23. parser.add_option('--genpydir', type='string', dest='genpydir', default='gen-py')
  24. options, args = parser.parse_args()
  25. del sys.argv[1:] # clean up hack so unittest doesn't complain
  26. sys.path.insert(0, options.genpydir)
  27. sys.path.insert(0, glob.glob('../../lib/py/build/lib.*')[0])
  28. from ThriftTest.ttypes import *
  29. from DebugProtoTest.ttypes import CompactProtoTestStruct, Empty
  30. from thrift.transport import TTransport
  31. from thrift.transport import TSocket
  32. from thrift.protocol import TBinaryProtocol, TCompactProtocol
  33. from thrift.TSerialization import serialize, deserialize
  34. import unittest
  35. import time
  36. class AbstractTest(unittest.TestCase):
  37. def setUp(self):
  38. self.v1obj = VersioningTestV1(
  39. begin_in_both=12345,
  40. old_string='aaa',
  41. end_in_both=54321,
  42. )
  43. self.v2obj = VersioningTestV2(
  44. begin_in_both=12345,
  45. newint=1,
  46. newbyte=2,
  47. newshort=3,
  48. newlong=4,
  49. newdouble=5.0,
  50. newstruct=Bonk(message="Hello!", type=123),
  51. newlist=[7,8,9],
  52. newset=set([42,1,8]),
  53. newmap={1:2,2:3},
  54. newstring="Hola!",
  55. end_in_both=54321,
  56. )
  57. self.bools = Bools(im_true=True, im_false=False)
  58. self.bools_flipped = Bools(im_true=False, im_false=True)
  59. self.large_deltas = LargeDeltas (
  60. b1=self.bools,
  61. b10=self.bools_flipped,
  62. b100=self.bools,
  63. check_true=True,
  64. b1000=self.bools_flipped,
  65. check_false=False,
  66. vertwo2000=VersioningTestV2(newstruct=Bonk(message='World!', type=314)),
  67. a_set2500=set(['lazy', 'brown', 'cow']),
  68. vertwo3000=VersioningTestV2(newset=set([2, 3, 5, 7, 11])),
  69. big_numbers=[2**8, 2**16, 2**31-1, -(2**31-1)]
  70. )
  71. self.compact_struct = CompactProtoTestStruct(
  72. a_byte = 127,
  73. a_i16=32000,
  74. a_i32=1000000000,
  75. a_i64=0xffffffffff,
  76. a_double=5.6789,
  77. a_string="my string",
  78. true_field=True,
  79. false_field=False,
  80. empty_struct_field=Empty(),
  81. byte_list=[-127, -1, 0, 1, 127],
  82. i16_list=[-1, 0, 1, 0x7fff],
  83. i32_list= [-1, 0, 0xff, 0xffff, 0xffffff, 0x7fffffff],
  84. i64_list=[-1, 0, 0xff, 0xffff, 0xffffff, 0xffffffff, 0xffffffffff, 0xffffffffffff, 0xffffffffffffff, 0x7fffffffffffffff],
  85. double_list=[0.1, 0.2, 0.3],
  86. string_list=["first", "second", "third"],
  87. boolean_list=[True, True, True, False, False, False],
  88. struct_list=[Empty(), Empty()],
  89. byte_set=set([-127, -1, 0, 1, 127]),
  90. i16_set=set([-1, 0, 1, 0x7fff]),
  91. i32_set=set([1, 2, 3]),
  92. i64_set=set([-1, 0, 0xff, 0xffff, 0xffffff, 0xffffffff, 0xffffffffff, 0xffffffffffff, 0xffffffffffffff, 0x7fffffffffffffff]),
  93. double_set=set([0.1, 0.2, 0.3]),
  94. string_set=set(["first", "second", "third"]),
  95. boolean_set=set([True, False]),
  96. #struct_set=set([Empty()]), # unhashable instance
  97. byte_byte_map={1 : 2},
  98. i16_byte_map={1 : 1, -1 : 1, 0x7fff : 1},
  99. i32_byte_map={1 : 1, -1 : 1, 0x7fffffff : 1},
  100. i64_byte_map={0 : 1, 1 : 1, -1 : 1, 0x7fffffffffffffff : 1},
  101. double_byte_map={-1.1 : 1, 1.1 : 1},
  102. string_byte_map={"first" : 1, "second" : 2, "third" : 3, "" : 0},
  103. boolean_byte_map={True : 1, False: 0},
  104. byte_i16_map={1 : 1, 2 : -1, 3 : 0x7fff},
  105. byte_i32_map={1 : 1, 2 : -1, 3 : 0x7fffffff},
  106. byte_i64_map={1 : 1, 2 : -1, 3 : 0x7fffffffffffffff},
  107. byte_double_map={1 : 0.1, 2 : -0.1, 3 : 1000000.1},
  108. byte_string_map={1 : "", 2 : "blah", 3 : "loooooooooooooong string"},
  109. byte_boolean_map={1 : True, 2 : False},
  110. #list_byte_map # unhashable
  111. #set_byte_map={set([1, 2, 3]) : 1, set([0, 1]) : 2, set([]) : 0}, # unhashable
  112. #map_byte_map # unhashable
  113. byte_map_map={0 : {}, 1 : {1 : 1}, 2 : {1 : 1, 2 : 2}},
  114. byte_set_map={0 : set([]), 1 : set([1]), 2 : set([1, 2])},
  115. byte_list_map={0 : [], 1 : [1], 2 : [1, 2]},
  116. )
  117. self.nested_lists_i32x2 = NestedListsI32x2(
  118. [
  119. [ 1, 1, 2 ],
  120. [ 2, 7, 9 ],
  121. [ 3, 5, 8 ]
  122. ]
  123. )
  124. self.nested_lists_i32x3 = NestedListsI32x3(
  125. [
  126. [
  127. [ 2, 7, 9 ],
  128. [ 3, 5, 8 ]
  129. ],
  130. [
  131. [ 1, 1, 2 ],
  132. [ 1, 4, 9 ]
  133. ]
  134. ]
  135. )
  136. self.nested_mixedx2 = NestedMixedx2( int_set_list=[
  137. set([1,2,3]),
  138. set([1,4,9]),
  139. set([1,2,3,5,8,13,21]),
  140. set([-1, 0, 1])
  141. ],
  142. # note, the sets below are sets of chars, since the strings are iterated
  143. map_int_strset={ 10:set('abc'), 20:set('def'), 30:set('GHI') },
  144. map_int_strset_list=[
  145. { 10:set('abc'), 20:set('def'), 30:set('GHI') },
  146. { 100:set('lmn'), 200:set('opq'), 300:set('RST') },
  147. { 1000:set('uvw'), 2000:set('wxy'), 3000:set('XYZ') }
  148. ]
  149. )
  150. self.nested_lists_bonk = NestedListsBonk(
  151. [
  152. [
  153. [
  154. Bonk(message='inner A first', type=1),
  155. Bonk(message='inner A second', type=1)
  156. ],
  157. [
  158. Bonk(message='inner B first', type=2),
  159. Bonk(message='inner B second', type=2)
  160. ]
  161. ]
  162. ]
  163. )
  164. self.list_bonks = ListBonks(
  165. [
  166. Bonk(message='inner A', type=1),
  167. Bonk(message='inner B', type=2),
  168. Bonk(message='inner C', type=0)
  169. ]
  170. )
  171. def _serialize(self, obj):
  172. trans = TTransport.TMemoryBuffer()
  173. prot = self.protocol_factory.getProtocol(trans)
  174. obj.write(prot)
  175. return trans.getvalue()
  176. def _deserialize(self, objtype, data):
  177. prot = self.protocol_factory.getProtocol(TTransport.TMemoryBuffer(data))
  178. ret = objtype()
  179. ret.read(prot)
  180. return ret
  181. def testForwards(self):
  182. obj = self._deserialize(VersioningTestV2, self._serialize(self.v1obj))
  183. self.assertEquals(obj.begin_in_both, self.v1obj.begin_in_both)
  184. self.assertEquals(obj.end_in_both, self.v1obj.end_in_both)
  185. def testBackwards(self):
  186. obj = self._deserialize(VersioningTestV1, self._serialize(self.v2obj))
  187. self.assertEquals(obj.begin_in_both, self.v2obj.begin_in_both)
  188. self.assertEquals(obj.end_in_both, self.v2obj.end_in_both)
  189. def testSerializeV1(self):
  190. obj = self._deserialize(VersioningTestV1, self._serialize(self.v1obj))
  191. self.assertEquals(obj, self.v1obj)
  192. def testSerializeV2(self):
  193. obj = self._deserialize(VersioningTestV2, self._serialize(self.v2obj))
  194. self.assertEquals(obj, self.v2obj)
  195. def testBools(self):
  196. self.assertNotEquals(self.bools, self.bools_flipped)
  197. self.assertNotEquals(self.bools, self.v1obj)
  198. obj = self._deserialize(Bools, self._serialize(self.bools))
  199. self.assertEquals(obj, self.bools)
  200. obj = self._deserialize(Bools, self._serialize(self.bools_flipped))
  201. self.assertEquals(obj, self.bools_flipped)
  202. rep = repr(self.bools)
  203. self.assertTrue(len(rep) > 0)
  204. def testLargeDeltas(self):
  205. # test large field deltas (meaningful in CompactProto only)
  206. obj = self._deserialize(LargeDeltas, self._serialize(self.large_deltas))
  207. self.assertEquals(obj, self.large_deltas)
  208. rep = repr(self.large_deltas)
  209. self.assertTrue(len(rep) > 0)
  210. def testNestedListsI32x2(self):
  211. obj = self._deserialize(NestedListsI32x2, self._serialize(self.nested_lists_i32x2))
  212. self.assertEquals(obj, self.nested_lists_i32x2)
  213. rep = repr(self.nested_lists_i32x2)
  214. self.assertTrue(len(rep) > 0)
  215. def testNestedListsI32x3(self):
  216. obj = self._deserialize(NestedListsI32x3, self._serialize(self.nested_lists_i32x3))
  217. self.assertEquals(obj, self.nested_lists_i32x3)
  218. rep = repr(self.nested_lists_i32x3)
  219. self.assertTrue(len(rep) > 0)
  220. def testNestedMixedx2(self):
  221. obj = self._deserialize(NestedMixedx2, self._serialize(self.nested_mixedx2))
  222. self.assertEquals(obj, self.nested_mixedx2)
  223. rep = repr(self.nested_mixedx2)
  224. self.assertTrue(len(rep) > 0)
  225. def testNestedListsBonk(self):
  226. obj = self._deserialize(NestedListsBonk, self._serialize(self.nested_lists_bonk))
  227. self.assertEquals(obj, self.nested_lists_bonk)
  228. rep = repr(self.nested_lists_bonk)
  229. self.assertTrue(len(rep) > 0)
  230. def testListBonks(self):
  231. obj = self._deserialize(ListBonks, self._serialize(self.list_bonks))
  232. self.assertEquals(obj, self.list_bonks)
  233. rep = repr(self.list_bonks)
  234. self.assertTrue(len(rep) > 0)
  235. def testCompactStruct(self):
  236. # test large field deltas (meaningful in CompactProto only)
  237. obj = self._deserialize(CompactProtoTestStruct, self._serialize(self.compact_struct))
  238. self.assertEquals(obj, self.compact_struct)
  239. rep = repr(self.compact_struct)
  240. self.assertTrue(len(rep) > 0)
  241. class NormalBinaryTest(AbstractTest):
  242. protocol_factory = TBinaryProtocol.TBinaryProtocolFactory()
  243. class AcceleratedBinaryTest(AbstractTest):
  244. protocol_factory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory()
  245. class CompactProtocolTest(AbstractTest):
  246. protocol_factory = TCompactProtocol.TCompactProtocolFactory()
  247. class AcceleratedFramedTest(unittest.TestCase):
  248. def testSplit(self):
  249. """Test FramedTransport and BinaryProtocolAccelerated
  250. Tests that TBinaryProtocolAccelerated and TFramedTransport
  251. play nicely together when a read spans a frame"""
  252. protocol_factory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory()
  253. bigstring = "".join(chr(byte) for byte in range(ord("a"), ord("z")+1))
  254. databuf = TTransport.TMemoryBuffer()
  255. prot = protocol_factory.getProtocol(databuf)
  256. prot.writeI32(42)
  257. prot.writeString(bigstring)
  258. prot.writeI16(24)
  259. data = databuf.getvalue()
  260. cutpoint = len(data)/2
  261. parts = [ data[:cutpoint], data[cutpoint:] ]
  262. framed_buffer = TTransport.TMemoryBuffer()
  263. framed_writer = TTransport.TFramedTransport(framed_buffer)
  264. for part in parts:
  265. framed_writer.write(part)
  266. framed_writer.flush()
  267. self.assertEquals(len(framed_buffer.getvalue()), len(data) + 8)
  268. # Recreate framed_buffer so we can read from it.
  269. framed_buffer = TTransport.TMemoryBuffer(framed_buffer.getvalue())
  270. framed_reader = TTransport.TFramedTransport(framed_buffer)
  271. prot = protocol_factory.getProtocol(framed_reader)
  272. self.assertEqual(prot.readI32(), 42)
  273. self.assertEqual(prot.readString(), bigstring)
  274. self.assertEqual(prot.readI16(), 24)
  275. class SerializersTest(unittest.TestCase):
  276. def testSerializeThenDeserialize(self):
  277. obj = Xtruct2(i32_thing=1,
  278. struct_thing=Xtruct(string_thing="foo"))
  279. s1 = serialize(obj)
  280. for i in range(10):
  281. self.assertEquals(s1, serialize(obj))
  282. objcopy = Xtruct2()
  283. deserialize(objcopy, serialize(obj))
  284. self.assertEquals(obj, objcopy)
  285. obj = Xtruct(string_thing="bar")
  286. objcopy = Xtruct()
  287. deserialize(objcopy, serialize(obj))
  288. self.assertEquals(obj, objcopy)
  289. # test booleans
  290. obj = Bools(im_true=True, im_false=False)
  291. objcopy = Bools()
  292. deserialize(objcopy, serialize(obj))
  293. self.assertEquals(obj, objcopy)
  294. # test enums
  295. for num, name in Numberz._VALUES_TO_NAMES.iteritems():
  296. obj = Bonk(message='enum Numberz value %d is string %s' % (num, name), type=num)
  297. objcopy = Bonk()
  298. deserialize(objcopy, serialize(obj))
  299. self.assertEquals(obj, objcopy)
  300. def suite():
  301. suite = unittest.TestSuite()
  302. loader = unittest.TestLoader()
  303. suite.addTest(loader.loadTestsFromTestCase(NormalBinaryTest))
  304. suite.addTest(loader.loadTestsFromTestCase(AcceleratedBinaryTest))
  305. suite.addTest(loader.loadTestsFromTestCase(CompactProtocolTest))
  306. suite.addTest(loader.loadTestsFromTestCase(AcceleratedFramedTest))
  307. suite.addTest(loader.loadTestsFromTestCase(SerializersTest))
  308. return suite
  309. if __name__ == "__main__":
  310. unittest.main(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=2))