test_xdrlib.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from test import test_support
  2. import unittest
  3. import xdrlib
  4. class XDRTest(unittest.TestCase):
  5. def test_xdr(self):
  6. p = xdrlib.Packer()
  7. s = 'hello world'
  8. a = ['what', 'is', 'hapnin', 'doctor']
  9. p.pack_int(42)
  10. p.pack_int(-17)
  11. p.pack_uint(9)
  12. p.pack_bool(True)
  13. p.pack_bool(False)
  14. p.pack_uhyper(45L)
  15. p.pack_float(1.9)
  16. p.pack_double(1.9)
  17. p.pack_string(s)
  18. p.pack_list(range(5), p.pack_uint)
  19. p.pack_array(a, p.pack_string)
  20. # now verify
  21. data = p.get_buffer()
  22. up = xdrlib.Unpacker(data)
  23. self.assertEqual(up.get_position(), 0)
  24. self.assertEqual(up.unpack_int(), 42)
  25. self.assertEqual(up.unpack_int(), -17)
  26. self.assertEqual(up.unpack_uint(), 9)
  27. self.assertTrue(up.unpack_bool() is True)
  28. # remember position
  29. pos = up.get_position()
  30. self.assertTrue(up.unpack_bool() is False)
  31. # rewind and unpack again
  32. up.set_position(pos)
  33. self.assertTrue(up.unpack_bool() is False)
  34. self.assertEqual(up.unpack_uhyper(), 45L)
  35. self.assertAlmostEqual(up.unpack_float(), 1.9)
  36. self.assertAlmostEqual(up.unpack_double(), 1.9)
  37. self.assertEqual(up.unpack_string(), s)
  38. self.assertEqual(up.unpack_list(up.unpack_uint), range(5))
  39. self.assertEqual(up.unpack_array(up.unpack_string), a)
  40. up.done()
  41. self.assertRaises(EOFError, up.unpack_uint)
  42. class ConversionErrorTest(unittest.TestCase):
  43. def setUp(self):
  44. self.packer = xdrlib.Packer()
  45. def assertRaisesConversion(self, *args):
  46. self.assertRaises(xdrlib.ConversionError, *args)
  47. def test_pack_int(self):
  48. self.assertRaisesConversion(self.packer.pack_int, 'string')
  49. def test_pack_uint(self):
  50. self.assertRaisesConversion(self.packer.pack_uint, 'string')
  51. def test_float(self):
  52. self.assertRaisesConversion(self.packer.pack_float, 'string')
  53. def test_double(self):
  54. self.assertRaisesConversion(self.packer.pack_double, 'string')
  55. def test_uhyper(self):
  56. self.assertRaisesConversion(self.packer.pack_uhyper, 'string')
  57. def test_main():
  58. test_support.run_unittest(XDRTest)
  59. test_support.run_unittest(ConversionErrorTest)
  60. if __name__ == "__main__":
  61. test_main()