blob: 4f86aaa0c0eb49930483f4ff3ba741b48023703c [file] [log] [blame]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Walter Dörwald21d3a322003-05-01 17:45:56 +00003import base64
Guido van Rossum4581ae52007-05-22 21:56:47 +00004import binascii
Vinay Sajipf9596182012-03-02 01:01:13 +00005import os
Nick Coghlanfdf239a2013-10-03 00:43:22 +10006from array import array
Berker Peksag00f81972015-07-25 14:14:24 +03007from test.support import script_helper
Raymond Hettinger2ae87532002-05-18 00:25:10 +00008
Ezio Melottib3aedd42010-11-20 19:04:17 +00009
Barry Warsaw4f019d32004-01-04 01:13:02 +000010class LegacyBase64TestCase(unittest.TestCase):
Nick Coghlanfdf239a2013-10-03 00:43:22 +100011
12 # Legacy API is not as permissive as the modern API
13 def check_type_errors(self, f):
14 self.assertRaises(TypeError, f, "")
15 self.assertRaises(TypeError, f, [])
16 multidimensional = memoryview(b"1234").cast('B', (2, 2))
17 self.assertRaises(TypeError, f, multidimensional)
18 int_data = memoryview(b"1234").cast('I')
19 self.assertRaises(TypeError, f, int_data)
20
Georg Brandlb54d8012009-06-04 09:11:51 +000021 def test_encodebytes(self):
Barry Warsaw4f019d32004-01-04 01:13:02 +000022 eq = self.assertEqual
Georg Brandlb54d8012009-06-04 09:11:51 +000023 eq(base64.encodebytes(b"www.python.org"), b"d3d3LnB5dGhvbi5vcmc=\n")
24 eq(base64.encodebytes(b"a"), b"YQ==\n")
25 eq(base64.encodebytes(b"ab"), b"YWI=\n")
26 eq(base64.encodebytes(b"abc"), b"YWJj\n")
27 eq(base64.encodebytes(b""), b"")
28 eq(base64.encodebytes(b"abcdefghijklmnopqrstuvwxyz"
Guido van Rossum4581ae52007-05-22 21:56:47 +000029 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30 b"0123456789!@#0^&*();:<>,. []{}"),
31 b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
32 b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
33 b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n")
Serhiy Storchaka017523c2013-04-28 15:53:08 +030034 # Non-bytes
35 eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\n')
Nick Coghlanfdf239a2013-10-03 00:43:22 +100036 eq(base64.encodebytes(memoryview(b'abc')), b'YWJj\n')
37 eq(base64.encodebytes(array('B', b'abc')), b'YWJj\n')
38 self.check_type_errors(base64.encodebytes)
Guido van Rossumcb682582002-08-22 19:18:56 +000039
Georg Brandlb54d8012009-06-04 09:11:51 +000040 def test_decodebytes(self):
Barry Warsaw4f019d32004-01-04 01:13:02 +000041 eq = self.assertEqual
Georg Brandlb54d8012009-06-04 09:11:51 +000042 eq(base64.decodebytes(b"d3d3LnB5dGhvbi5vcmc=\n"), b"www.python.org")
43 eq(base64.decodebytes(b"YQ==\n"), b"a")
44 eq(base64.decodebytes(b"YWI=\n"), b"ab")
45 eq(base64.decodebytes(b"YWJj\n"), b"abc")
46 eq(base64.decodebytes(b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
Guido van Rossum4581ae52007-05-22 21:56:47 +000047 b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
48 b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n"),
49 b"abcdefghijklmnopqrstuvwxyz"
50 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
51 b"0123456789!@#0^&*();:<>,. []{}")
Georg Brandlb54d8012009-06-04 09:11:51 +000052 eq(base64.decodebytes(b''), b'')
Serhiy Storchaka017523c2013-04-28 15:53:08 +030053 # Non-bytes
54 eq(base64.decodebytes(bytearray(b'YWJj\n')), b'abc')
Nick Coghlanfdf239a2013-10-03 00:43:22 +100055 eq(base64.decodebytes(memoryview(b'YWJj\n')), b'abc')
56 eq(base64.decodebytes(array('B', b'YWJj\n')), b'abc')
57 self.check_type_errors(base64.decodebytes)
Barry Warsaw4f019d32004-01-04 01:13:02 +000058
59 def test_encode(self):
60 eq = self.assertEqual
Serhiy Storchakaabac0a72013-04-28 15:56:11 +030061 from io import BytesIO, StringIO
Guido van Rossum34d19282007-08-09 01:03:29 +000062 infp = BytesIO(b'abcdefghijklmnopqrstuvwxyz'
63 b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
64 b'0123456789!@#0^&*();:<>,. []{}')
65 outfp = BytesIO()
Barry Warsaw4f019d32004-01-04 01:13:02 +000066 base64.encode(infp, outfp)
67 eq(outfp.getvalue(),
Guido van Rossum34d19282007-08-09 01:03:29 +000068 b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE'
69 b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT'
70 b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n')
Serhiy Storchakaabac0a72013-04-28 15:56:11 +030071 # Non-binary files
72 self.assertRaises(TypeError, base64.encode, StringIO('abc'), BytesIO())
73 self.assertRaises(TypeError, base64.encode, BytesIO(b'abc'), StringIO())
74 self.assertRaises(TypeError, base64.encode, StringIO('abc'), StringIO())
Barry Warsaw4f019d32004-01-04 01:13:02 +000075
76 def test_decode(self):
Serhiy Storchakaabac0a72013-04-28 15:56:11 +030077 from io import BytesIO, StringIO
Guido van Rossum34d19282007-08-09 01:03:29 +000078 infp = BytesIO(b'd3d3LnB5dGhvbi5vcmc=')
79 outfp = BytesIO()
Barry Warsaw4f019d32004-01-04 01:13:02 +000080 base64.decode(infp, outfp)
Guido van Rossum34d19282007-08-09 01:03:29 +000081 self.assertEqual(outfp.getvalue(), b'www.python.org')
Serhiy Storchakaabac0a72013-04-28 15:56:11 +030082 # Non-binary files
83 self.assertRaises(TypeError, base64.encode, StringIO('YWJj\n'), BytesIO())
84 self.assertRaises(TypeError, base64.encode, BytesIO(b'YWJj\n'), StringIO())
85 self.assertRaises(TypeError, base64.encode, StringIO('YWJj\n'), StringIO())
Barry Warsaw4f019d32004-01-04 01:13:02 +000086
Ezio Melottib3aedd42010-11-20 19:04:17 +000087
Barry Warsaw4f019d32004-01-04 01:13:02 +000088class BaseXYTestCase(unittest.TestCase):
Nick Coghlanfdf239a2013-10-03 00:43:22 +100089
90 # Modern API completely ignores exported dimension and format data and
91 # treats any buffer as a stream of bytes
92 def check_encode_type_errors(self, f):
93 self.assertRaises(TypeError, f, "")
94 self.assertRaises(TypeError, f, [])
95
96 def check_decode_type_errors(self, f):
97 self.assertRaises(TypeError, f, [])
98
99 def check_other_types(self, f, bytes_data, expected):
100 eq = self.assertEqual
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100101 b = bytearray(bytes_data)
102 eq(f(b), expected)
103 # The bytearray wasn't mutated
104 eq(b, bytes_data)
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000105 eq(f(memoryview(bytes_data)), expected)
106 eq(f(array('B', bytes_data)), expected)
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100107 # XXX why is b64encode hardcoded here?
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000108 self.check_nonbyte_element_format(base64.b64encode, bytes_data)
109 self.check_multidimensional(base64.b64encode, bytes_data)
110
111 def check_multidimensional(self, f, data):
112 padding = b"\x00" if len(data) % 2 else b""
113 bytes_data = data + padding # Make sure cast works
114 shape = (len(bytes_data) // 2, 2)
115 multidimensional = memoryview(bytes_data).cast('B', shape)
116 self.assertEqual(f(multidimensional), f(bytes_data))
117
118 def check_nonbyte_element_format(self, f, data):
119 padding = b"\x00" * ((4 - len(data)) % 4)
120 bytes_data = data + padding # Make sure cast works
121 int_data = memoryview(bytes_data).cast('I')
122 self.assertEqual(f(int_data), f(bytes_data))
123
124
Barry Warsaw4f019d32004-01-04 01:13:02 +0000125 def test_b64encode(self):
126 eq = self.assertEqual
127 # Test default alphabet
Guido van Rossum4581ae52007-05-22 21:56:47 +0000128 eq(base64.b64encode(b"www.python.org"), b"d3d3LnB5dGhvbi5vcmc=")
129 eq(base64.b64encode(b'\x00'), b'AA==')
130 eq(base64.b64encode(b"a"), b"YQ==")
131 eq(base64.b64encode(b"ab"), b"YWI=")
132 eq(base64.b64encode(b"abc"), b"YWJj")
133 eq(base64.b64encode(b""), b"")
134 eq(base64.b64encode(b"abcdefghijklmnopqrstuvwxyz"
135 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
136 b"0123456789!@#0^&*();:<>,. []{}"),
137 b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
138 b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
139 b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
Barry Warsaw4f019d32004-01-04 01:13:02 +0000140 # Test with arbitrary alternative characters
Alexandre Vassalotti5209857f2008-05-03 04:39:38 +0000141 eq(base64.b64encode(b'\xd3V\xbeo\xf7\x1d', altchars=b'*$'), b'01a*b$cd')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300142 eq(base64.b64encode(b'\xd3V\xbeo\xf7\x1d', altchars=bytearray(b'*$')),
143 b'01a*b$cd')
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000144 eq(base64.b64encode(b'\xd3V\xbeo\xf7\x1d', altchars=memoryview(b'*$')),
145 b'01a*b$cd')
146 eq(base64.b64encode(b'\xd3V\xbeo\xf7\x1d', altchars=array('B', b'*$')),
147 b'01a*b$cd')
148 # Non-bytes
149 self.check_other_types(base64.b64encode, b'abcd', b'YWJjZA==')
150 self.check_encode_type_errors(base64.b64encode)
151 self.assertRaises(TypeError, base64.b64encode, b"", altchars="*$")
Barry Warsaw4f019d32004-01-04 01:13:02 +0000152 # Test standard alphabet
Guido van Rossum4581ae52007-05-22 21:56:47 +0000153 eq(base64.standard_b64encode(b"www.python.org"), b"d3d3LnB5dGhvbi5vcmc=")
154 eq(base64.standard_b64encode(b"a"), b"YQ==")
155 eq(base64.standard_b64encode(b"ab"), b"YWI=")
156 eq(base64.standard_b64encode(b"abc"), b"YWJj")
157 eq(base64.standard_b64encode(b""), b"")
158 eq(base64.standard_b64encode(b"abcdefghijklmnopqrstuvwxyz"
159 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
160 b"0123456789!@#0^&*();:<>,. []{}"),
161 b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
162 b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
163 b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300164 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000165 self.check_other_types(base64.standard_b64encode,
166 b'abcd', b'YWJjZA==')
167 self.check_encode_type_errors(base64.standard_b64encode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000168 # Test with 'URL safe' alternative characters
Guido van Rossum4581ae52007-05-22 21:56:47 +0000169 eq(base64.urlsafe_b64encode(b'\xd3V\xbeo\xf7\x1d'), b'01a-b_cd')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300170 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000171 self.check_other_types(base64.urlsafe_b64encode,
172 b'\xd3V\xbeo\xf7\x1d', b'01a-b_cd')
173 self.check_encode_type_errors(base64.urlsafe_b64encode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000174
175 def test_b64decode(self):
176 eq = self.assertEqual
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100177
178 tests = {b"d3d3LnB5dGhvbi5vcmc=": b"www.python.org",
179 b'AA==': b'\x00',
180 b"YQ==": b"a",
181 b"YWI=": b"ab",
182 b"YWJj": b"abc",
183 b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
184 b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
185 b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==":
186
187 b"abcdefghijklmnopqrstuvwxyz"
188 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
189 b"0123456789!@#0^&*();:<>,. []{}",
190 b'': b'',
191 }
192 for data, res in tests.items():
193 eq(base64.b64decode(data), res)
194 eq(base64.b64decode(data.decode('ascii')), res)
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300195 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000196 self.check_other_types(base64.b64decode, b"YWJj", b"abc")
197 self.check_decode_type_errors(base64.b64decode)
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100198
Barry Warsaw4f019d32004-01-04 01:13:02 +0000199 # Test with arbitrary alternative characters
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100200 tests_altchars = {(b'01a*b$cd', b'*$'): b'\xd3V\xbeo\xf7\x1d',
201 }
202 for (data, altchars), res in tests_altchars.items():
203 data_str = data.decode('ascii')
204 altchars_str = altchars.decode('ascii')
205
206 eq(base64.b64decode(data, altchars=altchars), res)
207 eq(base64.b64decode(data_str, altchars=altchars), res)
208 eq(base64.b64decode(data, altchars=altchars_str), res)
209 eq(base64.b64decode(data_str, altchars=altchars_str), res)
210
Barry Warsaw4f019d32004-01-04 01:13:02 +0000211 # Test standard alphabet
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100212 for data, res in tests.items():
213 eq(base64.standard_b64decode(data), res)
214 eq(base64.standard_b64decode(data.decode('ascii')), res)
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300215 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000216 self.check_other_types(base64.standard_b64decode, b"YWJj", b"abc")
217 self.check_decode_type_errors(base64.standard_b64decode)
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100218
Barry Warsaw4f019d32004-01-04 01:13:02 +0000219 # Test with 'URL safe' alternative characters
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100220 tests_urlsafe = {b'01a-b_cd': b'\xd3V\xbeo\xf7\x1d',
221 b'': b'',
222 }
223 for data, res in tests_urlsafe.items():
224 eq(base64.urlsafe_b64decode(data), res)
225 eq(base64.urlsafe_b64decode(data.decode('ascii')), res)
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300226 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000227 self.check_other_types(base64.urlsafe_b64decode, b'01a-b_cd',
228 b'\xd3V\xbeo\xf7\x1d')
229 self.check_decode_type_errors(base64.urlsafe_b64decode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000230
R. David Murray64951362010-11-11 20:09:20 +0000231 def test_b64decode_padding_error(self):
Guido van Rossum4581ae52007-05-22 21:56:47 +0000232 self.assertRaises(binascii.Error, base64.b64decode, b'abc')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100233 self.assertRaises(binascii.Error, base64.b64decode, 'abc')
Barry Warsaw4f019d32004-01-04 01:13:02 +0000234
R. David Murray64951362010-11-11 20:09:20 +0000235 def test_b64decode_invalid_chars(self):
236 # issue 1466065: Test some invalid characters.
237 tests = ((b'%3d==', b'\xdd'),
238 (b'$3d==', b'\xdd'),
239 (b'[==', b''),
240 (b'YW]3=', b'am'),
241 (b'3{d==', b'\xdd'),
242 (b'3d}==', b'\xdd'),
243 (b'@@', b''),
244 (b'!', b''),
245 (b'YWJj\nYWI=', b'abcab'))
Martin Panteree3074e2016-02-23 22:30:50 +0000246 funcs = (
247 base64.b64decode,
248 base64.standard_b64decode,
249 base64.urlsafe_b64decode,
250 )
R. David Murray64951362010-11-11 20:09:20 +0000251 for bstr, res in tests:
Martin Panteree3074e2016-02-23 22:30:50 +0000252 for func in funcs:
253 with self.subTest(bstr=bstr, func=func):
254 self.assertEqual(func(bstr), res)
255 self.assertEqual(func(bstr.decode('ascii')), res)
R. David Murray64951362010-11-11 20:09:20 +0000256 with self.assertRaises(binascii.Error):
257 base64.b64decode(bstr, validate=True)
Antoine Pitroudff46fa2012-02-20 19:46:26 +0100258 with self.assertRaises(binascii.Error):
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100259 base64.b64decode(bstr.decode('ascii'), validate=True)
R. David Murray64951362010-11-11 20:09:20 +0000260
Martin Panteree3074e2016-02-23 22:30:50 +0000261 # Normal alphabet characters not discarded when alternative given
262 res = b'\xFB\xEF\xBE\xFF\xFF\xFF'
263 self.assertEqual(base64.b64decode(b'++[[//]]', b'[]'), res)
264 self.assertEqual(base64.urlsafe_b64decode(b'++--//__'), res)
265
Barry Warsaw4f019d32004-01-04 01:13:02 +0000266 def test_b32encode(self):
267 eq = self.assertEqual
Guido van Rossum4581ae52007-05-22 21:56:47 +0000268 eq(base64.b32encode(b''), b'')
269 eq(base64.b32encode(b'\x00'), b'AA======')
270 eq(base64.b32encode(b'a'), b'ME======')
271 eq(base64.b32encode(b'ab'), b'MFRA====')
272 eq(base64.b32encode(b'abc'), b'MFRGG===')
273 eq(base64.b32encode(b'abcd'), b'MFRGGZA=')
274 eq(base64.b32encode(b'abcde'), b'MFRGGZDF')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300275 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000276 self.check_other_types(base64.b32encode, b'abcd', b'MFRGGZA=')
277 self.check_encode_type_errors(base64.b32encode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000278
279 def test_b32decode(self):
280 eq = self.assertEqual
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100281 tests = {b'': b'',
282 b'AA======': b'\x00',
283 b'ME======': b'a',
284 b'MFRA====': b'ab',
285 b'MFRGG===': b'abc',
286 b'MFRGGZA=': b'abcd',
287 b'MFRGGZDF': b'abcde',
288 }
289 for data, res in tests.items():
290 eq(base64.b32decode(data), res)
291 eq(base64.b32decode(data.decode('ascii')), res)
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300292 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000293 self.check_other_types(base64.b32decode, b'MFRGG===', b"abc")
294 self.check_decode_type_errors(base64.b32decode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000295
296 def test_b32decode_casefold(self):
297 eq = self.assertEqual
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100298 tests = {b'': b'',
299 b'ME======': b'a',
300 b'MFRA====': b'ab',
301 b'MFRGG===': b'abc',
302 b'MFRGGZA=': b'abcd',
303 b'MFRGGZDF': b'abcde',
304 # Lower cases
305 b'me======': b'a',
306 b'mfra====': b'ab',
307 b'mfrgg===': b'abc',
308 b'mfrggza=': b'abcd',
309 b'mfrggzdf': b'abcde',
310 }
311
312 for data, res in tests.items():
313 eq(base64.b32decode(data, True), res)
314 eq(base64.b32decode(data.decode('ascii'), True), res)
315
Serhiy Storchakaea2b4902013-05-28 15:27:29 +0300316 self.assertRaises(binascii.Error, base64.b32decode, b'me======')
317 self.assertRaises(binascii.Error, base64.b32decode, 'me======')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100318
Barry Warsaw4f019d32004-01-04 01:13:02 +0000319 # Mapping zero and one
Guido van Rossum4581ae52007-05-22 21:56:47 +0000320 eq(base64.b32decode(b'MLO23456'), b'b\xdd\xad\xf3\xbe')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100321 eq(base64.b32decode('MLO23456'), b'b\xdd\xad\xf3\xbe')
322
323 map_tests = {(b'M1023456', b'L'): b'b\xdd\xad\xf3\xbe',
324 (b'M1023456', b'I'): b'b\x1d\xad\xf3\xbe',
325 }
326 for (data, map01), res in map_tests.items():
327 data_str = data.decode('ascii')
328 map01_str = map01.decode('ascii')
329
330 eq(base64.b32decode(data, map01=map01), res)
331 eq(base64.b32decode(data_str, map01=map01), res)
332 eq(base64.b32decode(data, map01=map01_str), res)
333 eq(base64.b32decode(data_str, map01=map01_str), res)
Serhiy Storchakaea2b4902013-05-28 15:27:29 +0300334 self.assertRaises(binascii.Error, base64.b32decode, data)
335 self.assertRaises(binascii.Error, base64.b32decode, data_str)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000336
337 def test_b32decode_error(self):
Serhiy Storchakaea2b4902013-05-28 15:27:29 +0300338 for data in [b'abc', b'ABCDEF==', b'==ABCDEF']:
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100339 with self.assertRaises(binascii.Error):
340 base64.b32decode(data)
Antoine Pitroudff46fa2012-02-20 19:46:26 +0100341 with self.assertRaises(binascii.Error):
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100342 base64.b32decode(data.decode('ascii'))
Barry Warsaw4f019d32004-01-04 01:13:02 +0000343
344 def test_b16encode(self):
345 eq = self.assertEqual
Guido van Rossum4581ae52007-05-22 21:56:47 +0000346 eq(base64.b16encode(b'\x01\x02\xab\xcd\xef'), b'0102ABCDEF')
347 eq(base64.b16encode(b'\x00'), b'00')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300348 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000349 self.check_other_types(base64.b16encode, b'\x01\x02\xab\xcd\xef',
350 b'0102ABCDEF')
351 self.check_encode_type_errors(base64.b16encode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000352
353 def test_b16decode(self):
354 eq = self.assertEqual
Guido van Rossum4581ae52007-05-22 21:56:47 +0000355 eq(base64.b16decode(b'0102ABCDEF'), b'\x01\x02\xab\xcd\xef')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100356 eq(base64.b16decode('0102ABCDEF'), b'\x01\x02\xab\xcd\xef')
Guido van Rossum4581ae52007-05-22 21:56:47 +0000357 eq(base64.b16decode(b'00'), b'\x00')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100358 eq(base64.b16decode('00'), b'\x00')
Barry Warsaw4f019d32004-01-04 01:13:02 +0000359 # Lower case is not allowed without a flag
Guido van Rossum4581ae52007-05-22 21:56:47 +0000360 self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100361 self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef')
Barry Warsaw4f019d32004-01-04 01:13:02 +0000362 # Case fold
Guido van Rossum4581ae52007-05-22 21:56:47 +0000363 eq(base64.b16decode(b'0102abcdef', True), b'\x01\x02\xab\xcd\xef')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100364 eq(base64.b16decode('0102abcdef', True), b'\x01\x02\xab\xcd\xef')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300365 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000366 self.check_other_types(base64.b16decode, b"0102ABCDEF",
367 b'\x01\x02\xab\xcd\xef')
368 self.check_decode_type_errors(base64.b16decode)
369 eq(base64.b16decode(bytearray(b"0102abcdef"), True),
370 b'\x01\x02\xab\xcd\xef')
371 eq(base64.b16decode(memoryview(b"0102abcdef"), True),
372 b'\x01\x02\xab\xcd\xef')
373 eq(base64.b16decode(array('B', b"0102abcdef"), True),
374 b'\x01\x02\xab\xcd\xef')
Martin Panteree3074e2016-02-23 22:30:50 +0000375 # Non-alphabet characters
376 self.assertRaises(binascii.Error, base64.b16decode, '0102AG')
377 # Incorrect "padding"
378 self.assertRaises(binascii.Error, base64.b16decode, '010')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100379
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100380 def test_a85encode(self):
381 eq = self.assertEqual
382
383 tests = {
384 b'': b'',
385 b"www.python.org": b'GB\\6`E-ZP=Df.1GEb>',
386 bytes(range(255)): b"""!!*-'"9eu7#RLhG$k3[W&.oNg'GVB"(`=52*$$"""
387 b"""(B+<_pR,UFcb-n-Vr/1iJ-0JP==1c70M3&s#]4?Ykm5X@_(6q'R884cE"""
388 b"""H9MJ8X:f1+h<)lt#=BSg3>[:ZC?t!MSA7]@cBPD3sCi+'.E,fo>FEMbN"""
389 b"""G^4U^I!pHnJ:W<)KS>/9Ll%"IN/`jYOHG]iPa.Q$R$jD4S=Q7DTV8*TU"""
390 b"""nsrdW2ZetXKAY/Yd(L?['d?O\\@K2_]Y2%o^qmn*`5Ta:aN;TJbg"GZd"""
391 b"""*^:jeCE.%f\\,!5gtgiEi8N\\UjQ5OekiqBum-X60nF?)@o_%qPq"ad`"""
392 b"""r;HT""",
393 b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
394 b"0123456789!@#0^&*();:<>,. []{}":
395 b'@:E_WAS,RgBkhF"D/O92EH6,BF`qtRH$VbC6UX@47n?3D92&&T'
396 b":Jand;cHat='/U/0JP==1c70M3&r-I,;<FN.OZ`-3]oSW/g+A(H[P",
397 b"no padding..": b'DJpY:@:Wn_DJ(RS',
398 b"zero compression\0\0\0\0": b'H=_,8+Cf>,E,oN2F(oQ1z',
399 b"zero compression\0\0\0": b'H=_,8+Cf>,E,oN2F(oQ1!!!!',
400 b"Boundary:\0\0\0\0": b'6>q!aA79M(3WK-[!!',
401 b"Space compr: ": b';fH/TAKYK$D/aMV+<VdL',
402 b'\xff': b'rr',
403 b'\xff'*2: b's8N',
404 b'\xff'*3: b's8W*',
405 b'\xff'*4: b's8W-!',
406 }
407
408 for data, res in tests.items():
409 eq(base64.a85encode(data), res, data)
410 eq(base64.a85encode(data, adobe=False), res, data)
411 eq(base64.a85encode(data, adobe=True), b'<~' + res + b'~>', data)
412
413 self.check_other_types(base64.a85encode, b"www.python.org",
414 b'GB\\6`E-ZP=Df.1GEb>')
415
416 self.assertRaises(TypeError, base64.a85encode, "")
417
418 eq(base64.a85encode(b"www.python.org", wrapcol=7, adobe=False),
419 b'GB\\6`E-\nZP=Df.1\nGEb>')
420 eq(base64.a85encode(b"\0\0\0\0www.python.org", wrapcol=7, adobe=False),
421 b'zGB\\6`E\n-ZP=Df.\n1GEb>')
422 eq(base64.a85encode(b"www.python.org", wrapcol=7, adobe=True),
423 b'<~GB\\6`\nE-ZP=Df\n.1GEb>\n~>')
424
425 eq(base64.a85encode(b' '*8, foldspaces=True, adobe=False), b'yy')
426 eq(base64.a85encode(b' '*7, foldspaces=True, adobe=False), b'y+<Vd')
427 eq(base64.a85encode(b' '*6, foldspaces=True, adobe=False), b'y+<U')
428 eq(base64.a85encode(b' '*5, foldspaces=True, adobe=False), b'y+9')
429
430 def test_b85encode(self):
431 eq = self.assertEqual
432
433 tests = {
434 b'': b'',
435 b'www.python.org': b'cXxL#aCvlSZ*DGca%T',
436 bytes(range(255)): b"""009C61O)~M2nh-c3=Iws5D^j+6crX17#SKH9337X"""
437 b"""AR!_nBqb&%C@Cr{EG;fCFflSSG&MFiI5|2yJUu=?KtV!7L`6nNNJ&ad"""
438 b"""OifNtP*GA-R8>}2SXo+ITwPvYU}0ioWMyV&XlZI|Y;A6DaB*^Tbai%j"""
439 b"""czJqze0_d@fPsR8goTEOh>41ejE#<ukdcy;l$Dm3n3<ZJoSmMZprN9p"""
440 b"""q@|{(sHv)}tgWuEu(7hUw6(UkxVgH!yuH4^z`?@9#Kp$P$jQpf%+1cv"""
441 b"""(9zP<)YaD4*xB0K+}+;a;Njxq<mKk)=;`X~?CtLF@bU8V^!4`l`1$(#"""
442 b"""{Qdp""",
443 b"""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"""
444 b"""0123456789!@#0^&*();:<>,. []{}""":
445 b"""VPa!sWoBn+X=-b1ZEkOHadLBXb#`}nd3r%YLqtVJM@UIZOH55pPf$@("""
446 b"""Q&d$}S6EqEFflSSG&MFiI5{CeBQRbjDkv#CIy^osE+AW7dwl""",
447 b'no padding..': b'Zf_uPVPs@!Zf7no',
448 b'zero compression\x00\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG00000',
449 b'zero compression\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG0000',
450 b"""Boundary:\x00\x00\x00\x00""": b"""LT`0$WMOi7IsgCw00""",
451 b'Space compr: ': b'Q*dEpWgug3ZE$irARr(h',
452 b'\xff': b'{{',
453 b'\xff'*2: b'|Nj',
454 b'\xff'*3: b'|Ns9',
455 b'\xff'*4: b'|NsC0',
456 }
457
458 for data, res in tests.items():
459 eq(base64.b85encode(data), res)
460
461 self.check_other_types(base64.b85encode, b"www.python.org",
462 b'cXxL#aCvlSZ*DGca%T')
463
464 def test_a85decode(self):
465 eq = self.assertEqual
466
467 tests = {
468 b'': b'',
469 b'GB\\6`E-ZP=Df.1GEb>': b'www.python.org',
470 b"""! ! * -'"\n\t\t9eu\r\n7# RL\vhG$k3[W&.oNg'GVB"(`=52*$$"""
471 b"""(B+<_pR,UFcb-n-Vr/1iJ-0JP==1c70M3&s#]4?Ykm5X@_(6q'R884cE"""
472 b"""H9MJ8X:f1+h<)lt#=BSg3>[:ZC?t!MSA7]@cBPD3sCi+'.E,fo>FEMbN"""
473 b"""G^4U^I!pHnJ:W<)KS>/9Ll%"IN/`jYOHG]iPa.Q$R$jD4S=Q7DTV8*TU"""
474 b"""nsrdW2ZetXKAY/Yd(L?['d?O\\@K2_]Y2%o^qmn*`5Ta:aN;TJbg"GZd"""
475 b"""*^:jeCE.%f\\,!5gtgiEi8N\\UjQ5OekiqBum-X60nF?)@o_%qPq"ad`"""
476 b"""r;HT""": bytes(range(255)),
477 b"""@:E_WAS,RgBkhF"D/O92EH6,BF`qtRH$VbC6UX@47n?3D92&&T:Jand;c"""
478 b"""Hat='/U/0JP==1c70M3&r-I,;<FN.OZ`-3]oSW/g+A(H[P""":
479 b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234'
480 b'56789!@#0^&*();:<>,. []{}',
481 b'DJpY:@:Wn_DJ(RS': b'no padding..',
482 b'H=_,8+Cf>,E,oN2F(oQ1z': b'zero compression\x00\x00\x00\x00',
483 b'H=_,8+Cf>,E,oN2F(oQ1!!!!': b'zero compression\x00\x00\x00',
484 b'6>q!aA79M(3WK-[!!': b"Boundary:\x00\x00\x00\x00",
485 b';fH/TAKYK$D/aMV+<VdL': b'Space compr: ',
486 b'rr': b'\xff',
487 b's8N': b'\xff'*2,
488 b's8W*': b'\xff'*3,
489 b's8W-!': b'\xff'*4,
490 }
491
492 for data, res in tests.items():
493 eq(base64.a85decode(data), res, data)
494 eq(base64.a85decode(data, adobe=False), res, data)
495 eq(base64.a85decode(data.decode("ascii"), adobe=False), res, data)
496 eq(base64.a85decode(b'<~' + data + b'~>', adobe=True), res, data)
Serhiy Storchaka205e75b2016-02-24 12:05:50 +0200497 eq(base64.a85decode(data + b'~>', adobe=True), res, data)
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100498 eq(base64.a85decode('<~%s~>' % data.decode("ascii"), adobe=True),
499 res, data)
500
501 eq(base64.a85decode(b'yy', foldspaces=True, adobe=False), b' '*8)
502 eq(base64.a85decode(b'y+<Vd', foldspaces=True, adobe=False), b' '*7)
503 eq(base64.a85decode(b'y+<U', foldspaces=True, adobe=False), b' '*6)
504 eq(base64.a85decode(b'y+9', foldspaces=True, adobe=False), b' '*5)
505
506 self.check_other_types(base64.a85decode, b'GB\\6`E-ZP=Df.1GEb>',
507 b"www.python.org")
508
509 def test_b85decode(self):
510 eq = self.assertEqual
511
512 tests = {
513 b'': b'',
514 b'cXxL#aCvlSZ*DGca%T': b'www.python.org',
515 b"""009C61O)~M2nh-c3=Iws5D^j+6crX17#SKH9337X"""
516 b"""AR!_nBqb&%C@Cr{EG;fCFflSSG&MFiI5|2yJUu=?KtV!7L`6nNNJ&ad"""
517 b"""OifNtP*GA-R8>}2SXo+ITwPvYU}0ioWMyV&XlZI|Y;A6DaB*^Tbai%j"""
518 b"""czJqze0_d@fPsR8goTEOh>41ejE#<ukdcy;l$Dm3n3<ZJoSmMZprN9p"""
519 b"""q@|{(sHv)}tgWuEu(7hUw6(UkxVgH!yuH4^z`?@9#Kp$P$jQpf%+1cv"""
520 b"""(9zP<)YaD4*xB0K+}+;a;Njxq<mKk)=;`X~?CtLF@bU8V^!4`l`1$(#"""
521 b"""{Qdp""": bytes(range(255)),
522 b"""VPa!sWoBn+X=-b1ZEkOHadLBXb#`}nd3r%YLqtVJM@UIZOH55pPf$@("""
523 b"""Q&d$}S6EqEFflSSG&MFiI5{CeBQRbjDkv#CIy^osE+AW7dwl""":
524 b"""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"""
525 b"""0123456789!@#0^&*();:<>,. []{}""",
526 b'Zf_uPVPs@!Zf7no': b'no padding..',
527 b'dS!BNAY*TBaB^jHb7^mG00000': b'zero compression\x00\x00\x00\x00',
528 b'dS!BNAY*TBaB^jHb7^mG0000': b'zero compression\x00\x00\x00',
529 b"""LT`0$WMOi7IsgCw00""": b"""Boundary:\x00\x00\x00\x00""",
530 b'Q*dEpWgug3ZE$irARr(h': b'Space compr: ',
531 b'{{': b'\xff',
532 b'|Nj': b'\xff'*2,
533 b'|Ns9': b'\xff'*3,
534 b'|NsC0': b'\xff'*4,
535 }
536
537 for data, res in tests.items():
538 eq(base64.b85decode(data), res)
539 eq(base64.b85decode(data.decode("ascii")), res)
540
541 self.check_other_types(base64.b85decode, b'cXxL#aCvlSZ*DGca%T',
542 b"www.python.org")
543
544 def test_a85_padding(self):
545 eq = self.assertEqual
546
547 eq(base64.a85encode(b"x", pad=True), b'GQ7^D')
548 eq(base64.a85encode(b"xx", pad=True), b"G^'2g")
549 eq(base64.a85encode(b"xxx", pad=True), b'G^+H5')
550 eq(base64.a85encode(b"xxxx", pad=True), b'G^+IX')
551 eq(base64.a85encode(b"xxxxx", pad=True), b'G^+IXGQ7^D')
552
553 eq(base64.a85decode(b'GQ7^D'), b"x\x00\x00\x00")
554 eq(base64.a85decode(b"G^'2g"), b"xx\x00\x00")
555 eq(base64.a85decode(b'G^+H5'), b"xxx\x00")
556 eq(base64.a85decode(b'G^+IX'), b"xxxx")
557 eq(base64.a85decode(b'G^+IXGQ7^D'), b"xxxxx\x00\x00\x00")
558
559 def test_b85_padding(self):
560 eq = self.assertEqual
561
562 eq(base64.b85encode(b"x", pad=True), b'cmMzZ')
563 eq(base64.b85encode(b"xx", pad=True), b'cz6H+')
564 eq(base64.b85encode(b"xxx", pad=True), b'czAdK')
565 eq(base64.b85encode(b"xxxx", pad=True), b'czAet')
566 eq(base64.b85encode(b"xxxxx", pad=True), b'czAetcmMzZ')
567
568 eq(base64.b85decode(b'cmMzZ'), b"x\x00\x00\x00")
569 eq(base64.b85decode(b'cz6H+'), b"xx\x00\x00")
570 eq(base64.b85decode(b'czAdK'), b"xxx\x00")
571 eq(base64.b85decode(b'czAet'), b"xxxx")
572 eq(base64.b85decode(b'czAetcmMzZ'), b"xxxxx\x00\x00\x00")
573
574 def test_a85decode_errors(self):
575 illegal = (set(range(32)) | set(range(118, 256))) - set(b' \t\n\r\v')
576 for c in illegal:
577 with self.assertRaises(ValueError, msg=bytes([c])):
578 base64.a85decode(b'!!!!' + bytes([c]))
579 with self.assertRaises(ValueError, msg=bytes([c])):
580 base64.a85decode(b'!!!!' + bytes([c]), adobe=False)
581 with self.assertRaises(ValueError, msg=bytes([c])):
582 base64.a85decode(b'<~!!!!' + bytes([c]) + b'~>', adobe=True)
583
584 self.assertRaises(ValueError, base64.a85decode,
585 b"malformed", adobe=True)
586 self.assertRaises(ValueError, base64.a85decode,
587 b"<~still malformed", adobe=True)
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100588
589 # With adobe=False (the default), Adobe framing markers are disallowed
590 self.assertRaises(ValueError, base64.a85decode,
591 b"<~~>")
592 self.assertRaises(ValueError, base64.a85decode,
593 b"<~~>", adobe=False)
594 base64.a85decode(b"<~~>", adobe=True) # sanity check
595
596 self.assertRaises(ValueError, base64.a85decode,
597 b"abcx", adobe=False)
598 self.assertRaises(ValueError, base64.a85decode,
599 b"abcdey", adobe=False)
600 self.assertRaises(ValueError, base64.a85decode,
601 b"a b\nc", adobe=False, ignorechars=b"")
602
603 self.assertRaises(ValueError, base64.a85decode, b's', adobe=False)
604 self.assertRaises(ValueError, base64.a85decode, b's8', adobe=False)
605 self.assertRaises(ValueError, base64.a85decode, b's8W', adobe=False)
606 self.assertRaises(ValueError, base64.a85decode, b's8W-', adobe=False)
607 self.assertRaises(ValueError, base64.a85decode, b's8W-"', adobe=False)
608
609 def test_b85decode_errors(self):
610 illegal = list(range(33)) + \
611 list(b'"\',./:[\\]') + \
612 list(range(128, 256))
613 for c in illegal:
614 with self.assertRaises(ValueError, msg=bytes([c])):
615 base64.b85decode(b'0000' + bytes([c]))
616
617 self.assertRaises(ValueError, base64.b85decode, b'|')
618 self.assertRaises(ValueError, base64.b85decode, b'|N')
619 self.assertRaises(ValueError, base64.b85decode, b'|Ns')
620 self.assertRaises(ValueError, base64.b85decode, b'|NsC')
621 self.assertRaises(ValueError, base64.b85decode, b'|NsC1')
622
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100623 def test_decode_nonascii_str(self):
624 decode_funcs = (base64.b64decode,
625 base64.standard_b64decode,
626 base64.urlsafe_b64decode,
627 base64.b32decode,
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100628 base64.b16decode,
629 base64.b85decode,
630 base64.a85decode)
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100631 for f in decode_funcs:
632 self.assertRaises(ValueError, f, 'with non-ascii \xcb')
Guido van Rossum4581ae52007-05-22 21:56:47 +0000633
634 def test_ErrorHeritage(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000635 self.assertTrue(issubclass(binascii.Error, ValueError))
Barry Warsaw4f019d32004-01-04 01:13:02 +0000636
637
Victor Stinner479736b2010-05-25 21:12:34 +0000638class TestMain(unittest.TestCase):
Vinay Sajipf9596182012-03-02 01:01:13 +0000639 def tearDown(self):
640 if os.path.exists(support.TESTFN):
641 os.unlink(support.TESTFN)
642
Berker Peksag00f81972015-07-25 14:14:24 +0300643 def get_output(self, *args):
644 return script_helper.assert_python_ok('-m', 'base64', *args).out
Victor Stinner479736b2010-05-25 21:12:34 +0000645
646 def test_encode_decode(self):
647 output = self.get_output('-t')
648 self.assertSequenceEqual(output.splitlines(), (
649 b"b'Aladdin:open sesame'",
650 br"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\n'",
651 b"b'Aladdin:open sesame'",
652 ))
653
654 def test_encode_file(self):
655 with open(support.TESTFN, 'wb') as fp:
656 fp.write(b'a\xffb\n')
Victor Stinner479736b2010-05-25 21:12:34 +0000657 output = self.get_output('-e', support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000658 self.assertEqual(output.rstrip(), b'Yf9iCg==')
Victor Stinner479736b2010-05-25 21:12:34 +0000659
Berker Peksag00f81972015-07-25 14:14:24 +0300660 def test_encode_from_stdin(self):
661 with script_helper.spawn_python('-m', 'base64', '-e') as proc:
662 out, err = proc.communicate(b'a\xffb\n')
663 self.assertEqual(out.rstrip(), b'Yf9iCg==')
664 self.assertIsNone(err)
Victor Stinner479736b2010-05-25 21:12:34 +0000665
666 def test_decode(self):
667 with open(support.TESTFN, 'wb') as fp:
668 fp.write(b'Yf9iCg==')
669 output = self.get_output('-d', support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000670 self.assertEqual(output.rstrip(), b'a\xffb')
Victor Stinner479736b2010-05-25 21:12:34 +0000671
Barry Warsaw4f019d32004-01-04 01:13:02 +0000672if __name__ == '__main__':
Berker Peksag00f81972015-07-25 14:14:24 +0300673 unittest.main()