blob: 2a4cc2acad24b1b32c6d91aca27db9748edeee90 [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
Matthias Bussonnierc643a962017-03-02 06:21:26 -080021 def test_encodestring_warns(self):
22 with self.assertWarns(DeprecationWarning):
23 base64.encodestring(b"www.python.org")
24
25 def test_decodestring_warns(self):
26 with self.assertWarns(DeprecationWarning):
27 base64.decodestring(b"d3d3LnB5dGhvbi5vcmc=\n")
28
Georg Brandlb54d8012009-06-04 09:11:51 +000029 def test_encodebytes(self):
Barry Warsaw4f019d32004-01-04 01:13:02 +000030 eq = self.assertEqual
Georg Brandlb54d8012009-06-04 09:11:51 +000031 eq(base64.encodebytes(b"www.python.org"), b"d3d3LnB5dGhvbi5vcmc=\n")
32 eq(base64.encodebytes(b"a"), b"YQ==\n")
33 eq(base64.encodebytes(b"ab"), b"YWI=\n")
34 eq(base64.encodebytes(b"abc"), b"YWJj\n")
35 eq(base64.encodebytes(b""), b"")
36 eq(base64.encodebytes(b"abcdefghijklmnopqrstuvwxyz"
Guido van Rossum4581ae52007-05-22 21:56:47 +000037 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
38 b"0123456789!@#0^&*();:<>,. []{}"),
39 b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
40 b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
41 b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n")
Serhiy Storchaka017523c2013-04-28 15:53:08 +030042 # Non-bytes
43 eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\n')
Nick Coghlanfdf239a2013-10-03 00:43:22 +100044 eq(base64.encodebytes(memoryview(b'abc')), b'YWJj\n')
45 eq(base64.encodebytes(array('B', b'abc')), b'YWJj\n')
46 self.check_type_errors(base64.encodebytes)
Guido van Rossumcb682582002-08-22 19:18:56 +000047
Georg Brandlb54d8012009-06-04 09:11:51 +000048 def test_decodebytes(self):
Barry Warsaw4f019d32004-01-04 01:13:02 +000049 eq = self.assertEqual
Georg Brandlb54d8012009-06-04 09:11:51 +000050 eq(base64.decodebytes(b"d3d3LnB5dGhvbi5vcmc=\n"), b"www.python.org")
51 eq(base64.decodebytes(b"YQ==\n"), b"a")
52 eq(base64.decodebytes(b"YWI=\n"), b"ab")
53 eq(base64.decodebytes(b"YWJj\n"), b"abc")
54 eq(base64.decodebytes(b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
Guido van Rossum4581ae52007-05-22 21:56:47 +000055 b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
56 b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n"),
57 b"abcdefghijklmnopqrstuvwxyz"
58 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
59 b"0123456789!@#0^&*();:<>,. []{}")
Georg Brandlb54d8012009-06-04 09:11:51 +000060 eq(base64.decodebytes(b''), b'')
Serhiy Storchaka017523c2013-04-28 15:53:08 +030061 # Non-bytes
62 eq(base64.decodebytes(bytearray(b'YWJj\n')), b'abc')
Nick Coghlanfdf239a2013-10-03 00:43:22 +100063 eq(base64.decodebytes(memoryview(b'YWJj\n')), b'abc')
64 eq(base64.decodebytes(array('B', b'YWJj\n')), b'abc')
65 self.check_type_errors(base64.decodebytes)
Barry Warsaw4f019d32004-01-04 01:13:02 +000066
67 def test_encode(self):
68 eq = self.assertEqual
Serhiy Storchakaabac0a72013-04-28 15:56:11 +030069 from io import BytesIO, StringIO
Guido van Rossum34d19282007-08-09 01:03:29 +000070 infp = BytesIO(b'abcdefghijklmnopqrstuvwxyz'
71 b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
72 b'0123456789!@#0^&*();:<>,. []{}')
73 outfp = BytesIO()
Barry Warsaw4f019d32004-01-04 01:13:02 +000074 base64.encode(infp, outfp)
75 eq(outfp.getvalue(),
Guido van Rossum34d19282007-08-09 01:03:29 +000076 b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE'
77 b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT'
78 b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n')
Serhiy Storchakaabac0a72013-04-28 15:56:11 +030079 # Non-binary files
80 self.assertRaises(TypeError, base64.encode, StringIO('abc'), BytesIO())
81 self.assertRaises(TypeError, base64.encode, BytesIO(b'abc'), StringIO())
82 self.assertRaises(TypeError, base64.encode, StringIO('abc'), StringIO())
Barry Warsaw4f019d32004-01-04 01:13:02 +000083
84 def test_decode(self):
Serhiy Storchakaabac0a72013-04-28 15:56:11 +030085 from io import BytesIO, StringIO
Guido van Rossum34d19282007-08-09 01:03:29 +000086 infp = BytesIO(b'd3d3LnB5dGhvbi5vcmc=')
87 outfp = BytesIO()
Barry Warsaw4f019d32004-01-04 01:13:02 +000088 base64.decode(infp, outfp)
Guido van Rossum34d19282007-08-09 01:03:29 +000089 self.assertEqual(outfp.getvalue(), b'www.python.org')
Serhiy Storchakaabac0a72013-04-28 15:56:11 +030090 # Non-binary files
91 self.assertRaises(TypeError, base64.encode, StringIO('YWJj\n'), BytesIO())
92 self.assertRaises(TypeError, base64.encode, BytesIO(b'YWJj\n'), StringIO())
93 self.assertRaises(TypeError, base64.encode, StringIO('YWJj\n'), StringIO())
Barry Warsaw4f019d32004-01-04 01:13:02 +000094
Ezio Melottib3aedd42010-11-20 19:04:17 +000095
Barry Warsaw4f019d32004-01-04 01:13:02 +000096class BaseXYTestCase(unittest.TestCase):
Nick Coghlanfdf239a2013-10-03 00:43:22 +100097
98 # Modern API completely ignores exported dimension and format data and
99 # treats any buffer as a stream of bytes
100 def check_encode_type_errors(self, f):
101 self.assertRaises(TypeError, f, "")
102 self.assertRaises(TypeError, f, [])
103
104 def check_decode_type_errors(self, f):
105 self.assertRaises(TypeError, f, [])
106
107 def check_other_types(self, f, bytes_data, expected):
108 eq = self.assertEqual
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100109 b = bytearray(bytes_data)
110 eq(f(b), expected)
111 # The bytearray wasn't mutated
112 eq(b, bytes_data)
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000113 eq(f(memoryview(bytes_data)), expected)
114 eq(f(array('B', bytes_data)), expected)
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100115 # XXX why is b64encode hardcoded here?
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000116 self.check_nonbyte_element_format(base64.b64encode, bytes_data)
117 self.check_multidimensional(base64.b64encode, bytes_data)
118
119 def check_multidimensional(self, f, data):
120 padding = b"\x00" if len(data) % 2 else b""
121 bytes_data = data + padding # Make sure cast works
122 shape = (len(bytes_data) // 2, 2)
123 multidimensional = memoryview(bytes_data).cast('B', shape)
124 self.assertEqual(f(multidimensional), f(bytes_data))
125
126 def check_nonbyte_element_format(self, f, data):
127 padding = b"\x00" * ((4 - len(data)) % 4)
128 bytes_data = data + padding # Make sure cast works
129 int_data = memoryview(bytes_data).cast('I')
130 self.assertEqual(f(int_data), f(bytes_data))
131
132
Barry Warsaw4f019d32004-01-04 01:13:02 +0000133 def test_b64encode(self):
134 eq = self.assertEqual
135 # Test default alphabet
Guido van Rossum4581ae52007-05-22 21:56:47 +0000136 eq(base64.b64encode(b"www.python.org"), b"d3d3LnB5dGhvbi5vcmc=")
137 eq(base64.b64encode(b'\x00'), b'AA==')
138 eq(base64.b64encode(b"a"), b"YQ==")
139 eq(base64.b64encode(b"ab"), b"YWI=")
140 eq(base64.b64encode(b"abc"), b"YWJj")
141 eq(base64.b64encode(b""), b"")
142 eq(base64.b64encode(b"abcdefghijklmnopqrstuvwxyz"
143 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
144 b"0123456789!@#0^&*();:<>,. []{}"),
145 b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
146 b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
147 b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
Barry Warsaw4f019d32004-01-04 01:13:02 +0000148 # Test with arbitrary alternative characters
Alexandre Vassalotti5209857f2008-05-03 04:39:38 +0000149 eq(base64.b64encode(b'\xd3V\xbeo\xf7\x1d', altchars=b'*$'), b'01a*b$cd')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300150 eq(base64.b64encode(b'\xd3V\xbeo\xf7\x1d', altchars=bytearray(b'*$')),
151 b'01a*b$cd')
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000152 eq(base64.b64encode(b'\xd3V\xbeo\xf7\x1d', altchars=memoryview(b'*$')),
153 b'01a*b$cd')
154 eq(base64.b64encode(b'\xd3V\xbeo\xf7\x1d', altchars=array('B', b'*$')),
155 b'01a*b$cd')
156 # Non-bytes
157 self.check_other_types(base64.b64encode, b'abcd', b'YWJjZA==')
158 self.check_encode_type_errors(base64.b64encode)
159 self.assertRaises(TypeError, base64.b64encode, b"", altchars="*$")
Barry Warsaw4f019d32004-01-04 01:13:02 +0000160 # Test standard alphabet
Guido van Rossum4581ae52007-05-22 21:56:47 +0000161 eq(base64.standard_b64encode(b"www.python.org"), b"d3d3LnB5dGhvbi5vcmc=")
162 eq(base64.standard_b64encode(b"a"), b"YQ==")
163 eq(base64.standard_b64encode(b"ab"), b"YWI=")
164 eq(base64.standard_b64encode(b"abc"), b"YWJj")
165 eq(base64.standard_b64encode(b""), b"")
166 eq(base64.standard_b64encode(b"abcdefghijklmnopqrstuvwxyz"
167 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
168 b"0123456789!@#0^&*();:<>,. []{}"),
169 b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
170 b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
171 b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300172 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000173 self.check_other_types(base64.standard_b64encode,
174 b'abcd', b'YWJjZA==')
175 self.check_encode_type_errors(base64.standard_b64encode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000176 # Test with 'URL safe' alternative characters
Guido van Rossum4581ae52007-05-22 21:56:47 +0000177 eq(base64.urlsafe_b64encode(b'\xd3V\xbeo\xf7\x1d'), b'01a-b_cd')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300178 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000179 self.check_other_types(base64.urlsafe_b64encode,
180 b'\xd3V\xbeo\xf7\x1d', b'01a-b_cd')
181 self.check_encode_type_errors(base64.urlsafe_b64encode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000182
183 def test_b64decode(self):
184 eq = self.assertEqual
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100185
186 tests = {b"d3d3LnB5dGhvbi5vcmc=": b"www.python.org",
187 b'AA==': b'\x00',
188 b"YQ==": b"a",
189 b"YWI=": b"ab",
190 b"YWJj": b"abc",
191 b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
192 b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
193 b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==":
194
195 b"abcdefghijklmnopqrstuvwxyz"
196 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
197 b"0123456789!@#0^&*();:<>,. []{}",
198 b'': b'',
199 }
200 for data, res in tests.items():
201 eq(base64.b64decode(data), res)
202 eq(base64.b64decode(data.decode('ascii')), res)
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300203 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000204 self.check_other_types(base64.b64decode, b"YWJj", b"abc")
205 self.check_decode_type_errors(base64.b64decode)
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100206
Barry Warsaw4f019d32004-01-04 01:13:02 +0000207 # Test with arbitrary alternative characters
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100208 tests_altchars = {(b'01a*b$cd', b'*$'): b'\xd3V\xbeo\xf7\x1d',
209 }
210 for (data, altchars), res in tests_altchars.items():
211 data_str = data.decode('ascii')
212 altchars_str = altchars.decode('ascii')
213
214 eq(base64.b64decode(data, altchars=altchars), res)
215 eq(base64.b64decode(data_str, altchars=altchars), res)
216 eq(base64.b64decode(data, altchars=altchars_str), res)
217 eq(base64.b64decode(data_str, altchars=altchars_str), res)
218
Barry Warsaw4f019d32004-01-04 01:13:02 +0000219 # Test standard alphabet
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100220 for data, res in tests.items():
221 eq(base64.standard_b64decode(data), res)
222 eq(base64.standard_b64decode(data.decode('ascii')), res)
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300223 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000224 self.check_other_types(base64.standard_b64decode, b"YWJj", b"abc")
225 self.check_decode_type_errors(base64.standard_b64decode)
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100226
Barry Warsaw4f019d32004-01-04 01:13:02 +0000227 # Test with 'URL safe' alternative characters
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100228 tests_urlsafe = {b'01a-b_cd': b'\xd3V\xbeo\xf7\x1d',
229 b'': b'',
230 }
231 for data, res in tests_urlsafe.items():
232 eq(base64.urlsafe_b64decode(data), res)
233 eq(base64.urlsafe_b64decode(data.decode('ascii')), res)
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300234 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000235 self.check_other_types(base64.urlsafe_b64decode, b'01a-b_cd',
236 b'\xd3V\xbeo\xf7\x1d')
237 self.check_decode_type_errors(base64.urlsafe_b64decode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000238
R. David Murray64951362010-11-11 20:09:20 +0000239 def test_b64decode_padding_error(self):
Guido van Rossum4581ae52007-05-22 21:56:47 +0000240 self.assertRaises(binascii.Error, base64.b64decode, b'abc')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100241 self.assertRaises(binascii.Error, base64.b64decode, 'abc')
Barry Warsaw4f019d32004-01-04 01:13:02 +0000242
R. David Murray64951362010-11-11 20:09:20 +0000243 def test_b64decode_invalid_chars(self):
244 # issue 1466065: Test some invalid characters.
245 tests = ((b'%3d==', b'\xdd'),
246 (b'$3d==', b'\xdd'),
247 (b'[==', b''),
248 (b'YW]3=', b'am'),
249 (b'3{d==', b'\xdd'),
250 (b'3d}==', b'\xdd'),
251 (b'@@', b''),
252 (b'!', b''),
253 (b'YWJj\nYWI=', b'abcab'))
Martin Panteree3074e2016-02-23 22:30:50 +0000254 funcs = (
255 base64.b64decode,
256 base64.standard_b64decode,
257 base64.urlsafe_b64decode,
258 )
R. David Murray64951362010-11-11 20:09:20 +0000259 for bstr, res in tests:
Martin Panteree3074e2016-02-23 22:30:50 +0000260 for func in funcs:
261 with self.subTest(bstr=bstr, func=func):
262 self.assertEqual(func(bstr), res)
263 self.assertEqual(func(bstr.decode('ascii')), res)
R. David Murray64951362010-11-11 20:09:20 +0000264 with self.assertRaises(binascii.Error):
265 base64.b64decode(bstr, validate=True)
Antoine Pitroudff46fa2012-02-20 19:46:26 +0100266 with self.assertRaises(binascii.Error):
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100267 base64.b64decode(bstr.decode('ascii'), validate=True)
R. David Murray64951362010-11-11 20:09:20 +0000268
Martin Panteree3074e2016-02-23 22:30:50 +0000269 # Normal alphabet characters not discarded when alternative given
270 res = b'\xFB\xEF\xBE\xFF\xFF\xFF'
271 self.assertEqual(base64.b64decode(b'++[[//]]', b'[]'), res)
272 self.assertEqual(base64.urlsafe_b64decode(b'++--//__'), res)
273
Barry Warsaw4f019d32004-01-04 01:13:02 +0000274 def test_b32encode(self):
275 eq = self.assertEqual
Guido van Rossum4581ae52007-05-22 21:56:47 +0000276 eq(base64.b32encode(b''), b'')
277 eq(base64.b32encode(b'\x00'), b'AA======')
278 eq(base64.b32encode(b'a'), b'ME======')
279 eq(base64.b32encode(b'ab'), b'MFRA====')
280 eq(base64.b32encode(b'abc'), b'MFRGG===')
281 eq(base64.b32encode(b'abcd'), b'MFRGGZA=')
282 eq(base64.b32encode(b'abcde'), b'MFRGGZDF')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300283 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000284 self.check_other_types(base64.b32encode, b'abcd', b'MFRGGZA=')
285 self.check_encode_type_errors(base64.b32encode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000286
287 def test_b32decode(self):
288 eq = self.assertEqual
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100289 tests = {b'': b'',
290 b'AA======': b'\x00',
291 b'ME======': b'a',
292 b'MFRA====': b'ab',
293 b'MFRGG===': b'abc',
294 b'MFRGGZA=': b'abcd',
295 b'MFRGGZDF': b'abcde',
296 }
297 for data, res in tests.items():
298 eq(base64.b32decode(data), res)
299 eq(base64.b32decode(data.decode('ascii')), res)
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300300 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000301 self.check_other_types(base64.b32decode, b'MFRGG===', b"abc")
302 self.check_decode_type_errors(base64.b32decode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000303
304 def test_b32decode_casefold(self):
305 eq = self.assertEqual
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100306 tests = {b'': b'',
307 b'ME======': b'a',
308 b'MFRA====': b'ab',
309 b'MFRGG===': b'abc',
310 b'MFRGGZA=': b'abcd',
311 b'MFRGGZDF': b'abcde',
312 # Lower cases
313 b'me======': b'a',
314 b'mfra====': b'ab',
315 b'mfrgg===': b'abc',
316 b'mfrggza=': b'abcd',
317 b'mfrggzdf': b'abcde',
318 }
319
320 for data, res in tests.items():
321 eq(base64.b32decode(data, True), res)
322 eq(base64.b32decode(data.decode('ascii'), True), res)
323
Serhiy Storchakaea2b4902013-05-28 15:27:29 +0300324 self.assertRaises(binascii.Error, base64.b32decode, b'me======')
325 self.assertRaises(binascii.Error, base64.b32decode, 'me======')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100326
Barry Warsaw4f019d32004-01-04 01:13:02 +0000327 # Mapping zero and one
Guido van Rossum4581ae52007-05-22 21:56:47 +0000328 eq(base64.b32decode(b'MLO23456'), b'b\xdd\xad\xf3\xbe')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100329 eq(base64.b32decode('MLO23456'), b'b\xdd\xad\xf3\xbe')
330
331 map_tests = {(b'M1023456', b'L'): b'b\xdd\xad\xf3\xbe',
332 (b'M1023456', b'I'): b'b\x1d\xad\xf3\xbe',
333 }
334 for (data, map01), res in map_tests.items():
335 data_str = data.decode('ascii')
336 map01_str = map01.decode('ascii')
337
338 eq(base64.b32decode(data, map01=map01), res)
339 eq(base64.b32decode(data_str, map01=map01), res)
340 eq(base64.b32decode(data, map01=map01_str), res)
341 eq(base64.b32decode(data_str, map01=map01_str), res)
Serhiy Storchakaea2b4902013-05-28 15:27:29 +0300342 self.assertRaises(binascii.Error, base64.b32decode, data)
343 self.assertRaises(binascii.Error, base64.b32decode, data_str)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000344
345 def test_b32decode_error(self):
Serhiy Storchakaac0b3c22018-07-24 12:52:51 +0300346 tests = [b'abc', b'ABCDEF==', b'==ABCDEF']
347 prefixes = [b'M', b'ME', b'MFRA', b'MFRGG', b'MFRGGZA', b'MFRGGZDF']
348 for i in range(0, 17):
349 if i:
350 tests.append(b'='*i)
351 for prefix in prefixes:
352 if len(prefix) + i != 8:
353 tests.append(prefix + b'='*i)
354 for data in tests:
355 with self.subTest(data=data):
356 with self.assertRaises(binascii.Error):
357 base64.b32decode(data)
358 with self.assertRaises(binascii.Error):
359 base64.b32decode(data.decode('ascii'))
Barry Warsaw4f019d32004-01-04 01:13:02 +0000360
361 def test_b16encode(self):
362 eq = self.assertEqual
Guido van Rossum4581ae52007-05-22 21:56:47 +0000363 eq(base64.b16encode(b'\x01\x02\xab\xcd\xef'), b'0102ABCDEF')
364 eq(base64.b16encode(b'\x00'), b'00')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300365 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000366 self.check_other_types(base64.b16encode, b'\x01\x02\xab\xcd\xef',
367 b'0102ABCDEF')
368 self.check_encode_type_errors(base64.b16encode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000369
370 def test_b16decode(self):
371 eq = self.assertEqual
Guido van Rossum4581ae52007-05-22 21:56:47 +0000372 eq(base64.b16decode(b'0102ABCDEF'), b'\x01\x02\xab\xcd\xef')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100373 eq(base64.b16decode('0102ABCDEF'), b'\x01\x02\xab\xcd\xef')
Guido van Rossum4581ae52007-05-22 21:56:47 +0000374 eq(base64.b16decode(b'00'), b'\x00')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100375 eq(base64.b16decode('00'), b'\x00')
Barry Warsaw4f019d32004-01-04 01:13:02 +0000376 # Lower case is not allowed without a flag
Guido van Rossum4581ae52007-05-22 21:56:47 +0000377 self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100378 self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef')
Barry Warsaw4f019d32004-01-04 01:13:02 +0000379 # Case fold
Guido van Rossum4581ae52007-05-22 21:56:47 +0000380 eq(base64.b16decode(b'0102abcdef', True), b'\x01\x02\xab\xcd\xef')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100381 eq(base64.b16decode('0102abcdef', True), b'\x01\x02\xab\xcd\xef')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300382 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000383 self.check_other_types(base64.b16decode, b"0102ABCDEF",
384 b'\x01\x02\xab\xcd\xef')
385 self.check_decode_type_errors(base64.b16decode)
386 eq(base64.b16decode(bytearray(b"0102abcdef"), True),
387 b'\x01\x02\xab\xcd\xef')
388 eq(base64.b16decode(memoryview(b"0102abcdef"), True),
389 b'\x01\x02\xab\xcd\xef')
390 eq(base64.b16decode(array('B', b"0102abcdef"), True),
391 b'\x01\x02\xab\xcd\xef')
Martin Panteree3074e2016-02-23 22:30:50 +0000392 # Non-alphabet characters
393 self.assertRaises(binascii.Error, base64.b16decode, '0102AG')
394 # Incorrect "padding"
395 self.assertRaises(binascii.Error, base64.b16decode, '010')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100396
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100397 def test_a85encode(self):
398 eq = self.assertEqual
399
400 tests = {
401 b'': b'',
402 b"www.python.org": b'GB\\6`E-ZP=Df.1GEb>',
403 bytes(range(255)): b"""!!*-'"9eu7#RLhG$k3[W&.oNg'GVB"(`=52*$$"""
404 b"""(B+<_pR,UFcb-n-Vr/1iJ-0JP==1c70M3&s#]4?Ykm5X@_(6q'R884cE"""
405 b"""H9MJ8X:f1+h<)lt#=BSg3>[:ZC?t!MSA7]@cBPD3sCi+'.E,fo>FEMbN"""
406 b"""G^4U^I!pHnJ:W<)KS>/9Ll%"IN/`jYOHG]iPa.Q$R$jD4S=Q7DTV8*TU"""
407 b"""nsrdW2ZetXKAY/Yd(L?['d?O\\@K2_]Y2%o^qmn*`5Ta:aN;TJbg"GZd"""
408 b"""*^:jeCE.%f\\,!5gtgiEi8N\\UjQ5OekiqBum-X60nF?)@o_%qPq"ad`"""
409 b"""r;HT""",
410 b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
411 b"0123456789!@#0^&*();:<>,. []{}":
412 b'@:E_WAS,RgBkhF"D/O92EH6,BF`qtRH$VbC6UX@47n?3D92&&T'
413 b":Jand;cHat='/U/0JP==1c70M3&r-I,;<FN.OZ`-3]oSW/g+A(H[P",
414 b"no padding..": b'DJpY:@:Wn_DJ(RS',
415 b"zero compression\0\0\0\0": b'H=_,8+Cf>,E,oN2F(oQ1z',
416 b"zero compression\0\0\0": b'H=_,8+Cf>,E,oN2F(oQ1!!!!',
417 b"Boundary:\0\0\0\0": b'6>q!aA79M(3WK-[!!',
418 b"Space compr: ": b';fH/TAKYK$D/aMV+<VdL',
419 b'\xff': b'rr',
420 b'\xff'*2: b's8N',
421 b'\xff'*3: b's8W*',
422 b'\xff'*4: b's8W-!',
423 }
424
425 for data, res in tests.items():
426 eq(base64.a85encode(data), res, data)
427 eq(base64.a85encode(data, adobe=False), res, data)
428 eq(base64.a85encode(data, adobe=True), b'<~' + res + b'~>', data)
429
430 self.check_other_types(base64.a85encode, b"www.python.org",
431 b'GB\\6`E-ZP=Df.1GEb>')
432
433 self.assertRaises(TypeError, base64.a85encode, "")
434
435 eq(base64.a85encode(b"www.python.org", wrapcol=7, adobe=False),
436 b'GB\\6`E-\nZP=Df.1\nGEb>')
437 eq(base64.a85encode(b"\0\0\0\0www.python.org", wrapcol=7, adobe=False),
438 b'zGB\\6`E\n-ZP=Df.\n1GEb>')
439 eq(base64.a85encode(b"www.python.org", wrapcol=7, adobe=True),
440 b'<~GB\\6`\nE-ZP=Df\n.1GEb>\n~>')
441
442 eq(base64.a85encode(b' '*8, foldspaces=True, adobe=False), b'yy')
443 eq(base64.a85encode(b' '*7, foldspaces=True, adobe=False), b'y+<Vd')
444 eq(base64.a85encode(b' '*6, foldspaces=True, adobe=False), b'y+<U')
445 eq(base64.a85encode(b' '*5, foldspaces=True, adobe=False), b'y+9')
446
447 def test_b85encode(self):
448 eq = self.assertEqual
449
450 tests = {
451 b'': b'',
452 b'www.python.org': b'cXxL#aCvlSZ*DGca%T',
453 bytes(range(255)): b"""009C61O)~M2nh-c3=Iws5D^j+6crX17#SKH9337X"""
454 b"""AR!_nBqb&%C@Cr{EG;fCFflSSG&MFiI5|2yJUu=?KtV!7L`6nNNJ&ad"""
455 b"""OifNtP*GA-R8>}2SXo+ITwPvYU}0ioWMyV&XlZI|Y;A6DaB*^Tbai%j"""
456 b"""czJqze0_d@fPsR8goTEOh>41ejE#<ukdcy;l$Dm3n3<ZJoSmMZprN9p"""
457 b"""q@|{(sHv)}tgWuEu(7hUw6(UkxVgH!yuH4^z`?@9#Kp$P$jQpf%+1cv"""
458 b"""(9zP<)YaD4*xB0K+}+;a;Njxq<mKk)=;`X~?CtLF@bU8V^!4`l`1$(#"""
459 b"""{Qdp""",
460 b"""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"""
461 b"""0123456789!@#0^&*();:<>,. []{}""":
462 b"""VPa!sWoBn+X=-b1ZEkOHadLBXb#`}nd3r%YLqtVJM@UIZOH55pPf$@("""
463 b"""Q&d$}S6EqEFflSSG&MFiI5{CeBQRbjDkv#CIy^osE+AW7dwl""",
464 b'no padding..': b'Zf_uPVPs@!Zf7no',
465 b'zero compression\x00\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG00000',
466 b'zero compression\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG0000',
467 b"""Boundary:\x00\x00\x00\x00""": b"""LT`0$WMOi7IsgCw00""",
468 b'Space compr: ': b'Q*dEpWgug3ZE$irARr(h',
469 b'\xff': b'{{',
470 b'\xff'*2: b'|Nj',
471 b'\xff'*3: b'|Ns9',
472 b'\xff'*4: b'|NsC0',
473 }
474
475 for data, res in tests.items():
476 eq(base64.b85encode(data), res)
477
478 self.check_other_types(base64.b85encode, b"www.python.org",
479 b'cXxL#aCvlSZ*DGca%T')
480
481 def test_a85decode(self):
482 eq = self.assertEqual
483
484 tests = {
485 b'': b'',
486 b'GB\\6`E-ZP=Df.1GEb>': b'www.python.org',
487 b"""! ! * -'"\n\t\t9eu\r\n7# RL\vhG$k3[W&.oNg'GVB"(`=52*$$"""
488 b"""(B+<_pR,UFcb-n-Vr/1iJ-0JP==1c70M3&s#]4?Ykm5X@_(6q'R884cE"""
489 b"""H9MJ8X:f1+h<)lt#=BSg3>[:ZC?t!MSA7]@cBPD3sCi+'.E,fo>FEMbN"""
490 b"""G^4U^I!pHnJ:W<)KS>/9Ll%"IN/`jYOHG]iPa.Q$R$jD4S=Q7DTV8*TU"""
491 b"""nsrdW2ZetXKAY/Yd(L?['d?O\\@K2_]Y2%o^qmn*`5Ta:aN;TJbg"GZd"""
492 b"""*^:jeCE.%f\\,!5gtgiEi8N\\UjQ5OekiqBum-X60nF?)@o_%qPq"ad`"""
493 b"""r;HT""": bytes(range(255)),
494 b"""@:E_WAS,RgBkhF"D/O92EH6,BF`qtRH$VbC6UX@47n?3D92&&T:Jand;c"""
495 b"""Hat='/U/0JP==1c70M3&r-I,;<FN.OZ`-3]oSW/g+A(H[P""":
496 b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234'
497 b'56789!@#0^&*();:<>,. []{}',
498 b'DJpY:@:Wn_DJ(RS': b'no padding..',
499 b'H=_,8+Cf>,E,oN2F(oQ1z': b'zero compression\x00\x00\x00\x00',
500 b'H=_,8+Cf>,E,oN2F(oQ1!!!!': b'zero compression\x00\x00\x00',
501 b'6>q!aA79M(3WK-[!!': b"Boundary:\x00\x00\x00\x00",
502 b';fH/TAKYK$D/aMV+<VdL': b'Space compr: ',
503 b'rr': b'\xff',
504 b's8N': b'\xff'*2,
505 b's8W*': b'\xff'*3,
506 b's8W-!': b'\xff'*4,
507 }
508
509 for data, res in tests.items():
510 eq(base64.a85decode(data), res, data)
511 eq(base64.a85decode(data, adobe=False), res, data)
512 eq(base64.a85decode(data.decode("ascii"), adobe=False), res, data)
513 eq(base64.a85decode(b'<~' + data + b'~>', adobe=True), res, data)
Serhiy Storchaka205e75b2016-02-24 12:05:50 +0200514 eq(base64.a85decode(data + b'~>', adobe=True), res, data)
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100515 eq(base64.a85decode('<~%s~>' % data.decode("ascii"), adobe=True),
516 res, data)
517
518 eq(base64.a85decode(b'yy', foldspaces=True, adobe=False), b' '*8)
519 eq(base64.a85decode(b'y+<Vd', foldspaces=True, adobe=False), b' '*7)
520 eq(base64.a85decode(b'y+<U', foldspaces=True, adobe=False), b' '*6)
521 eq(base64.a85decode(b'y+9', foldspaces=True, adobe=False), b' '*5)
522
523 self.check_other_types(base64.a85decode, b'GB\\6`E-ZP=Df.1GEb>',
524 b"www.python.org")
525
526 def test_b85decode(self):
527 eq = self.assertEqual
528
529 tests = {
530 b'': b'',
531 b'cXxL#aCvlSZ*DGca%T': b'www.python.org',
532 b"""009C61O)~M2nh-c3=Iws5D^j+6crX17#SKH9337X"""
533 b"""AR!_nBqb&%C@Cr{EG;fCFflSSG&MFiI5|2yJUu=?KtV!7L`6nNNJ&ad"""
534 b"""OifNtP*GA-R8>}2SXo+ITwPvYU}0ioWMyV&XlZI|Y;A6DaB*^Tbai%j"""
535 b"""czJqze0_d@fPsR8goTEOh>41ejE#<ukdcy;l$Dm3n3<ZJoSmMZprN9p"""
536 b"""q@|{(sHv)}tgWuEu(7hUw6(UkxVgH!yuH4^z`?@9#Kp$P$jQpf%+1cv"""
537 b"""(9zP<)YaD4*xB0K+}+;a;Njxq<mKk)=;`X~?CtLF@bU8V^!4`l`1$(#"""
538 b"""{Qdp""": bytes(range(255)),
539 b"""VPa!sWoBn+X=-b1ZEkOHadLBXb#`}nd3r%YLqtVJM@UIZOH55pPf$@("""
540 b"""Q&d$}S6EqEFflSSG&MFiI5{CeBQRbjDkv#CIy^osE+AW7dwl""":
541 b"""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"""
542 b"""0123456789!@#0^&*();:<>,. []{}""",
543 b'Zf_uPVPs@!Zf7no': b'no padding..',
544 b'dS!BNAY*TBaB^jHb7^mG00000': b'zero compression\x00\x00\x00\x00',
545 b'dS!BNAY*TBaB^jHb7^mG0000': b'zero compression\x00\x00\x00',
546 b"""LT`0$WMOi7IsgCw00""": b"""Boundary:\x00\x00\x00\x00""",
547 b'Q*dEpWgug3ZE$irARr(h': b'Space compr: ',
548 b'{{': b'\xff',
549 b'|Nj': b'\xff'*2,
550 b'|Ns9': b'\xff'*3,
551 b'|NsC0': b'\xff'*4,
552 }
553
554 for data, res in tests.items():
555 eq(base64.b85decode(data), res)
556 eq(base64.b85decode(data.decode("ascii")), res)
557
558 self.check_other_types(base64.b85decode, b'cXxL#aCvlSZ*DGca%T',
559 b"www.python.org")
560
561 def test_a85_padding(self):
562 eq = self.assertEqual
563
564 eq(base64.a85encode(b"x", pad=True), b'GQ7^D')
565 eq(base64.a85encode(b"xx", pad=True), b"G^'2g")
566 eq(base64.a85encode(b"xxx", pad=True), b'G^+H5')
567 eq(base64.a85encode(b"xxxx", pad=True), b'G^+IX')
568 eq(base64.a85encode(b"xxxxx", pad=True), b'G^+IXGQ7^D')
569
570 eq(base64.a85decode(b'GQ7^D'), b"x\x00\x00\x00")
571 eq(base64.a85decode(b"G^'2g"), b"xx\x00\x00")
572 eq(base64.a85decode(b'G^+H5'), b"xxx\x00")
573 eq(base64.a85decode(b'G^+IX'), b"xxxx")
574 eq(base64.a85decode(b'G^+IXGQ7^D'), b"xxxxx\x00\x00\x00")
575
576 def test_b85_padding(self):
577 eq = self.assertEqual
578
579 eq(base64.b85encode(b"x", pad=True), b'cmMzZ')
580 eq(base64.b85encode(b"xx", pad=True), b'cz6H+')
581 eq(base64.b85encode(b"xxx", pad=True), b'czAdK')
582 eq(base64.b85encode(b"xxxx", pad=True), b'czAet')
583 eq(base64.b85encode(b"xxxxx", pad=True), b'czAetcmMzZ')
584
585 eq(base64.b85decode(b'cmMzZ'), b"x\x00\x00\x00")
586 eq(base64.b85decode(b'cz6H+'), b"xx\x00\x00")
587 eq(base64.b85decode(b'czAdK'), b"xxx\x00")
588 eq(base64.b85decode(b'czAet'), b"xxxx")
589 eq(base64.b85decode(b'czAetcmMzZ'), b"xxxxx\x00\x00\x00")
590
591 def test_a85decode_errors(self):
592 illegal = (set(range(32)) | set(range(118, 256))) - set(b' \t\n\r\v')
593 for c in illegal:
594 with self.assertRaises(ValueError, msg=bytes([c])):
595 base64.a85decode(b'!!!!' + bytes([c]))
596 with self.assertRaises(ValueError, msg=bytes([c])):
597 base64.a85decode(b'!!!!' + bytes([c]), adobe=False)
598 with self.assertRaises(ValueError, msg=bytes([c])):
599 base64.a85decode(b'<~!!!!' + bytes([c]) + b'~>', adobe=True)
600
601 self.assertRaises(ValueError, base64.a85decode,
602 b"malformed", adobe=True)
603 self.assertRaises(ValueError, base64.a85decode,
604 b"<~still malformed", adobe=True)
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100605
606 # With adobe=False (the default), Adobe framing markers are disallowed
607 self.assertRaises(ValueError, base64.a85decode,
608 b"<~~>")
609 self.assertRaises(ValueError, base64.a85decode,
610 b"<~~>", adobe=False)
611 base64.a85decode(b"<~~>", adobe=True) # sanity check
612
613 self.assertRaises(ValueError, base64.a85decode,
614 b"abcx", adobe=False)
615 self.assertRaises(ValueError, base64.a85decode,
616 b"abcdey", adobe=False)
617 self.assertRaises(ValueError, base64.a85decode,
618 b"a b\nc", adobe=False, ignorechars=b"")
619
620 self.assertRaises(ValueError, base64.a85decode, b's', adobe=False)
621 self.assertRaises(ValueError, base64.a85decode, b's8', adobe=False)
622 self.assertRaises(ValueError, base64.a85decode, b's8W', adobe=False)
623 self.assertRaises(ValueError, base64.a85decode, b's8W-', adobe=False)
624 self.assertRaises(ValueError, base64.a85decode, b's8W-"', adobe=False)
625
626 def test_b85decode_errors(self):
627 illegal = list(range(33)) + \
628 list(b'"\',./:[\\]') + \
629 list(range(128, 256))
630 for c in illegal:
631 with self.assertRaises(ValueError, msg=bytes([c])):
632 base64.b85decode(b'0000' + bytes([c]))
633
634 self.assertRaises(ValueError, base64.b85decode, b'|')
635 self.assertRaises(ValueError, base64.b85decode, b'|N')
636 self.assertRaises(ValueError, base64.b85decode, b'|Ns')
637 self.assertRaises(ValueError, base64.b85decode, b'|NsC')
638 self.assertRaises(ValueError, base64.b85decode, b'|NsC1')
639
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100640 def test_decode_nonascii_str(self):
641 decode_funcs = (base64.b64decode,
642 base64.standard_b64decode,
643 base64.urlsafe_b64decode,
644 base64.b32decode,
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100645 base64.b16decode,
646 base64.b85decode,
647 base64.a85decode)
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100648 for f in decode_funcs:
649 self.assertRaises(ValueError, f, 'with non-ascii \xcb')
Guido van Rossum4581ae52007-05-22 21:56:47 +0000650
651 def test_ErrorHeritage(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000652 self.assertTrue(issubclass(binascii.Error, ValueError))
Barry Warsaw4f019d32004-01-04 01:13:02 +0000653
654
Victor Stinner479736b2010-05-25 21:12:34 +0000655class TestMain(unittest.TestCase):
Vinay Sajipf9596182012-03-02 01:01:13 +0000656 def tearDown(self):
657 if os.path.exists(support.TESTFN):
658 os.unlink(support.TESTFN)
659
Berker Peksag00f81972015-07-25 14:14:24 +0300660 def get_output(self, *args):
661 return script_helper.assert_python_ok('-m', 'base64', *args).out
Victor Stinner479736b2010-05-25 21:12:34 +0000662
663 def test_encode_decode(self):
664 output = self.get_output('-t')
665 self.assertSequenceEqual(output.splitlines(), (
666 b"b'Aladdin:open sesame'",
667 br"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\n'",
668 b"b'Aladdin:open sesame'",
669 ))
670
671 def test_encode_file(self):
672 with open(support.TESTFN, 'wb') as fp:
673 fp.write(b'a\xffb\n')
Victor Stinner479736b2010-05-25 21:12:34 +0000674 output = self.get_output('-e', support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000675 self.assertEqual(output.rstrip(), b'Yf9iCg==')
Victor Stinner479736b2010-05-25 21:12:34 +0000676
Berker Peksag00f81972015-07-25 14:14:24 +0300677 def test_encode_from_stdin(self):
678 with script_helper.spawn_python('-m', 'base64', '-e') as proc:
679 out, err = proc.communicate(b'a\xffb\n')
680 self.assertEqual(out.rstrip(), b'Yf9iCg==')
681 self.assertIsNone(err)
Victor Stinner479736b2010-05-25 21:12:34 +0000682
683 def test_decode(self):
684 with open(support.TESTFN, 'wb') as fp:
685 fp.write(b'Yf9iCg==')
686 output = self.get_output('-d', support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000687 self.assertEqual(output.rstrip(), b'a\xffb')
Victor Stinner479736b2010-05-25 21:12:34 +0000688
Barry Warsaw4f019d32004-01-04 01:13:02 +0000689if __name__ == '__main__':
Berker Peksag00f81972015-07-25 14:14:24 +0300690 unittest.main()