blob: 7dba6635d4eae7bffa79d41c66d96298b0d837bf [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''),
Serhiy Storchakab19c0d772020-01-05 14:15:50 +0200253 (b"YWJj\n", b"abc"),
R. David Murray64951362010-11-11 20:09:20 +0000254 (b'YWJj\nYWI=', b'abcab'))
Martin Panteree3074e2016-02-23 22:30:50 +0000255 funcs = (
256 base64.b64decode,
257 base64.standard_b64decode,
258 base64.urlsafe_b64decode,
259 )
R. David Murray64951362010-11-11 20:09:20 +0000260 for bstr, res in tests:
Martin Panteree3074e2016-02-23 22:30:50 +0000261 for func in funcs:
262 with self.subTest(bstr=bstr, func=func):
263 self.assertEqual(func(bstr), res)
264 self.assertEqual(func(bstr.decode('ascii')), res)
R. David Murray64951362010-11-11 20:09:20 +0000265 with self.assertRaises(binascii.Error):
266 base64.b64decode(bstr, validate=True)
Antoine Pitroudff46fa2012-02-20 19:46:26 +0100267 with self.assertRaises(binascii.Error):
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100268 base64.b64decode(bstr.decode('ascii'), validate=True)
R. David Murray64951362010-11-11 20:09:20 +0000269
Martin Panteree3074e2016-02-23 22:30:50 +0000270 # Normal alphabet characters not discarded when alternative given
271 res = b'\xFB\xEF\xBE\xFF\xFF\xFF'
272 self.assertEqual(base64.b64decode(b'++[[//]]', b'[]'), res)
273 self.assertEqual(base64.urlsafe_b64decode(b'++--//__'), res)
274
Barry Warsaw4f019d32004-01-04 01:13:02 +0000275 def test_b32encode(self):
276 eq = self.assertEqual
Guido van Rossum4581ae52007-05-22 21:56:47 +0000277 eq(base64.b32encode(b''), b'')
278 eq(base64.b32encode(b'\x00'), b'AA======')
279 eq(base64.b32encode(b'a'), b'ME======')
280 eq(base64.b32encode(b'ab'), b'MFRA====')
281 eq(base64.b32encode(b'abc'), b'MFRGG===')
282 eq(base64.b32encode(b'abcd'), b'MFRGGZA=')
283 eq(base64.b32encode(b'abcde'), b'MFRGGZDF')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300284 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000285 self.check_other_types(base64.b32encode, b'abcd', b'MFRGGZA=')
286 self.check_encode_type_errors(base64.b32encode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000287
288 def test_b32decode(self):
289 eq = self.assertEqual
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100290 tests = {b'': b'',
291 b'AA======': b'\x00',
292 b'ME======': b'a',
293 b'MFRA====': b'ab',
294 b'MFRGG===': b'abc',
295 b'MFRGGZA=': b'abcd',
296 b'MFRGGZDF': b'abcde',
297 }
298 for data, res in tests.items():
299 eq(base64.b32decode(data), res)
300 eq(base64.b32decode(data.decode('ascii')), res)
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300301 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000302 self.check_other_types(base64.b32decode, b'MFRGG===', b"abc")
303 self.check_decode_type_errors(base64.b32decode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000304
305 def test_b32decode_casefold(self):
306 eq = self.assertEqual
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100307 tests = {b'': b'',
308 b'ME======': b'a',
309 b'MFRA====': b'ab',
310 b'MFRGG===': b'abc',
311 b'MFRGGZA=': b'abcd',
312 b'MFRGGZDF': b'abcde',
313 # Lower cases
314 b'me======': b'a',
315 b'mfra====': b'ab',
316 b'mfrgg===': b'abc',
317 b'mfrggza=': b'abcd',
318 b'mfrggzdf': b'abcde',
319 }
320
321 for data, res in tests.items():
322 eq(base64.b32decode(data, True), res)
323 eq(base64.b32decode(data.decode('ascii'), True), res)
324
Serhiy Storchakaea2b4902013-05-28 15:27:29 +0300325 self.assertRaises(binascii.Error, base64.b32decode, b'me======')
326 self.assertRaises(binascii.Error, base64.b32decode, 'me======')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100327
Barry Warsaw4f019d32004-01-04 01:13:02 +0000328 # Mapping zero and one
Guido van Rossum4581ae52007-05-22 21:56:47 +0000329 eq(base64.b32decode(b'MLO23456'), b'b\xdd\xad\xf3\xbe')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100330 eq(base64.b32decode('MLO23456'), b'b\xdd\xad\xf3\xbe')
331
332 map_tests = {(b'M1023456', b'L'): b'b\xdd\xad\xf3\xbe',
333 (b'M1023456', b'I'): b'b\x1d\xad\xf3\xbe',
334 }
335 for (data, map01), res in map_tests.items():
336 data_str = data.decode('ascii')
337 map01_str = map01.decode('ascii')
338
339 eq(base64.b32decode(data, map01=map01), res)
340 eq(base64.b32decode(data_str, map01=map01), res)
341 eq(base64.b32decode(data, map01=map01_str), res)
342 eq(base64.b32decode(data_str, map01=map01_str), res)
Serhiy Storchakaea2b4902013-05-28 15:27:29 +0300343 self.assertRaises(binascii.Error, base64.b32decode, data)
344 self.assertRaises(binascii.Error, base64.b32decode, data_str)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000345
346 def test_b32decode_error(self):
Serhiy Storchakaac0b3c22018-07-24 12:52:51 +0300347 tests = [b'abc', b'ABCDEF==', b'==ABCDEF']
348 prefixes = [b'M', b'ME', b'MFRA', b'MFRGG', b'MFRGGZA', b'MFRGGZDF']
349 for i in range(0, 17):
350 if i:
351 tests.append(b'='*i)
352 for prefix in prefixes:
353 if len(prefix) + i != 8:
354 tests.append(prefix + b'='*i)
355 for data in tests:
356 with self.subTest(data=data):
357 with self.assertRaises(binascii.Error):
358 base64.b32decode(data)
359 with self.assertRaises(binascii.Error):
360 base64.b32decode(data.decode('ascii'))
Barry Warsaw4f019d32004-01-04 01:13:02 +0000361
362 def test_b16encode(self):
363 eq = self.assertEqual
Guido van Rossum4581ae52007-05-22 21:56:47 +0000364 eq(base64.b16encode(b'\x01\x02\xab\xcd\xef'), b'0102ABCDEF')
365 eq(base64.b16encode(b'\x00'), b'00')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300366 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000367 self.check_other_types(base64.b16encode, b'\x01\x02\xab\xcd\xef',
368 b'0102ABCDEF')
369 self.check_encode_type_errors(base64.b16encode)
Barry Warsaw4f019d32004-01-04 01:13:02 +0000370
371 def test_b16decode(self):
372 eq = self.assertEqual
Guido van Rossum4581ae52007-05-22 21:56:47 +0000373 eq(base64.b16decode(b'0102ABCDEF'), b'\x01\x02\xab\xcd\xef')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100374 eq(base64.b16decode('0102ABCDEF'), b'\x01\x02\xab\xcd\xef')
Guido van Rossum4581ae52007-05-22 21:56:47 +0000375 eq(base64.b16decode(b'00'), b'\x00')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100376 eq(base64.b16decode('00'), b'\x00')
Barry Warsaw4f019d32004-01-04 01:13:02 +0000377 # Lower case is not allowed without a flag
Guido van Rossum4581ae52007-05-22 21:56:47 +0000378 self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100379 self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef')
Barry Warsaw4f019d32004-01-04 01:13:02 +0000380 # Case fold
Guido van Rossum4581ae52007-05-22 21:56:47 +0000381 eq(base64.b16decode(b'0102abcdef', True), b'\x01\x02\xab\xcd\xef')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100382 eq(base64.b16decode('0102abcdef', True), b'\x01\x02\xab\xcd\xef')
Serhiy Storchaka017523c2013-04-28 15:53:08 +0300383 # Non-bytes
Nick Coghlanfdf239a2013-10-03 00:43:22 +1000384 self.check_other_types(base64.b16decode, b"0102ABCDEF",
385 b'\x01\x02\xab\xcd\xef')
386 self.check_decode_type_errors(base64.b16decode)
387 eq(base64.b16decode(bytearray(b"0102abcdef"), True),
388 b'\x01\x02\xab\xcd\xef')
389 eq(base64.b16decode(memoryview(b"0102abcdef"), True),
390 b'\x01\x02\xab\xcd\xef')
391 eq(base64.b16decode(array('B', b"0102abcdef"), True),
392 b'\x01\x02\xab\xcd\xef')
Martin Panteree3074e2016-02-23 22:30:50 +0000393 # Non-alphabet characters
394 self.assertRaises(binascii.Error, base64.b16decode, '0102AG')
395 # Incorrect "padding"
396 self.assertRaises(binascii.Error, base64.b16decode, '010')
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100397
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100398 def test_a85encode(self):
399 eq = self.assertEqual
400
401 tests = {
402 b'': b'',
403 b"www.python.org": b'GB\\6`E-ZP=Df.1GEb>',
404 bytes(range(255)): b"""!!*-'"9eu7#RLhG$k3[W&.oNg'GVB"(`=52*$$"""
405 b"""(B+<_pR,UFcb-n-Vr/1iJ-0JP==1c70M3&s#]4?Ykm5X@_(6q'R884cE"""
406 b"""H9MJ8X:f1+h<)lt#=BSg3>[:ZC?t!MSA7]@cBPD3sCi+'.E,fo>FEMbN"""
407 b"""G^4U^I!pHnJ:W<)KS>/9Ll%"IN/`jYOHG]iPa.Q$R$jD4S=Q7DTV8*TU"""
408 b"""nsrdW2ZetXKAY/Yd(L?['d?O\\@K2_]Y2%o^qmn*`5Ta:aN;TJbg"GZd"""
409 b"""*^:jeCE.%f\\,!5gtgiEi8N\\UjQ5OekiqBum-X60nF?)@o_%qPq"ad`"""
410 b"""r;HT""",
411 b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
412 b"0123456789!@#0^&*();:<>,. []{}":
413 b'@:E_WAS,RgBkhF"D/O92EH6,BF`qtRH$VbC6UX@47n?3D92&&T'
414 b":Jand;cHat='/U/0JP==1c70M3&r-I,;<FN.OZ`-3]oSW/g+A(H[P",
415 b"no padding..": b'DJpY:@:Wn_DJ(RS',
416 b"zero compression\0\0\0\0": b'H=_,8+Cf>,E,oN2F(oQ1z',
417 b"zero compression\0\0\0": b'H=_,8+Cf>,E,oN2F(oQ1!!!!',
418 b"Boundary:\0\0\0\0": b'6>q!aA79M(3WK-[!!',
419 b"Space compr: ": b';fH/TAKYK$D/aMV+<VdL',
420 b'\xff': b'rr',
421 b'\xff'*2: b's8N',
422 b'\xff'*3: b's8W*',
423 b'\xff'*4: b's8W-!',
424 }
425
426 for data, res in tests.items():
427 eq(base64.a85encode(data), res, data)
428 eq(base64.a85encode(data, adobe=False), res, data)
429 eq(base64.a85encode(data, adobe=True), b'<~' + res + b'~>', data)
430
431 self.check_other_types(base64.a85encode, b"www.python.org",
432 b'GB\\6`E-ZP=Df.1GEb>')
433
434 self.assertRaises(TypeError, base64.a85encode, "")
435
436 eq(base64.a85encode(b"www.python.org", wrapcol=7, adobe=False),
437 b'GB\\6`E-\nZP=Df.1\nGEb>')
438 eq(base64.a85encode(b"\0\0\0\0www.python.org", wrapcol=7, adobe=False),
439 b'zGB\\6`E\n-ZP=Df.\n1GEb>')
440 eq(base64.a85encode(b"www.python.org", wrapcol=7, adobe=True),
441 b'<~GB\\6`\nE-ZP=Df\n.1GEb>\n~>')
442
443 eq(base64.a85encode(b' '*8, foldspaces=True, adobe=False), b'yy')
444 eq(base64.a85encode(b' '*7, foldspaces=True, adobe=False), b'y+<Vd')
445 eq(base64.a85encode(b' '*6, foldspaces=True, adobe=False), b'y+<U')
446 eq(base64.a85encode(b' '*5, foldspaces=True, adobe=False), b'y+9')
447
448 def test_b85encode(self):
449 eq = self.assertEqual
450
451 tests = {
452 b'': b'',
453 b'www.python.org': b'cXxL#aCvlSZ*DGca%T',
454 bytes(range(255)): b"""009C61O)~M2nh-c3=Iws5D^j+6crX17#SKH9337X"""
455 b"""AR!_nBqb&%C@Cr{EG;fCFflSSG&MFiI5|2yJUu=?KtV!7L`6nNNJ&ad"""
456 b"""OifNtP*GA-R8>}2SXo+ITwPvYU}0ioWMyV&XlZI|Y;A6DaB*^Tbai%j"""
457 b"""czJqze0_d@fPsR8goTEOh>41ejE#<ukdcy;l$Dm3n3<ZJoSmMZprN9p"""
458 b"""q@|{(sHv)}tgWuEu(7hUw6(UkxVgH!yuH4^z`?@9#Kp$P$jQpf%+1cv"""
459 b"""(9zP<)YaD4*xB0K+}+;a;Njxq<mKk)=;`X~?CtLF@bU8V^!4`l`1$(#"""
460 b"""{Qdp""",
461 b"""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"""
462 b"""0123456789!@#0^&*();:<>,. []{}""":
463 b"""VPa!sWoBn+X=-b1ZEkOHadLBXb#`}nd3r%YLqtVJM@UIZOH55pPf$@("""
464 b"""Q&d$}S6EqEFflSSG&MFiI5{CeBQRbjDkv#CIy^osE+AW7dwl""",
465 b'no padding..': b'Zf_uPVPs@!Zf7no',
466 b'zero compression\x00\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG00000',
467 b'zero compression\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG0000',
468 b"""Boundary:\x00\x00\x00\x00""": b"""LT`0$WMOi7IsgCw00""",
469 b'Space compr: ': b'Q*dEpWgug3ZE$irARr(h',
470 b'\xff': b'{{',
471 b'\xff'*2: b'|Nj',
472 b'\xff'*3: b'|Ns9',
473 b'\xff'*4: b'|NsC0',
474 }
475
476 for data, res in tests.items():
477 eq(base64.b85encode(data), res)
478
479 self.check_other_types(base64.b85encode, b"www.python.org",
480 b'cXxL#aCvlSZ*DGca%T')
481
482 def test_a85decode(self):
483 eq = self.assertEqual
484
485 tests = {
486 b'': b'',
487 b'GB\\6`E-ZP=Df.1GEb>': b'www.python.org',
488 b"""! ! * -'"\n\t\t9eu\r\n7# RL\vhG$k3[W&.oNg'GVB"(`=52*$$"""
489 b"""(B+<_pR,UFcb-n-Vr/1iJ-0JP==1c70M3&s#]4?Ykm5X@_(6q'R884cE"""
490 b"""H9MJ8X:f1+h<)lt#=BSg3>[:ZC?t!MSA7]@cBPD3sCi+'.E,fo>FEMbN"""
491 b"""G^4U^I!pHnJ:W<)KS>/9Ll%"IN/`jYOHG]iPa.Q$R$jD4S=Q7DTV8*TU"""
492 b"""nsrdW2ZetXKAY/Yd(L?['d?O\\@K2_]Y2%o^qmn*`5Ta:aN;TJbg"GZd"""
493 b"""*^:jeCE.%f\\,!5gtgiEi8N\\UjQ5OekiqBum-X60nF?)@o_%qPq"ad`"""
494 b"""r;HT""": bytes(range(255)),
495 b"""@:E_WAS,RgBkhF"D/O92EH6,BF`qtRH$VbC6UX@47n?3D92&&T:Jand;c"""
496 b"""Hat='/U/0JP==1c70M3&r-I,;<FN.OZ`-3]oSW/g+A(H[P""":
497 b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234'
498 b'56789!@#0^&*();:<>,. []{}',
499 b'DJpY:@:Wn_DJ(RS': b'no padding..',
500 b'H=_,8+Cf>,E,oN2F(oQ1z': b'zero compression\x00\x00\x00\x00',
501 b'H=_,8+Cf>,E,oN2F(oQ1!!!!': b'zero compression\x00\x00\x00',
502 b'6>q!aA79M(3WK-[!!': b"Boundary:\x00\x00\x00\x00",
503 b';fH/TAKYK$D/aMV+<VdL': b'Space compr: ',
504 b'rr': b'\xff',
505 b's8N': b'\xff'*2,
506 b's8W*': b'\xff'*3,
507 b's8W-!': b'\xff'*4,
508 }
509
510 for data, res in tests.items():
511 eq(base64.a85decode(data), res, data)
512 eq(base64.a85decode(data, adobe=False), res, data)
513 eq(base64.a85decode(data.decode("ascii"), adobe=False), res, data)
514 eq(base64.a85decode(b'<~' + data + b'~>', adobe=True), res, data)
Serhiy Storchaka205e75b2016-02-24 12:05:50 +0200515 eq(base64.a85decode(data + b'~>', adobe=True), res, data)
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100516 eq(base64.a85decode('<~%s~>' % data.decode("ascii"), adobe=True),
517 res, data)
518
519 eq(base64.a85decode(b'yy', foldspaces=True, adobe=False), b' '*8)
520 eq(base64.a85decode(b'y+<Vd', foldspaces=True, adobe=False), b' '*7)
521 eq(base64.a85decode(b'y+<U', foldspaces=True, adobe=False), b' '*6)
522 eq(base64.a85decode(b'y+9', foldspaces=True, adobe=False), b' '*5)
523
524 self.check_other_types(base64.a85decode, b'GB\\6`E-ZP=Df.1GEb>',
525 b"www.python.org")
526
527 def test_b85decode(self):
528 eq = self.assertEqual
529
530 tests = {
531 b'': b'',
532 b'cXxL#aCvlSZ*DGca%T': b'www.python.org',
533 b"""009C61O)~M2nh-c3=Iws5D^j+6crX17#SKH9337X"""
534 b"""AR!_nBqb&%C@Cr{EG;fCFflSSG&MFiI5|2yJUu=?KtV!7L`6nNNJ&ad"""
535 b"""OifNtP*GA-R8>}2SXo+ITwPvYU}0ioWMyV&XlZI|Y;A6DaB*^Tbai%j"""
536 b"""czJqze0_d@fPsR8goTEOh>41ejE#<ukdcy;l$Dm3n3<ZJoSmMZprN9p"""
537 b"""q@|{(sHv)}tgWuEu(7hUw6(UkxVgH!yuH4^z`?@9#Kp$P$jQpf%+1cv"""
538 b"""(9zP<)YaD4*xB0K+}+;a;Njxq<mKk)=;`X~?CtLF@bU8V^!4`l`1$(#"""
539 b"""{Qdp""": bytes(range(255)),
540 b"""VPa!sWoBn+X=-b1ZEkOHadLBXb#`}nd3r%YLqtVJM@UIZOH55pPf$@("""
541 b"""Q&d$}S6EqEFflSSG&MFiI5{CeBQRbjDkv#CIy^osE+AW7dwl""":
542 b"""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"""
543 b"""0123456789!@#0^&*();:<>,. []{}""",
544 b'Zf_uPVPs@!Zf7no': b'no padding..',
545 b'dS!BNAY*TBaB^jHb7^mG00000': b'zero compression\x00\x00\x00\x00',
546 b'dS!BNAY*TBaB^jHb7^mG0000': b'zero compression\x00\x00\x00',
547 b"""LT`0$WMOi7IsgCw00""": b"""Boundary:\x00\x00\x00\x00""",
548 b'Q*dEpWgug3ZE$irARr(h': b'Space compr: ',
549 b'{{': b'\xff',
550 b'|Nj': b'\xff'*2,
551 b'|Ns9': b'\xff'*3,
552 b'|NsC0': b'\xff'*4,
553 }
554
555 for data, res in tests.items():
556 eq(base64.b85decode(data), res)
557 eq(base64.b85decode(data.decode("ascii")), res)
558
559 self.check_other_types(base64.b85decode, b'cXxL#aCvlSZ*DGca%T',
560 b"www.python.org")
561
562 def test_a85_padding(self):
563 eq = self.assertEqual
564
565 eq(base64.a85encode(b"x", pad=True), b'GQ7^D')
566 eq(base64.a85encode(b"xx", pad=True), b"G^'2g")
567 eq(base64.a85encode(b"xxx", pad=True), b'G^+H5')
568 eq(base64.a85encode(b"xxxx", pad=True), b'G^+IX')
569 eq(base64.a85encode(b"xxxxx", pad=True), b'G^+IXGQ7^D')
570
571 eq(base64.a85decode(b'GQ7^D'), b"x\x00\x00\x00")
572 eq(base64.a85decode(b"G^'2g"), b"xx\x00\x00")
573 eq(base64.a85decode(b'G^+H5'), b"xxx\x00")
574 eq(base64.a85decode(b'G^+IX'), b"xxxx")
575 eq(base64.a85decode(b'G^+IXGQ7^D'), b"xxxxx\x00\x00\x00")
576
577 def test_b85_padding(self):
578 eq = self.assertEqual
579
580 eq(base64.b85encode(b"x", pad=True), b'cmMzZ')
581 eq(base64.b85encode(b"xx", pad=True), b'cz6H+')
582 eq(base64.b85encode(b"xxx", pad=True), b'czAdK')
583 eq(base64.b85encode(b"xxxx", pad=True), b'czAet')
584 eq(base64.b85encode(b"xxxxx", pad=True), b'czAetcmMzZ')
585
586 eq(base64.b85decode(b'cmMzZ'), b"x\x00\x00\x00")
587 eq(base64.b85decode(b'cz6H+'), b"xx\x00\x00")
588 eq(base64.b85decode(b'czAdK'), b"xxx\x00")
589 eq(base64.b85decode(b'czAet'), b"xxxx")
590 eq(base64.b85decode(b'czAetcmMzZ'), b"xxxxx\x00\x00\x00")
591
592 def test_a85decode_errors(self):
593 illegal = (set(range(32)) | set(range(118, 256))) - set(b' \t\n\r\v')
594 for c in illegal:
595 with self.assertRaises(ValueError, msg=bytes([c])):
596 base64.a85decode(b'!!!!' + bytes([c]))
597 with self.assertRaises(ValueError, msg=bytes([c])):
598 base64.a85decode(b'!!!!' + bytes([c]), adobe=False)
599 with self.assertRaises(ValueError, msg=bytes([c])):
600 base64.a85decode(b'<~!!!!' + bytes([c]) + b'~>', adobe=True)
601
602 self.assertRaises(ValueError, base64.a85decode,
603 b"malformed", adobe=True)
604 self.assertRaises(ValueError, base64.a85decode,
605 b"<~still malformed", adobe=True)
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100606
607 # With adobe=False (the default), Adobe framing markers are disallowed
608 self.assertRaises(ValueError, base64.a85decode,
609 b"<~~>")
610 self.assertRaises(ValueError, base64.a85decode,
611 b"<~~>", adobe=False)
612 base64.a85decode(b"<~~>", adobe=True) # sanity check
613
614 self.assertRaises(ValueError, base64.a85decode,
615 b"abcx", adobe=False)
616 self.assertRaises(ValueError, base64.a85decode,
617 b"abcdey", adobe=False)
618 self.assertRaises(ValueError, base64.a85decode,
619 b"a b\nc", adobe=False, ignorechars=b"")
620
621 self.assertRaises(ValueError, base64.a85decode, b's', adobe=False)
622 self.assertRaises(ValueError, base64.a85decode, b's8', adobe=False)
623 self.assertRaises(ValueError, base64.a85decode, b's8W', adobe=False)
624 self.assertRaises(ValueError, base64.a85decode, b's8W-', adobe=False)
625 self.assertRaises(ValueError, base64.a85decode, b's8W-"', adobe=False)
626
627 def test_b85decode_errors(self):
628 illegal = list(range(33)) + \
629 list(b'"\',./:[\\]') + \
630 list(range(128, 256))
631 for c in illegal:
632 with self.assertRaises(ValueError, msg=bytes([c])):
633 base64.b85decode(b'0000' + bytes([c]))
634
635 self.assertRaises(ValueError, base64.b85decode, b'|')
636 self.assertRaises(ValueError, base64.b85decode, b'|N')
637 self.assertRaises(ValueError, base64.b85decode, b'|Ns')
638 self.assertRaises(ValueError, base64.b85decode, b'|NsC')
639 self.assertRaises(ValueError, base64.b85decode, b'|NsC1')
640
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100641 def test_decode_nonascii_str(self):
642 decode_funcs = (base64.b64decode,
643 base64.standard_b64decode,
644 base64.urlsafe_b64decode,
645 base64.b32decode,
Antoine Pitrou6dd0d462013-11-17 23:52:25 +0100646 base64.b16decode,
647 base64.b85decode,
648 base64.a85decode)
Antoine Pitrouea6b4d52012-02-20 19:30:23 +0100649 for f in decode_funcs:
650 self.assertRaises(ValueError, f, 'with non-ascii \xcb')
Guido van Rossum4581ae52007-05-22 21:56:47 +0000651
652 def test_ErrorHeritage(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000653 self.assertTrue(issubclass(binascii.Error, ValueError))
Barry Warsaw4f019d32004-01-04 01:13:02 +0000654
655
Victor Stinner479736b2010-05-25 21:12:34 +0000656class TestMain(unittest.TestCase):
Vinay Sajipf9596182012-03-02 01:01:13 +0000657 def tearDown(self):
658 if os.path.exists(support.TESTFN):
659 os.unlink(support.TESTFN)
660
Berker Peksag00f81972015-07-25 14:14:24 +0300661 def get_output(self, *args):
662 return script_helper.assert_python_ok('-m', 'base64', *args).out
Victor Stinner479736b2010-05-25 21:12:34 +0000663
664 def test_encode_decode(self):
665 output = self.get_output('-t')
666 self.assertSequenceEqual(output.splitlines(), (
667 b"b'Aladdin:open sesame'",
668 br"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\n'",
669 b"b'Aladdin:open sesame'",
670 ))
671
672 def test_encode_file(self):
673 with open(support.TESTFN, 'wb') as fp:
674 fp.write(b'a\xffb\n')
Victor Stinner479736b2010-05-25 21:12:34 +0000675 output = self.get_output('-e', support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000676 self.assertEqual(output.rstrip(), b'Yf9iCg==')
Victor Stinner479736b2010-05-25 21:12:34 +0000677
Berker Peksag00f81972015-07-25 14:14:24 +0300678 def test_encode_from_stdin(self):
679 with script_helper.spawn_python('-m', 'base64', '-e') as proc:
680 out, err = proc.communicate(b'a\xffb\n')
681 self.assertEqual(out.rstrip(), b'Yf9iCg==')
682 self.assertIsNone(err)
Victor Stinner479736b2010-05-25 21:12:34 +0000683
684 def test_decode(self):
685 with open(support.TESTFN, 'wb') as fp:
686 fp.write(b'Yf9iCg==')
687 output = self.get_output('-d', support.TESTFN)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000688 self.assertEqual(output.rstrip(), b'a\xffb')
Victor Stinner479736b2010-05-25 21:12:34 +0000689
Barry Warsaw4f019d32004-01-04 01:13:02 +0000690if __name__ == '__main__':
Berker Peksag00f81972015-07-25 14:14:24 +0300691 unittest.main()