/Lib/test/test_binascii.py

http://unladen-swallow.googlecode.com/ · Python · 174 lines · 136 code · 23 blank · 15 comment · 22 complexity · 9245a17d96d9ae67dda8222ccb7dcd29 MD5 · raw file

  1. """Test the binascii C module."""
  2. from test import test_support
  3. import unittest
  4. import binascii
  5. class BinASCIITest(unittest.TestCase):
  6. # Create binary test data
  7. data = "The quick brown fox jumps over the lazy dog.\r\n"
  8. # Be slow so we don't depend on other modules
  9. data += "".join(map(chr, xrange(256)))
  10. data += "\r\nHello world.\n"
  11. def test_exceptions(self):
  12. # Check module exceptions
  13. self.assert_(issubclass(binascii.Error, Exception))
  14. self.assert_(issubclass(binascii.Incomplete, Exception))
  15. def test_functions(self):
  16. # Check presence of all functions
  17. funcs = []
  18. for suffix in "base64", "hqx", "uu", "hex":
  19. prefixes = ["a2b_", "b2a_"]
  20. if suffix == "hqx":
  21. prefixes.extend(["crc_", "rlecode_", "rledecode_"])
  22. for prefix in prefixes:
  23. name = prefix + suffix
  24. self.assert_(callable(getattr(binascii, name)))
  25. self.assertRaises(TypeError, getattr(binascii, name))
  26. for name in ("hexlify", "unhexlify"):
  27. self.assert_(callable(getattr(binascii, name)))
  28. self.assertRaises(TypeError, getattr(binascii, name))
  29. def test_base64valid(self):
  30. # Test base64 with valid data
  31. MAX_BASE64 = 57
  32. lines = []
  33. for i in range(0, len(self.data), MAX_BASE64):
  34. b = self.data[i:i+MAX_BASE64]
  35. a = binascii.b2a_base64(b)
  36. lines.append(a)
  37. res = ""
  38. for line in lines:
  39. b = binascii.a2b_base64(line)
  40. res = res + b
  41. self.assertEqual(res, self.data)
  42. def test_base64invalid(self):
  43. # Test base64 with random invalid characters sprinkled throughout
  44. # (This requires a new version of binascii.)
  45. MAX_BASE64 = 57
  46. lines = []
  47. for i in range(0, len(self.data), MAX_BASE64):
  48. b = self.data[i:i+MAX_BASE64]
  49. a = binascii.b2a_base64(b)
  50. lines.append(a)
  51. fillers = ""
  52. valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/"
  53. for i in xrange(256):
  54. c = chr(i)
  55. if c not in valid:
  56. fillers += c
  57. def addnoise(line):
  58. noise = fillers
  59. ratio = len(line) // len(noise)
  60. res = ""
  61. while line and noise:
  62. if len(line) // len(noise) > ratio:
  63. c, line = line[0], line[1:]
  64. else:
  65. c, noise = noise[0], noise[1:]
  66. res += c
  67. return res + noise + line
  68. res = ""
  69. for line in map(addnoise, lines):
  70. b = binascii.a2b_base64(line)
  71. res += b
  72. self.assertEqual(res, self.data)
  73. # Test base64 with just invalid characters, which should return
  74. # empty strings. TBD: shouldn't it raise an exception instead ?
  75. self.assertEqual(binascii.a2b_base64(fillers), '')
  76. def test_uu(self):
  77. MAX_UU = 45
  78. lines = []
  79. for i in range(0, len(self.data), MAX_UU):
  80. b = self.data[i:i+MAX_UU]
  81. a = binascii.b2a_uu(b)
  82. lines.append(a)
  83. res = ""
  84. for line in lines:
  85. b = binascii.a2b_uu(line)
  86. res += b
  87. self.assertEqual(res, self.data)
  88. self.assertEqual(binascii.a2b_uu("\x7f"), "\x00"*31)
  89. self.assertEqual(binascii.a2b_uu("\x80"), "\x00"*32)
  90. self.assertEqual(binascii.a2b_uu("\xff"), "\x00"*31)
  91. self.assertRaises(binascii.Error, binascii.a2b_uu, "\xff\x00")
  92. self.assertRaises(binascii.Error, binascii.a2b_uu, "!!!!")
  93. self.assertRaises(binascii.Error, binascii.b2a_uu, 46*"!")
  94. def test_crc32(self):
  95. crc = binascii.crc32("Test the CRC-32 of")
  96. crc = binascii.crc32(" this string.", crc)
  97. self.assertEqual(crc, 1571220330)
  98. self.assertRaises(TypeError, binascii.crc32)
  99. # The hqx test is in test_binhex.py
  100. def test_hex(self):
  101. # test hexlification
  102. s = '{s\005\000\000\000worldi\002\000\000\000s\005\000\000\000helloi\001\000\000\0000'
  103. t = binascii.b2a_hex(s)
  104. u = binascii.a2b_hex(t)
  105. self.assertEqual(s, u)
  106. self.assertRaises(TypeError, binascii.a2b_hex, t[:-1])
  107. self.assertRaises(TypeError, binascii.a2b_hex, t[:-1] + 'q')
  108. # Verify the treatment of Unicode strings
  109. if test_support.have_unicode:
  110. self.assertEqual(binascii.hexlify(unicode('a', 'ascii')), '61')
  111. def test_qp(self):
  112. # A test for SF bug 534347 (segfaults without the proper fix)
  113. try:
  114. binascii.a2b_qp("", **{1:1})
  115. except TypeError:
  116. pass
  117. else:
  118. self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError")
  119. self.assertEqual(binascii.a2b_qp("= "), "= ")
  120. self.assertEqual(binascii.a2b_qp("=="), "=")
  121. self.assertEqual(binascii.a2b_qp("=AX"), "=AX")
  122. self.assertRaises(TypeError, binascii.b2a_qp, foo="bar")
  123. self.assertEqual(binascii.a2b_qp("=00\r\n=00"), "\x00\r\n\x00")
  124. self.assertEqual(
  125. binascii.b2a_qp("\xff\r\n\xff\n\xff"),
  126. "=FF\r\n=FF\r\n=FF"
  127. )
  128. self.assertEqual(
  129. binascii.b2a_qp("0"*75+"\xff\r\n\xff\r\n\xff"),
  130. "0"*75+"=\r\n=FF\r\n=FF\r\n=FF"
  131. )
  132. self.assertEqual(binascii.b2a_qp('\0\n'), '=00\n')
  133. self.assertEqual(binascii.b2a_qp('\0\n', quotetabs=True), '=00\n')
  134. self.assertEqual(binascii.b2a_qp('foo\tbar\t\n'), 'foo\tbar=09\n')
  135. self.assertEqual(binascii.b2a_qp('foo\tbar\t\n', quotetabs=True), 'foo=09bar=09\n')
  136. self.assertEqual(binascii.b2a_qp('.'), '=2E')
  137. self.assertEqual(binascii.b2a_qp('.\n'), '=2E\n')
  138. self.assertEqual(binascii.b2a_qp('a.\n'), 'a.\n')
  139. def test_empty_string(self):
  140. # A test for SF bug #1022953. Make sure SystemError is not raised.
  141. for n in ['b2a_qp', 'a2b_hex', 'b2a_base64', 'a2b_uu', 'a2b_qp',
  142. 'b2a_hex', 'unhexlify', 'hexlify', 'crc32', 'b2a_hqx',
  143. 'a2b_hqx', 'a2b_base64', 'rlecode_hqx', 'b2a_uu',
  144. 'rledecode_hqx']:
  145. f = getattr(binascii, n)
  146. f('')
  147. binascii.crc_hqx('', 0)
  148. def test_main():
  149. test_support.run_unittest(BinASCIITest)
  150. if __name__ == "__main__":
  151. test_main()