blob: d40b672a7c1cce05416ae9e11e9bce5454de9354 [file] [log] [blame]
Guido van Rossumfdecda01999-10-19 19:08:13 +00001"""Test the binascii C module."""
Roger E. Masse2a1c8341997-01-16 16:44:09 +00002
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +00003from test import test_support
4import unittest
Guido van Rossumfdecda01999-10-19 19:08:13 +00005import binascii
Antoine Pitroufd3a60d2010-01-14 16:27:09 +00006import array
Roger E. Masse2a1c8341997-01-16 16:44:09 +00007
Antoine Pitroudb983a72010-01-16 17:45:56 +00008# Note: "*_hex" functions are aliases for "(un)hexlify"
9b2a_functions = ['b2a_base64', 'b2a_hex', 'b2a_hqx', 'b2a_qp', 'b2a_uu',
10 'hexlify', 'rlecode_hqx']
11a2b_functions = ['a2b_base64', 'a2b_hex', 'a2b_hqx', 'a2b_qp', 'a2b_uu',
12 'unhexlify', 'rledecode_hqx']
13all_functions = a2b_functions + b2a_functions + ['crc32', 'crc_hqx']
14
15
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +000016class BinASCIITest(unittest.TestCase):
Roger E. Masse2a1c8341997-01-16 16:44:09 +000017
Antoine Pitroufd3a60d2010-01-14 16:27:09 +000018 type2test = str
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +000019 # Create binary test data
Antoine Pitroufd3a60d2010-01-14 16:27:09 +000020 rawdata = "The quick brown fox jumps over the lazy dog.\r\n"
Guido van Rossumfdecda01999-10-19 19:08:13 +000021 # Be slow so we don't depend on other modules
Antoine Pitroufd3a60d2010-01-14 16:27:09 +000022 rawdata += "".join(map(chr, xrange(256)))
23 rawdata += "\r\nHello world.\n"
24
25 def setUp(self):
26 self.data = self.type2test(self.rawdata)
Roger E. Masse2a1c8341997-01-16 16:44:09 +000027
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +000028 def test_exceptions(self):
29 # Check module exceptions
Benjamin Peterson5c8da862009-06-30 22:57:08 +000030 self.assertTrue(issubclass(binascii.Error, Exception))
31 self.assertTrue(issubclass(binascii.Incomplete, Exception))
Roger E. Masse2a1c8341997-01-16 16:44:09 +000032
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +000033 def test_functions(self):
34 # Check presence of all functions
Antoine Pitroudb983a72010-01-16 17:45:56 +000035 for name in all_functions:
Antoine Pitroufd3a60d2010-01-14 16:27:09 +000036 self.assertTrue(hasattr(getattr(binascii, name), '__call__'))
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +000037 self.assertRaises(TypeError, getattr(binascii, name))
38
Antoine Pitroudb983a72010-01-16 17:45:56 +000039 def test_returned_value(self):
40 # Limit to the minimum of all limits (b2a_uu)
41 MAX_ALL = 45
42 raw = self.rawdata[:MAX_ALL]
43 for fa, fb in zip(a2b_functions, b2a_functions):
44 a2b = getattr(binascii, fa)
45 b2a = getattr(binascii, fb)
46 try:
47 a = b2a(self.type2test(raw))
48 res = a2b(self.type2test(a))
49 except Exception, err:
50 self.fail("{}/{} conversion raises {!r}".format(fb, fa, err))
51 if fb == 'b2a_hqx':
52 # b2a_hqx returns a tuple
53 res, _ = res
54 self.assertEqual(res, raw, "{}/{} conversion: "
55 "{!r} != {!r}".format(fb, fa, res, raw))
56 self.assertIsInstance(res, str)
57 self.assertIsInstance(a, str)
58 self.assertLess(max(ord(c) for c in a), 128)
59 self.assertIsInstance(binascii.crc_hqx(raw, 0), int)
60 self.assertIsInstance(binascii.crc32(raw), int)
61
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +000062 def test_base64valid(self):
63 # Test base64 with valid data
64 MAX_BASE64 = 57
65 lines = []
Antoine Pitroudb983a72010-01-16 17:45:56 +000066 for i in range(0, len(self.rawdata), MAX_BASE64):
67 b = self.type2test(self.rawdata[i:i+MAX_BASE64])
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +000068 a = binascii.b2a_base64(b)
69 lines.append(a)
70 res = ""
71 for line in lines:
Antoine Pitroudb983a72010-01-16 17:45:56 +000072 a = self.type2test(line)
73 b = binascii.a2b_base64(a)
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +000074 res = res + b
Antoine Pitroufd3a60d2010-01-14 16:27:09 +000075 self.assertEqual(res, self.rawdata)
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +000076
77 def test_base64invalid(self):
78 # Test base64 with random invalid characters sprinkled throughout
79 # (This requires a new version of binascii.)
80 MAX_BASE64 = 57
81 lines = []
82 for i in range(0, len(self.data), MAX_BASE64):
Antoine Pitroudb983a72010-01-16 17:45:56 +000083 b = self.type2test(self.rawdata[i:i+MAX_BASE64])
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +000084 a = binascii.b2a_base64(b)
85 lines.append(a)
86
87 fillers = ""
88 valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/"
89 for i in xrange(256):
90 c = chr(i)
91 if c not in valid:
92 fillers += c
93 def addnoise(line):
94 noise = fillers
95 ratio = len(line) // len(noise)
96 res = ""
97 while line and noise:
98 if len(line) // len(noise) > ratio:
99 c, line = line[0], line[1:]
100 else:
101 c, noise = noise[0], noise[1:]
102 res += c
103 return res + noise + line
104 res = ""
105 for line in map(addnoise, lines):
Antoine Pitroudb983a72010-01-16 17:45:56 +0000106 a = self.type2test(line)
107 b = binascii.a2b_base64(a)
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000108 res += b
Antoine Pitroufd3a60d2010-01-14 16:27:09 +0000109 self.assertEqual(res, self.rawdata)
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000110
111 # Test base64 with just invalid characters, which should return
112 # empty strings. TBD: shouldn't it raise an exception instead ?
Antoine Pitroudb983a72010-01-16 17:45:56 +0000113 self.assertEqual(binascii.a2b_base64(self.type2test(fillers)), '')
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000114
115 def test_uu(self):
116 MAX_UU = 45
117 lines = []
118 for i in range(0, len(self.data), MAX_UU):
Antoine Pitroudb983a72010-01-16 17:45:56 +0000119 b = self.type2test(self.rawdata[i:i+MAX_UU])
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000120 a = binascii.b2a_uu(b)
121 lines.append(a)
122 res = ""
123 for line in lines:
Antoine Pitroudb983a72010-01-16 17:45:56 +0000124 a = self.type2test(line)
125 b = binascii.a2b_uu(a)
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000126 res += b
Antoine Pitroufd3a60d2010-01-14 16:27:09 +0000127 self.assertEqual(res, self.rawdata)
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000128
129 self.assertEqual(binascii.a2b_uu("\x7f"), "\x00"*31)
130 self.assertEqual(binascii.a2b_uu("\x80"), "\x00"*32)
131 self.assertEqual(binascii.a2b_uu("\xff"), "\x00"*31)
132 self.assertRaises(binascii.Error, binascii.a2b_uu, "\xff\x00")
133 self.assertRaises(binascii.Error, binascii.a2b_uu, "!!!!")
Tim Peters27f88362004-07-08 04:22:35 +0000134
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000135 self.assertRaises(binascii.Error, binascii.b2a_uu, 46*"!")
136
Antoine Pitrouc391ad02010-01-15 00:18:00 +0000137 # Issue #7701 (crash on a pydebug build)
138 self.assertEqual(binascii.b2a_uu('x'), '!> \n')
139
Serhiy Storchakabd617ad2015-04-20 09:32:29 +0300140 def test_crc_hqx(self):
141 crc = binascii.crc_hqx(self.type2test(b"Test the CRC-32 of"), 0)
142 crc = binascii.crc_hqx(self.type2test(b" this string."), crc)
143 self.assertEqual(crc, 14290)
144
145 self.assertRaises(TypeError, binascii.crc_hqx)
146 self.assertRaises(TypeError, binascii.crc_hqx, self.type2test(b''))
147
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000148 def test_crc32(self):
Antoine Pitroudb983a72010-01-16 17:45:56 +0000149 crc = binascii.crc32(self.type2test("Test the CRC-32 of"))
150 crc = binascii.crc32(self.type2test(" this string."), crc)
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000151 self.assertEqual(crc, 1571220330)
152
153 self.assertRaises(TypeError, binascii.crc32)
154
Antoine Pitroudb983a72010-01-16 17:45:56 +0000155 def test_hqx(self):
156 # Perform binhex4 style RLE-compression
157 # Then calculate the hexbin4 binary-to-ASCII translation
158 rle = binascii.rlecode_hqx(self.data)
159 a = binascii.b2a_hqx(self.type2test(rle))
160 b, _ = binascii.a2b_hqx(self.type2test(a))
161 res = binascii.rledecode_hqx(b)
162
163 self.assertEqual(res, self.rawdata)
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000164
165 def test_hex(self):
166 # test hexlification
167 s = '{s\005\000\000\000worldi\002\000\000\000s\005\000\000\000helloi\001\000\000\0000'
Antoine Pitroudb983a72010-01-16 17:45:56 +0000168 t = binascii.b2a_hex(self.type2test(s))
169 u = binascii.a2b_hex(self.type2test(t))
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000170 self.assertEqual(s, u)
171 self.assertRaises(TypeError, binascii.a2b_hex, t[:-1])
172 self.assertRaises(TypeError, binascii.a2b_hex, t[:-1] + 'q')
173
174 # Verify the treatment of Unicode strings
175 if test_support.have_unicode:
176 self.assertEqual(binascii.hexlify(unicode('a', 'ascii')), '61')
177
178 def test_qp(self):
179 # A test for SF bug 534347 (segfaults without the proper fix)
180 try:
181 binascii.a2b_qp("", **{1:1})
182 except TypeError:
183 pass
Guido van Rossumfdecda01999-10-19 19:08:13 +0000184 else:
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000185 self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError")
Georg Brandl25aabf42006-11-16 17:08:45 +0000186 self.assertEqual(binascii.a2b_qp("= "), "= ")
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000187 self.assertEqual(binascii.a2b_qp("=="), "=")
188 self.assertEqual(binascii.a2b_qp("=AX"), "=AX")
189 self.assertRaises(TypeError, binascii.b2a_qp, foo="bar")
190 self.assertEqual(binascii.a2b_qp("=00\r\n=00"), "\x00\r\n\x00")
191 self.assertEqual(
192 binascii.b2a_qp("\xff\r\n\xff\n\xff"),
193 "=FF\r\n=FF\r\n=FF"
194 )
195 self.assertEqual(
196 binascii.b2a_qp("0"*75+"\xff\r\n\xff\r\n\xff"),
197 "0"*75+"=\r\n=FF\r\n=FF\r\n=FF"
198 )
Roger E. Masse2a1c8341997-01-16 16:44:09 +0000199
Georg Brandl4aef7272007-03-13 22:49:43 +0000200 self.assertEqual(binascii.b2a_qp('\0\n'), '=00\n')
201 self.assertEqual(binascii.b2a_qp('\0\n', quotetabs=True), '=00\n')
202 self.assertEqual(binascii.b2a_qp('foo\tbar\t\n'), 'foo\tbar=09\n')
203 self.assertEqual(binascii.b2a_qp('foo\tbar\t\n', quotetabs=True), 'foo=09bar=09\n')
204
205 self.assertEqual(binascii.b2a_qp('.'), '=2E')
206 self.assertEqual(binascii.b2a_qp('.\n'), '=2E\n')
207 self.assertEqual(binascii.b2a_qp('a.\n'), 'a.\n')
208
Raymond Hettinger658717e2004-09-06 22:58:37 +0000209 def test_empty_string(self):
210 # A test for SF bug #1022953. Make sure SystemError is not raised.
Antoine Pitroudb983a72010-01-16 17:45:56 +0000211 empty = self.type2test('')
212 for func in all_functions:
213 if func == 'crc_hqx':
214 # crc_hqx needs 2 arguments
215 binascii.crc_hqx(empty, 0)
216 continue
217 f = getattr(binascii, func)
218 try:
219 f(empty)
220 except Exception, err:
221 self.fail("{}({!r}) raises {!r}".format(func, empty, err))
Raymond Hettinger658717e2004-09-06 22:58:37 +0000222
Antoine Pitroufd3a60d2010-01-14 16:27:09 +0000223
224class ArrayBinASCIITest(BinASCIITest):
225 def type2test(self, s):
226 return array.array('c', s)
227
228
Antoine Pitroudb983a72010-01-16 17:45:56 +0000229class BytearrayBinASCIITest(BinASCIITest):
230 type2test = bytearray
231
232
Antoine Pitroufd3a60d2010-01-14 16:27:09 +0000233class MemoryviewBinASCIITest(BinASCIITest):
234 type2test = memoryview
235
236
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000237def test_main():
Antoine Pitroufd3a60d2010-01-14 16:27:09 +0000238 test_support.run_unittest(BinASCIITest,
239 ArrayBinASCIITest,
Antoine Pitroudb983a72010-01-16 17:45:56 +0000240 BytearrayBinASCIITest,
Antoine Pitroufd3a60d2010-01-14 16:27:09 +0000241 MemoryviewBinASCIITest)
Thomas Wouters9e1c1922003-03-17 11:24:29 +0000242
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000243if __name__ == "__main__":
244 test_main()