blob: f825f1c0779981ccfe0289c4857ae9c99c02ce46 [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
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000140 def test_crc32(self):
Antoine Pitroudb983a72010-01-16 17:45:56 +0000141 crc = binascii.crc32(self.type2test("Test the CRC-32 of"))
142 crc = binascii.crc32(self.type2test(" this string."), crc)
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000143 self.assertEqual(crc, 1571220330)
144
145 self.assertRaises(TypeError, binascii.crc32)
146
Antoine Pitroudb983a72010-01-16 17:45:56 +0000147 def test_hqx(self):
148 # Perform binhex4 style RLE-compression
149 # Then calculate the hexbin4 binary-to-ASCII translation
150 rle = binascii.rlecode_hqx(self.data)
151 a = binascii.b2a_hqx(self.type2test(rle))
152 b, _ = binascii.a2b_hqx(self.type2test(a))
153 res = binascii.rledecode_hqx(b)
154
155 self.assertEqual(res, self.rawdata)
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000156
157 def test_hex(self):
158 # test hexlification
159 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 +0000160 t = binascii.b2a_hex(self.type2test(s))
161 u = binascii.a2b_hex(self.type2test(t))
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000162 self.assertEqual(s, u)
163 self.assertRaises(TypeError, binascii.a2b_hex, t[:-1])
164 self.assertRaises(TypeError, binascii.a2b_hex, t[:-1] + 'q')
165
166 # Verify the treatment of Unicode strings
167 if test_support.have_unicode:
168 self.assertEqual(binascii.hexlify(unicode('a', 'ascii')), '61')
169
170 def test_qp(self):
171 # A test for SF bug 534347 (segfaults without the proper fix)
172 try:
173 binascii.a2b_qp("", **{1:1})
174 except TypeError:
175 pass
Guido van Rossumfdecda01999-10-19 19:08:13 +0000176 else:
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000177 self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError")
Georg Brandl25aabf42006-11-16 17:08:45 +0000178 self.assertEqual(binascii.a2b_qp("= "), "= ")
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000179 self.assertEqual(binascii.a2b_qp("=="), "=")
180 self.assertEqual(binascii.a2b_qp("=AX"), "=AX")
181 self.assertRaises(TypeError, binascii.b2a_qp, foo="bar")
182 self.assertEqual(binascii.a2b_qp("=00\r\n=00"), "\x00\r\n\x00")
183 self.assertEqual(
184 binascii.b2a_qp("\xff\r\n\xff\n\xff"),
185 "=FF\r\n=FF\r\n=FF"
186 )
187 self.assertEqual(
188 binascii.b2a_qp("0"*75+"\xff\r\n\xff\r\n\xff"),
189 "0"*75+"=\r\n=FF\r\n=FF\r\n=FF"
190 )
Roger E. Masse2a1c8341997-01-16 16:44:09 +0000191
Georg Brandl4aef7272007-03-13 22:49:43 +0000192 self.assertEqual(binascii.b2a_qp('\0\n'), '=00\n')
193 self.assertEqual(binascii.b2a_qp('\0\n', quotetabs=True), '=00\n')
194 self.assertEqual(binascii.b2a_qp('foo\tbar\t\n'), 'foo\tbar=09\n')
195 self.assertEqual(binascii.b2a_qp('foo\tbar\t\n', quotetabs=True), 'foo=09bar=09\n')
196
197 self.assertEqual(binascii.b2a_qp('.'), '=2E')
198 self.assertEqual(binascii.b2a_qp('.\n'), '=2E\n')
199 self.assertEqual(binascii.b2a_qp('a.\n'), 'a.\n')
200
Raymond Hettinger658717e2004-09-06 22:58:37 +0000201 def test_empty_string(self):
202 # A test for SF bug #1022953. Make sure SystemError is not raised.
Antoine Pitroudb983a72010-01-16 17:45:56 +0000203 empty = self.type2test('')
204 for func in all_functions:
205 if func == 'crc_hqx':
206 # crc_hqx needs 2 arguments
207 binascii.crc_hqx(empty, 0)
208 continue
209 f = getattr(binascii, func)
210 try:
211 f(empty)
212 except Exception, err:
213 self.fail("{}({!r}) raises {!r}".format(func, empty, err))
Raymond Hettinger658717e2004-09-06 22:58:37 +0000214
Antoine Pitroufd3a60d2010-01-14 16:27:09 +0000215
216class ArrayBinASCIITest(BinASCIITest):
217 def type2test(self, s):
218 return array.array('c', s)
219
220
Antoine Pitroudb983a72010-01-16 17:45:56 +0000221class BytearrayBinASCIITest(BinASCIITest):
222 type2test = bytearray
223
224
Antoine Pitroufd3a60d2010-01-14 16:27:09 +0000225class MemoryviewBinASCIITest(BinASCIITest):
226 type2test = memoryview
227
228
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000229def test_main():
Antoine Pitroufd3a60d2010-01-14 16:27:09 +0000230 test_support.run_unittest(BinASCIITest,
231 ArrayBinASCIITest,
Antoine Pitroudb983a72010-01-16 17:45:56 +0000232 BytearrayBinASCIITest,
Antoine Pitroufd3a60d2010-01-14 16:27:09 +0000233 MemoryviewBinASCIITest)
Thomas Wouters9e1c1922003-03-17 11:24:29 +0000234
Walter Dörwaldcd1e8a92004-03-15 12:07:38 +0000235if __name__ == "__main__":
236 test_main()