blob: a6f1826a0b9061fd0fe643a0eb5a5d37b8dfc9b3 [file] [log] [blame]
Guido van Rossum254348e2007-11-21 19:29:53 +00001"""Unit tests for the bytes and bytearray types.
Guido van Rossum98297ee2007-11-06 21:34:58 +00002
3XXX This is a mess. Common tests should be moved to buffer_tests.py,
4which itself ought to be unified with string_tests.py (and the latter
5should be modernized).
6"""
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00007
Guido van Rossumd624f182006-04-24 13:47:05 +00008import os
9import re
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000010import sys
Guido van Rossuma6c04be2007-11-03 00:24:24 +000011import copy
Florent Xiclunaedf5f0d2010-09-03 20:00:37 +000012import functools
Guido van Rossum0ad08122007-04-11 04:37:43 +000013import pickle
Guido van Rossumd624f182006-04-24 13:47:05 +000014import tempfile
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000015import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000016import test.support
Georg Brandlc7885542007-03-06 19:16:20 +000017import test.string_tests
Gregory P. Smith60d241f2007-10-16 06:31:30 +000018import test.buffer_tests
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000019
Florent Xiclunaedf5f0d2010-09-03 20:00:37 +000020
21if sys.flags.bytes_warning:
22 def check_bytes_warnings(func):
23 @functools.wraps(func)
24 def wrapper(*args, **kw):
25 with test.support.check_warnings(('', BytesWarning)):
26 return func(*args, **kw)
27 return wrapper
28else:
29 # no-op
30 def check_bytes_warnings(func):
31 return func
32
33
Georg Brandl9a54d7c2008-07-16 23:15:30 +000034class Indexable:
35 def __init__(self, value=0):
36 self.value = value
37 def __index__(self):
38 return self.value
39
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000040
Christian Heimes510711d2008-01-30 11:57:58 +000041class BaseBytesTest(unittest.TestCase):
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000042
43 def test_basics(self):
Christian Heimes510711d2008-01-30 11:57:58 +000044 b = self.type2test()
45 self.assertEqual(type(b), self.type2test)
46 self.assertEqual(b.__class__, self.type2test)
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000047
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +000048 def test_copy(self):
49 a = self.type2test(b"abcd")
50 for copy_method in (copy.copy, copy.deepcopy):
51 b = copy_method(a)
52 self.assertEqual(a, b)
53 self.assertEqual(type(a), type(b))
54
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000055 def test_empty_sequence(self):
Christian Heimes510711d2008-01-30 11:57:58 +000056 b = self.type2test()
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000057 self.assertEqual(len(b), 0)
58 self.assertRaises(IndexError, lambda: b[0])
59 self.assertRaises(IndexError, lambda: b[1])
Christian Heimesa37d4c62007-12-04 23:02:19 +000060 self.assertRaises(IndexError, lambda: b[sys.maxsize])
61 self.assertRaises(IndexError, lambda: b[sys.maxsize+1])
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000062 self.assertRaises(IndexError, lambda: b[10**100])
63 self.assertRaises(IndexError, lambda: b[-1])
64 self.assertRaises(IndexError, lambda: b[-2])
Christian Heimesa37d4c62007-12-04 23:02:19 +000065 self.assertRaises(IndexError, lambda: b[-sys.maxsize])
66 self.assertRaises(IndexError, lambda: b[-sys.maxsize-1])
67 self.assertRaises(IndexError, lambda: b[-sys.maxsize-2])
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000068 self.assertRaises(IndexError, lambda: b[-10**100])
69
70 def test_from_list(self):
71 ints = list(range(256))
Christian Heimes510711d2008-01-30 11:57:58 +000072 b = self.type2test(i for i in ints)
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000073 self.assertEqual(len(b), 256)
74 self.assertEqual(list(b), ints)
75
76 def test_from_index(self):
Georg Brandl9a54d7c2008-07-16 23:15:30 +000077 b = self.type2test([Indexable(), Indexable(1), Indexable(254),
78 Indexable(255)])
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000079 self.assertEqual(list(b), [0, 1, 254, 255])
Benjamin Peterson4c045832010-04-16 22:35:32 +000080 self.assertRaises(ValueError, self.type2test, [Indexable(-1)])
81 self.assertRaises(ValueError, self.type2test, [Indexable(256)])
Guido van Rossum98297ee2007-11-06 21:34:58 +000082
83 def test_from_ssize(self):
Benjamin Peterson4c045832010-04-16 22:35:32 +000084 self.assertEqual(self.type2test(0), b'')
85 self.assertEqual(self.type2test(1), b'\x00')
86 self.assertEqual(self.type2test(5), b'\x00\x00\x00\x00\x00')
87 self.assertRaises(ValueError, self.type2test, -1)
Guido van Rossum98297ee2007-11-06 21:34:58 +000088
Benjamin Peterson4c045832010-04-16 22:35:32 +000089 self.assertEqual(self.type2test('0', 'ascii'), b'0')
90 self.assertEqual(self.type2test(b'0'), b'0')
Benjamin Peterson8380dd52010-04-16 22:51:37 +000091 self.assertRaises(OverflowError, self.type2test, sys.maxsize + 1)
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000092
93 def test_constructor_type_errors(self):
Christian Heimes510711d2008-01-30 11:57:58 +000094 self.assertRaises(TypeError, self.type2test, 0.0)
Guido van Rossum4dfe8a12006-04-22 23:28:04 +000095 class C:
96 pass
Christian Heimes510711d2008-01-30 11:57:58 +000097 self.assertRaises(TypeError, self.type2test, ["0"])
98 self.assertRaises(TypeError, self.type2test, [0.0])
99 self.assertRaises(TypeError, self.type2test, [None])
100 self.assertRaises(TypeError, self.type2test, [C()])
Guido van Rossum4dfe8a12006-04-22 23:28:04 +0000101
102 def test_constructor_value_errors(self):
Christian Heimes510711d2008-01-30 11:57:58 +0000103 self.assertRaises(ValueError, self.type2test, [-1])
104 self.assertRaises(ValueError, self.type2test, [-sys.maxsize])
105 self.assertRaises(ValueError, self.type2test, [-sys.maxsize-1])
106 self.assertRaises(ValueError, self.type2test, [-sys.maxsize-2])
107 self.assertRaises(ValueError, self.type2test, [-10**100])
108 self.assertRaises(ValueError, self.type2test, [256])
109 self.assertRaises(ValueError, self.type2test, [257])
110 self.assertRaises(ValueError, self.type2test, [sys.maxsize])
111 self.assertRaises(ValueError, self.type2test, [sys.maxsize+1])
112 self.assertRaises(ValueError, self.type2test, [10**100])
Guido van Rossum4dfe8a12006-04-22 23:28:04 +0000113
114 def test_compare(self):
Christian Heimes510711d2008-01-30 11:57:58 +0000115 b1 = self.type2test([1, 2, 3])
116 b2 = self.type2test([1, 2, 3])
117 b3 = self.type2test([1, 3])
Guido van Rossum4dfe8a12006-04-22 23:28:04 +0000118
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000119 self.assertEqual(b1, b2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000120 self.assertTrue(b2 != b3)
121 self.assertTrue(b1 <= b2)
122 self.assertTrue(b1 <= b3)
123 self.assertTrue(b1 < b3)
124 self.assertTrue(b1 >= b2)
125 self.assertTrue(b3 >= b2)
126 self.assertTrue(b3 > b2)
Guido van Rossum4dfe8a12006-04-22 23:28:04 +0000127
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000128 self.assertFalse(b1 != b2)
129 self.assertFalse(b2 == b3)
130 self.assertFalse(b1 > b2)
131 self.assertFalse(b1 > b3)
132 self.assertFalse(b1 >= b3)
133 self.assertFalse(b1 < b2)
134 self.assertFalse(b3 < b2)
135 self.assertFalse(b3 <= b2)
Guido van Rossum4dfe8a12006-04-22 23:28:04 +0000136
Florent Xiclunaedf5f0d2010-09-03 20:00:37 +0000137 @check_bytes_warnings
Guido van Rossum343e97f2007-04-09 00:43:24 +0000138 def test_compare_to_str(self):
Florent Xiclunaedf5f0d2010-09-03 20:00:37 +0000139 # Byte comparisons with unicode should always fail!
140 # Test this for all expected byte orders and Unicode character
141 # sizes.
142 self.assertEqual(self.type2test(b"\0a\0b\0c") == "abc", False)
143 self.assertEqual(self.type2test(b"\0\0\0a\0\0\0b\0\0\0c") == "abc",
144 False)
145 self.assertEqual(self.type2test(b"a\0b\0c\0") == "abc", False)
146 self.assertEqual(self.type2test(b"a\0\0\0b\0\0\0c\0\0\0") == "abc",
147 False)
148 self.assertEqual(self.type2test() == str(), False)
149 self.assertEqual(self.type2test() != str(), True)
Christian Heimes510711d2008-01-30 11:57:58 +0000150
151 def test_reversed(self):
152 input = list(map(ord, "Hello"))
153 b = self.type2test(input)
154 output = list(reversed(b))
155 input.reverse()
156 self.assertEqual(output, input)
157
158 def test_getslice(self):
159 def by(s):
160 return self.type2test(map(ord, s))
161 b = by("Hello, world")
162
163 self.assertEqual(b[:5], by("Hello"))
164 self.assertEqual(b[1:5], by("ello"))
165 self.assertEqual(b[5:7], by(", "))
166 self.assertEqual(b[7:], by("world"))
167 self.assertEqual(b[7:12], by("world"))
168 self.assertEqual(b[7:100], by("world"))
169
170 self.assertEqual(b[:-7], by("Hello"))
171 self.assertEqual(b[-11:-7], by("ello"))
172 self.assertEqual(b[-7:-5], by(", "))
173 self.assertEqual(b[-5:], by("world"))
174 self.assertEqual(b[-5:12], by("world"))
175 self.assertEqual(b[-5:100], by("world"))
176 self.assertEqual(b[-100:5], by("Hello"))
177
178 def test_extended_getslice(self):
179 # Test extended slicing by comparing with list slicing.
180 L = list(range(255))
181 b = self.type2test(L)
182 indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
183 for start in indices:
184 for stop in indices:
185 # Skip step 0 (invalid)
186 for step in indices[1:]:
187 self.assertEqual(b[start:stop:step], self.type2test(L[start:stop:step]))
188
189 def test_encoding(self):
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000190 sample = "Hello world\n\u1234\u5678\u9abc"
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000191 for enc in ("utf-8", "utf-16"):
Christian Heimes510711d2008-01-30 11:57:58 +0000192 b = self.type2test(sample, enc)
193 self.assertEqual(b, self.type2test(sample.encode(enc)))
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000194 self.assertRaises(UnicodeEncodeError, self.type2test, sample, "latin-1")
195 b = self.type2test(sample, "latin-1", "ignore")
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000196 self.assertEqual(b, self.type2test(sample[:-3], "utf-8"))
Christian Heimes510711d2008-01-30 11:57:58 +0000197
198 def test_decode(self):
199 sample = "Hello world\n\u1234\u5678\u9abc\def0\def0"
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000200 for enc in ("utf-8", "utf-16"):
Christian Heimes510711d2008-01-30 11:57:58 +0000201 b = self.type2test(sample, enc)
202 self.assertEqual(b.decode(enc), sample)
203 sample = "Hello world\n\x80\x81\xfe\xff"
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000204 b = self.type2test(sample, "latin-1")
205 self.assertRaises(UnicodeDecodeError, b.decode, "utf-8")
206 self.assertEqual(b.decode("utf-8", "ignore"), "Hello world\n")
207 self.assertEqual(b.decode(errors="ignore", encoding="utf-8"),
Benjamin Peterson308d6372009-09-18 21:42:35 +0000208 "Hello world\n")
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000209 # Default encoding is utf-8
210 self.assertEqual(self.type2test(b'\xe2\x98\x83').decode(), '\u2603')
Christian Heimes510711d2008-01-30 11:57:58 +0000211
212 def test_from_int(self):
213 b = self.type2test(0)
214 self.assertEqual(b, self.type2test())
215 b = self.type2test(10)
216 self.assertEqual(b, self.type2test([0]*10))
217 b = self.type2test(10000)
218 self.assertEqual(b, self.type2test([0]*10000))
219
220 def test_concat(self):
221 b1 = self.type2test(b"abc")
222 b2 = self.type2test(b"def")
223 self.assertEqual(b1 + b2, b"abcdef")
224 self.assertEqual(b1 + bytes(b"def"), b"abcdef")
225 self.assertEqual(bytes(b"def") + b1, b"defabc")
226 self.assertRaises(TypeError, lambda: b1 + "def")
227 self.assertRaises(TypeError, lambda: "abc" + b2)
228
229 def test_repeat(self):
230 for b in b"abc", self.type2test(b"abc"):
231 self.assertEqual(b * 3, b"abcabcabc")
232 self.assertEqual(b * 0, b"")
233 self.assertEqual(b * -1, b"")
234 self.assertRaises(TypeError, lambda: b * 3.14)
235 self.assertRaises(TypeError, lambda: 3.14 * b)
236 # XXX Shouldn't bytes and bytearray agree on what to raise?
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000237 with self.assertRaises((OverflowError, MemoryError)):
238 c = b * sys.maxsize
239 with self.assertRaises((OverflowError, MemoryError)):
240 b *= sys.maxsize
Christian Heimes510711d2008-01-30 11:57:58 +0000241
242 def test_repeat_1char(self):
243 self.assertEqual(self.type2test(b'x')*100, self.type2test([ord('x')]*100))
244
245 def test_contains(self):
246 b = self.type2test(b"abc")
Benjamin Peterson577473f2010-01-19 00:09:57 +0000247 self.assertIn(ord('a'), b)
248 self.assertIn(int(ord('a')), b)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000249 self.assertNotIn(200, b)
Christian Heimes510711d2008-01-30 11:57:58 +0000250 self.assertRaises(ValueError, lambda: 300 in b)
251 self.assertRaises(ValueError, lambda: -1 in b)
252 self.assertRaises(TypeError, lambda: None in b)
253 self.assertRaises(TypeError, lambda: float(ord('a')) in b)
254 self.assertRaises(TypeError, lambda: "a" in b)
255 for f in bytes, bytearray:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000256 self.assertIn(f(b""), b)
257 self.assertIn(f(b"a"), b)
258 self.assertIn(f(b"b"), b)
259 self.assertIn(f(b"c"), b)
260 self.assertIn(f(b"ab"), b)
261 self.assertIn(f(b"bc"), b)
262 self.assertIn(f(b"abc"), b)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000263 self.assertNotIn(f(b"ac"), b)
264 self.assertNotIn(f(b"d"), b)
265 self.assertNotIn(f(b"dab"), b)
266 self.assertNotIn(f(b"abd"), b)
Christian Heimes510711d2008-01-30 11:57:58 +0000267
268 def test_fromhex(self):
269 self.assertRaises(TypeError, self.type2test.fromhex)
270 self.assertRaises(TypeError, self.type2test.fromhex, 1)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000271 self.assertEqual(self.type2test.fromhex(''), self.type2test())
Christian Heimes510711d2008-01-30 11:57:58 +0000272 b = bytearray([0x1a, 0x2b, 0x30])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000273 self.assertEqual(self.type2test.fromhex('1a2B30'), b)
274 self.assertEqual(self.type2test.fromhex(' 1A 2B 30 '), b)
275 self.assertEqual(self.type2test.fromhex('0000'), b'\0\0')
Christian Heimes510711d2008-01-30 11:57:58 +0000276 self.assertRaises(TypeError, self.type2test.fromhex, b'1B')
277 self.assertRaises(ValueError, self.type2test.fromhex, 'a')
278 self.assertRaises(ValueError, self.type2test.fromhex, 'rt')
279 self.assertRaises(ValueError, self.type2test.fromhex, '1a b cd')
280 self.assertRaises(ValueError, self.type2test.fromhex, '\x00')
281 self.assertRaises(ValueError, self.type2test.fromhex, '12 \x00 34')
282
283 def test_join(self):
284 self.assertEqual(self.type2test(b"").join([]), b"")
285 self.assertEqual(self.type2test(b"").join([b""]), b"")
286 for lst in [[b"abc"], [b"a", b"bc"], [b"ab", b"c"], [b"a", b"b", b"c"]]:
287 lst = list(map(self.type2test, lst))
288 self.assertEqual(self.type2test(b"").join(lst), b"abc")
289 self.assertEqual(self.type2test(b"").join(tuple(lst)), b"abc")
290 self.assertEqual(self.type2test(b"").join(iter(lst)), b"abc")
291 self.assertEqual(self.type2test(b".").join([b"ab", b"cd"]), b"ab.cd")
292 # XXX more...
293
Christian Heimes510711d2008-01-30 11:57:58 +0000294 def test_count(self):
295 b = self.type2test(b'mississippi')
296 self.assertEqual(b.count(b'i'), 4)
297 self.assertEqual(b.count(b'ss'), 2)
298 self.assertEqual(b.count(b'w'), 0)
299
300 def test_startswith(self):
301 b = self.type2test(b'hello')
302 self.assertFalse(self.type2test().startswith(b"anything"))
303 self.assertTrue(b.startswith(b"hello"))
304 self.assertTrue(b.startswith(b"hel"))
305 self.assertTrue(b.startswith(b"h"))
306 self.assertFalse(b.startswith(b"hellow"))
307 self.assertFalse(b.startswith(b"ha"))
308
309 def test_endswith(self):
310 b = self.type2test(b'hello')
311 self.assertFalse(bytearray().endswith(b"anything"))
312 self.assertTrue(b.endswith(b"hello"))
313 self.assertTrue(b.endswith(b"llo"))
314 self.assertTrue(b.endswith(b"o"))
315 self.assertFalse(b.endswith(b"whello"))
316 self.assertFalse(b.endswith(b"no"))
317
318 def test_find(self):
319 b = self.type2test(b'mississippi')
320 self.assertEqual(b.find(b'ss'), 2)
321 self.assertEqual(b.find(b'ss', 3), 5)
322 self.assertEqual(b.find(b'ss', 1, 7), 2)
323 self.assertEqual(b.find(b'ss', 1, 3), -1)
324 self.assertEqual(b.find(b'w'), -1)
325 self.assertEqual(b.find(b'mississippian'), -1)
326
327 def test_rfind(self):
328 b = self.type2test(b'mississippi')
329 self.assertEqual(b.rfind(b'ss'), 5)
330 self.assertEqual(b.rfind(b'ss', 3), 5)
331 self.assertEqual(b.rfind(b'ss', 0, 6), 2)
332 self.assertEqual(b.rfind(b'w'), -1)
333 self.assertEqual(b.rfind(b'mississippian'), -1)
334
335 def test_index(self):
336 b = self.type2test(b'world')
337 self.assertEqual(b.index(b'w'), 0)
338 self.assertEqual(b.index(b'orl'), 1)
339 self.assertRaises(ValueError, b.index, b'worm')
340 self.assertRaises(ValueError, b.index, b'ldo')
341
342 def test_rindex(self):
343 # XXX could be more rigorous
344 b = self.type2test(b'world')
345 self.assertEqual(b.rindex(b'w'), 0)
346 self.assertEqual(b.rindex(b'orl'), 1)
347 self.assertRaises(ValueError, b.rindex, b'worm')
348 self.assertRaises(ValueError, b.rindex, b'ldo')
349
350 def test_replace(self):
351 b = self.type2test(b'mississippi')
352 self.assertEqual(b.replace(b'i', b'a'), b'massassappa')
353 self.assertEqual(b.replace(b'ss', b'x'), b'mixixippi')
354
355 def test_split(self):
356 b = self.type2test(b'mississippi')
357 self.assertEqual(b.split(b'i'), [b'm', b'ss', b'ss', b'pp', b''])
358 self.assertEqual(b.split(b'ss'), [b'mi', b'i', b'ippi'])
359 self.assertEqual(b.split(b'w'), [b])
360
361 def test_split_whitespace(self):
362 for b in (b' arf barf ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf',
363 b'arf\fbarf', b'arf\vbarf'):
364 b = self.type2test(b)
365 self.assertEqual(b.split(), [b'arf', b'barf'])
366 self.assertEqual(b.split(None), [b'arf', b'barf'])
367 self.assertEqual(b.split(None, 2), [b'arf', b'barf'])
368 for b in (b'a\x1Cb', b'a\x1Db', b'a\x1Eb', b'a\x1Fb'):
369 b = self.type2test(b)
370 self.assertEqual(b.split(), [b])
371 self.assertEqual(self.type2test(b' a bb c ').split(None, 0), [b'a bb c '])
372 self.assertEqual(self.type2test(b' a bb c ').split(None, 1), [b'a', b'bb c '])
373 self.assertEqual(self.type2test(b' a bb c ').split(None, 2), [b'a', b'bb', b'c '])
374 self.assertEqual(self.type2test(b' a bb c ').split(None, 3), [b'a', b'bb', b'c'])
375
376 def test_split_string_error(self):
377 self.assertRaises(TypeError, self.type2test(b'a b').split, ' ')
378
Antoine Pitrouf8453022010-01-12 22:05:42 +0000379 def test_split_unicodewhitespace(self):
380 b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F")
381 self.assertEqual(b.split(), [b'\x1c\x1d\x1e\x1f'])
382
Christian Heimes510711d2008-01-30 11:57:58 +0000383 def test_rsplit(self):
384 b = self.type2test(b'mississippi')
385 self.assertEqual(b.rsplit(b'i'), [b'm', b'ss', b'ss', b'pp', b''])
386 self.assertEqual(b.rsplit(b'ss'), [b'mi', b'i', b'ippi'])
387 self.assertEqual(b.rsplit(b'w'), [b])
388
389 def test_rsplit_whitespace(self):
390 for b in (b' arf barf ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf',
391 b'arf\fbarf', b'arf\vbarf'):
392 b = self.type2test(b)
393 self.assertEqual(b.rsplit(), [b'arf', b'barf'])
394 self.assertEqual(b.rsplit(None), [b'arf', b'barf'])
395 self.assertEqual(b.rsplit(None, 2), [b'arf', b'barf'])
396 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 0), [b' a bb c'])
397 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 1), [b' a bb', b'c'])
398 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 2), [b' a', b'bb', b'c'])
399 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 3), [b'a', b'bb', b'c'])
400
401 def test_rsplit_string_error(self):
402 self.assertRaises(TypeError, self.type2test(b'a b').rsplit, ' ')
403
404 def test_rsplit_unicodewhitespace(self):
405 b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F")
Christian Heimes510711d2008-01-30 11:57:58 +0000406 self.assertEqual(b.rsplit(), [b'\x1c\x1d\x1e\x1f'])
407
408 def test_partition(self):
409 b = self.type2test(b'mississippi')
410 self.assertEqual(b.partition(b'ss'), (b'mi', b'ss', b'issippi'))
Antoine Pitrouf8453022010-01-12 22:05:42 +0000411 self.assertEqual(b.partition(b'w'), (b'mississippi', b'', b''))
Christian Heimes510711d2008-01-30 11:57:58 +0000412
413 def test_rpartition(self):
414 b = self.type2test(b'mississippi')
415 self.assertEqual(b.rpartition(b'ss'), (b'missi', b'ss', b'ippi'))
416 self.assertEqual(b.rpartition(b'i'), (b'mississipp', b'i', b''))
Antoine Pitrouf8453022010-01-12 22:05:42 +0000417 self.assertEqual(b.rpartition(b'w'), (b'', b'', b'mississippi'))
Christian Heimes510711d2008-01-30 11:57:58 +0000418
419 def test_pickling(self):
Hirokazu Yamamotod0d0b652008-10-23 00:38:15 +0000420 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
Christian Heimes510711d2008-01-30 11:57:58 +0000421 for b in b"", b"a", b"abc", b"\xffab\x80", b"\0\0\377\0\0":
422 b = self.type2test(b)
423 ps = pickle.dumps(b, proto)
424 q = pickle.loads(ps)
425 self.assertEqual(b, q)
426
427 def test_strip(self):
428 b = self.type2test(b'mississippi')
429 self.assertEqual(b.strip(b'i'), b'mississipp')
430 self.assertEqual(b.strip(b'm'), b'ississippi')
431 self.assertEqual(b.strip(b'pi'), b'mississ')
432 self.assertEqual(b.strip(b'im'), b'ssissipp')
433 self.assertEqual(b.strip(b'pim'), b'ssiss')
434 self.assertEqual(b.strip(b), b'')
435
436 def test_lstrip(self):
437 b = self.type2test(b'mississippi')
438 self.assertEqual(b.lstrip(b'i'), b'mississippi')
439 self.assertEqual(b.lstrip(b'm'), b'ississippi')
440 self.assertEqual(b.lstrip(b'pi'), b'mississippi')
441 self.assertEqual(b.lstrip(b'im'), b'ssissippi')
442 self.assertEqual(b.lstrip(b'pim'), b'ssissippi')
443
444 def test_rstrip(self):
445 b = self.type2test(b'mississippi')
446 self.assertEqual(b.rstrip(b'i'), b'mississipp')
447 self.assertEqual(b.rstrip(b'm'), b'mississippi')
448 self.assertEqual(b.rstrip(b'pi'), b'mississ')
449 self.assertEqual(b.rstrip(b'im'), b'mississipp')
450 self.assertEqual(b.rstrip(b'pim'), b'mississ')
451
452 def test_strip_whitespace(self):
453 b = self.type2test(b' \t\n\r\f\vabc \t\n\r\f\v')
454 self.assertEqual(b.strip(), b'abc')
455 self.assertEqual(b.lstrip(), b'abc \t\n\r\f\v')
456 self.assertEqual(b.rstrip(), b' \t\n\r\f\vabc')
457
458 def test_strip_bytearray(self):
459 self.assertEqual(self.type2test(b'abc').strip(memoryview(b'ac')), b'b')
460 self.assertEqual(self.type2test(b'abc').lstrip(memoryview(b'ac')), b'bc')
461 self.assertEqual(self.type2test(b'abc').rstrip(memoryview(b'ac')), b'ab')
462
463 def test_strip_string_error(self):
464 self.assertRaises(TypeError, self.type2test(b'abc').strip, 'b')
465 self.assertRaises(TypeError, self.type2test(b'abc').lstrip, 'b')
466 self.assertRaises(TypeError, self.type2test(b'abc').rstrip, 'b')
467
468 def test_ord(self):
469 b = self.type2test(b'\0A\x7f\x80\xff')
470 self.assertEqual([ord(b[i:i+1]) for i in range(len(b))],
471 [0, 65, 127, 128, 255])
472
Georg Brandlabc38772009-04-12 15:51:51 +0000473 def test_maketrans(self):
474 transtable = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'
Georg Brandlabc38772009-04-12 15:51:51 +0000475 self.assertEqual(self.type2test.maketrans(b'abc', b'xyz'), transtable)
Antoine Pitrou403ce782009-10-14 17:14:16 +0000476 transtable = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374xyz'
477 self.assertEqual(self.type2test.maketrans(b'\375\376\377', b'xyz'), transtable)
Georg Brandlabc38772009-04-12 15:51:51 +0000478 self.assertRaises(ValueError, self.type2test.maketrans, b'abc', b'xyzq')
479 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def')
480
Christian Heimes510711d2008-01-30 11:57:58 +0000481
482class BytesTest(BaseBytesTest):
483 type2test = bytes
484
Antoine Pitrou2f89aa62008-08-02 21:02:48 +0000485 def test_buffer_is_readonly(self):
Antoine Pitrou47d305d2008-08-16 23:28:44 +0000486 fd = os.dup(sys.stdin.fileno())
487 with open(fd, "rb", buffering=0) as f:
Antoine Pitrou2f89aa62008-08-02 21:02:48 +0000488 self.assertRaises(TypeError, f.readinto, b"")
489
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000490 def test_custom(self):
491 class A:
492 def __bytes__(self):
493 return b'abc'
494 self.assertEqual(bytes(A()), b'abc')
495 class A: pass
496 self.assertRaises(TypeError, bytes, A())
497 class A:
498 def __bytes__(self):
499 return None
500 self.assertRaises(TypeError, bytes, A())
501
Victor Stinner29e762c2011-01-05 03:33:28 +0000502 # Test PyBytes_FromFormat()
503 def test_from_format(self):
504 test.support.import_module('ctypes')
505 from ctypes import pythonapi, py_object, c_int, c_char_p
506 PyBytes_FromFormat = pythonapi.PyBytes_FromFormat
507 PyBytes_FromFormat.restype = py_object
508
509 self.assertEqual(PyBytes_FromFormat(b'format'),
510 b'format')
511
512 self.assertEqual(PyBytes_FromFormat(b'%'), b'%')
513 self.assertEqual(PyBytes_FromFormat(b'%%'), b'%')
514 self.assertEqual(PyBytes_FromFormat(b'%%s'), b'%s')
515 self.assertEqual(PyBytes_FromFormat(b'[%%]'), b'[%]')
516 self.assertEqual(PyBytes_FromFormat(b'%%%c', c_int(ord('_'))), b'%_')
517
518 self.assertEqual(PyBytes_FromFormat(b'c:%c', c_int(255)),
519 b'c:\xff')
520 self.assertEqual(PyBytes_FromFormat(b's:%s', c_char_p(b'cstr')),
521 b's:cstr')
522
Antoine Pitrou2f89aa62008-08-02 21:02:48 +0000523
Christian Heimes510711d2008-01-30 11:57:58 +0000524class ByteArrayTest(BaseBytesTest):
525 type2test = bytearray
Guido van Rossumebea9be2007-04-09 00:49:13 +0000526
Guido van Rossum4dfe8a12006-04-22 23:28:04 +0000527 def test_nohash(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000528 self.assertRaises(TypeError, hash, bytearray())
Guido van Rossum4dfe8a12006-04-22 23:28:04 +0000529
Guido van Rossum254348e2007-11-21 19:29:53 +0000530 def test_bytearray_api(self):
Guido van Rossum75d6f1a2007-05-24 17:52:00 +0000531 short_sample = b"Hello world\n"
Guido van Rossum98297ee2007-11-06 21:34:58 +0000532 sample = short_sample + b"\0"*(20 - len(short_sample))
Guido van Rossumd624f182006-04-24 13:47:05 +0000533 tfn = tempfile.mktemp()
534 try:
535 # Prepare
536 with open(tfn, "wb") as f:
537 f.write(short_sample)
538 # Test readinto
539 with open(tfn, "rb") as f:
Guido van Rossum254348e2007-11-21 19:29:53 +0000540 b = bytearray(20)
Guido van Rossumd624f182006-04-24 13:47:05 +0000541 n = f.readinto(b)
542 self.assertEqual(n, len(short_sample))
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000543 self.assertEqual(list(b), list(sample))
Guido van Rossumd624f182006-04-24 13:47:05 +0000544 # Test writing in binary mode
545 with open(tfn, "wb") as f:
546 f.write(b)
547 with open(tfn, "rb") as f:
548 self.assertEqual(f.read(), sample)
Guido van Rossum13633bb2007-04-13 18:42:35 +0000549 # Text mode is ambiguous; don't test
Guido van Rossumd624f182006-04-24 13:47:05 +0000550 finally:
551 try:
552 os.remove(tfn)
553 except os.error:
554 pass
555
Neal Norwitz6968b052007-02-27 19:02:19 +0000556 def test_reverse(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000557 b = bytearray(b'hello')
Neal Norwitz6968b052007-02-27 19:02:19 +0000558 self.assertEqual(b.reverse(), None)
559 self.assertEqual(b, b'olleh')
Guido van Rossum254348e2007-11-21 19:29:53 +0000560 b = bytearray(b'hello1') # test even number of items
Neal Norwitz6968b052007-02-27 19:02:19 +0000561 b.reverse()
562 self.assertEqual(b, b'1olleh')
Guido van Rossum254348e2007-11-21 19:29:53 +0000563 b = bytearray()
Neal Norwitz6968b052007-02-27 19:02:19 +0000564 b.reverse()
565 self.assertFalse(b)
566
Eli Bendersky4db28d32011-03-03 18:21:02 +0000567 def test_clear(self):
568 b = bytearray(b'python')
569 b.clear()
570 self.assertEqual(b, b'')
571
572 b = bytearray(b'')
573 b.clear()
574 self.assertEqual(b, b'')
575
576 b = bytearray(b'')
577 b.append(ord('r'))
578 b.clear()
579 b.append(ord('p'))
580 self.assertEqual(b, b'p')
581
582 def test_copy(self):
583 b = bytearray(b'abc')
584 bb = b.copy()
585 self.assertEqual(bb, b'abc')
586
587 b = bytearray(b'')
588 bb = b.copy()
589 self.assertEqual(bb, b'')
590
591 # test that it's indeed a copy and not a reference
592 b = bytearray(b'abc')
593 bb = b.copy()
594 self.assertEqual(b, bb)
595 self.assertIsNot(b, bb)
596 bb.append(ord('d'))
597 self.assertEqual(bb, b'abcd')
598 self.assertEqual(b, b'abc')
599
Guido van Rossumd624f182006-04-24 13:47:05 +0000600 def test_regexps(self):
601 def by(s):
Guido van Rossum254348e2007-11-21 19:29:53 +0000602 return bytearray(map(ord, s))
Guido van Rossumd624f182006-04-24 13:47:05 +0000603 b = by("Hello, world")
Antoine Pitroufd036452008-08-19 17:56:33 +0000604 self.assertEqual(re.findall(br"\w+", b), [by("Hello"), by("world")])
Guido van Rossumd624f182006-04-24 13:47:05 +0000605
606 def test_setitem(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000607 b = bytearray([1, 2, 3])
Guido van Rossumd624f182006-04-24 13:47:05 +0000608 b[1] = 100
Guido van Rossum254348e2007-11-21 19:29:53 +0000609 self.assertEqual(b, bytearray([1, 100, 3]))
Guido van Rossumd624f182006-04-24 13:47:05 +0000610 b[-1] = 200
Guido van Rossum254348e2007-11-21 19:29:53 +0000611 self.assertEqual(b, bytearray([1, 100, 200]))
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000612 b[0] = Indexable(10)
Guido van Rossum254348e2007-11-21 19:29:53 +0000613 self.assertEqual(b, bytearray([10, 100, 200]))
Guido van Rossumd624f182006-04-24 13:47:05 +0000614 try:
615 b[3] = 0
616 self.fail("Didn't raise IndexError")
617 except IndexError:
618 pass
619 try:
620 b[-10] = 0
621 self.fail("Didn't raise IndexError")
622 except IndexError:
623 pass
624 try:
625 b[0] = 256
626 self.fail("Didn't raise ValueError")
627 except ValueError:
628 pass
629 try:
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000630 b[0] = Indexable(-1)
Guido van Rossumd624f182006-04-24 13:47:05 +0000631 self.fail("Didn't raise ValueError")
632 except ValueError:
633 pass
634 try:
635 b[0] = None
636 self.fail("Didn't raise TypeError")
637 except TypeError:
638 pass
639
640 def test_delitem(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000641 b = bytearray(range(10))
Guido van Rossumd624f182006-04-24 13:47:05 +0000642 del b[0]
Guido van Rossum254348e2007-11-21 19:29:53 +0000643 self.assertEqual(b, bytearray(range(1, 10)))
Guido van Rossumd624f182006-04-24 13:47:05 +0000644 del b[-1]
Guido van Rossum254348e2007-11-21 19:29:53 +0000645 self.assertEqual(b, bytearray(range(1, 9)))
Guido van Rossumd624f182006-04-24 13:47:05 +0000646 del b[4]
Guido van Rossum254348e2007-11-21 19:29:53 +0000647 self.assertEqual(b, bytearray([1, 2, 3, 4, 6, 7, 8]))
Guido van Rossumd624f182006-04-24 13:47:05 +0000648
649 def test_setslice(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000650 b = bytearray(range(10))
Guido van Rossumd624f182006-04-24 13:47:05 +0000651 self.assertEqual(list(b), list(range(10)))
652
Guido van Rossum254348e2007-11-21 19:29:53 +0000653 b[0:5] = bytearray([1, 1, 1, 1, 1])
654 self.assertEqual(b, bytearray([1, 1, 1, 1, 1, 5, 6, 7, 8, 9]))
Guido van Rossumd624f182006-04-24 13:47:05 +0000655
656 del b[0:-5]
Guido van Rossum254348e2007-11-21 19:29:53 +0000657 self.assertEqual(b, bytearray([5, 6, 7, 8, 9]))
Guido van Rossumd624f182006-04-24 13:47:05 +0000658
Guido van Rossum254348e2007-11-21 19:29:53 +0000659 b[0:0] = bytearray([0, 1, 2, 3, 4])
660 self.assertEqual(b, bytearray(range(10)))
Guido van Rossumd624f182006-04-24 13:47:05 +0000661
Guido van Rossum254348e2007-11-21 19:29:53 +0000662 b[-7:-3] = bytearray([100, 101])
663 self.assertEqual(b, bytearray([0, 1, 2, 100, 101, 7, 8, 9]))
Guido van Rossumd624f182006-04-24 13:47:05 +0000664
665 b[3:5] = [3, 4, 5, 6]
Guido van Rossum254348e2007-11-21 19:29:53 +0000666 self.assertEqual(b, bytearray(range(10)))
Guido van Rossumad7d8d12007-04-13 01:39:34 +0000667
Thomas Wouters9a6e62b2006-08-23 23:20:29 +0000668 b[3:0] = [42, 42, 42]
Guido van Rossum254348e2007-11-21 19:29:53 +0000669 self.assertEqual(b, bytearray([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9]))
Guido van Rossumd624f182006-04-24 13:47:05 +0000670
Thomas Wouters376446d2006-12-19 08:30:14 +0000671 def test_extended_set_del_slice(self):
Mark Dickinsonbc099642010-01-29 17:27:24 +0000672 indices = (0, None, 1, 3, 19, 300, 1<<333, -1, -2, -31, -300)
Thomas Wouters376446d2006-12-19 08:30:14 +0000673 for start in indices:
674 for stop in indices:
675 # Skip invalid step 0
676 for step in indices[1:]:
677 L = list(range(255))
Guido van Rossum254348e2007-11-21 19:29:53 +0000678 b = bytearray(L)
Thomas Wouters376446d2006-12-19 08:30:14 +0000679 # Make sure we have a slice of exactly the right length,
680 # but with different data.
681 data = L[start:stop:step]
682 data.reverse()
683 L[start:stop:step] = data
684 b[start:stop:step] = data
Ezio Melottib3aedd42010-11-20 19:04:17 +0000685 self.assertEqual(b, bytearray(L))
Guido van Rossumad7d8d12007-04-13 01:39:34 +0000686
Thomas Wouters376446d2006-12-19 08:30:14 +0000687 del L[start:stop:step]
688 del b[start:stop:step]
Ezio Melottib3aedd42010-11-20 19:04:17 +0000689 self.assertEqual(b, bytearray(L))
Thomas Wouters376446d2006-12-19 08:30:14 +0000690
Guido van Rossumd624f182006-04-24 13:47:05 +0000691 def test_setslice_trap(self):
692 # This test verifies that we correctly handle assigning self
693 # to a slice of self (the old Lambert Meertens trap).
Guido van Rossum254348e2007-11-21 19:29:53 +0000694 b = bytearray(range(256))
Guido van Rossumd624f182006-04-24 13:47:05 +0000695 b[8:] = b
Guido van Rossum254348e2007-11-21 19:29:53 +0000696 self.assertEqual(b, bytearray(list(range(8)) + list(range(256))))
Guido van Rossumd624f182006-04-24 13:47:05 +0000697
Guido van Rossum13e57212006-04-27 22:54:26 +0000698 def test_iconcat(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000699 b = bytearray(b"abc")
Guido van Rossum13e57212006-04-27 22:54:26 +0000700 b1 = b
Guido van Rossum9c627722007-08-27 18:31:48 +0000701 b += b"def"
702 self.assertEqual(b, b"abcdef")
Guido van Rossum13e57212006-04-27 22:54:26 +0000703 self.assertEqual(b, b1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000704 self.assertTrue(b is b1)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000705 b += b"xyz"
Guido van Rossumad7d8d12007-04-13 01:39:34 +0000706 self.assertEqual(b, b"abcdefxyz")
707 try:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000708 b += ""
Guido van Rossumad7d8d12007-04-13 01:39:34 +0000709 except TypeError:
710 pass
711 else:
712 self.fail("bytes += unicode didn't raise TypeError")
Guido van Rossum13e57212006-04-27 22:54:26 +0000713
714 def test_irepeat(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000715 b = bytearray(b"abc")
Guido van Rossum13e57212006-04-27 22:54:26 +0000716 b1 = b
717 b *= 3
Guido van Rossum9c627722007-08-27 18:31:48 +0000718 self.assertEqual(b, b"abcabcabc")
Guido van Rossum13e57212006-04-27 22:54:26 +0000719 self.assertEqual(b, b1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000720 self.assertTrue(b is b1)
Guido van Rossum13e57212006-04-27 22:54:26 +0000721
722 def test_irepeat_1char(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000723 b = bytearray(b"x")
Guido van Rossum13e57212006-04-27 22:54:26 +0000724 b1 = b
725 b *= 100
Guido van Rossum98297ee2007-11-06 21:34:58 +0000726 self.assertEqual(b, b"x"*100)
Guido van Rossum13e57212006-04-27 22:54:26 +0000727 self.assertEqual(b, b1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000728 self.assertTrue(b is b1)
Guido van Rossum13e57212006-04-27 22:54:26 +0000729
Guido van Rossum20188312006-05-05 15:15:40 +0000730 def test_alloc(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000731 b = bytearray()
Guido van Rossum20188312006-05-05 15:15:40 +0000732 alloc = b.__alloc__()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000733 self.assertTrue(alloc >= 0)
Guido van Rossum20188312006-05-05 15:15:40 +0000734 seq = [alloc]
735 for i in range(100):
Guido van Rossum9c627722007-08-27 18:31:48 +0000736 b += b"x"
Guido van Rossum20188312006-05-05 15:15:40 +0000737 alloc = b.__alloc__()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000738 self.assertTrue(alloc >= len(b))
Guido van Rossum20188312006-05-05 15:15:40 +0000739 if alloc not in seq:
740 seq.append(alloc)
Guido van Rossum20188312006-05-05 15:15:40 +0000741
Neal Norwitz6968b052007-02-27 19:02:19 +0000742 def test_extend(self):
743 orig = b'hello'
Guido van Rossum254348e2007-11-21 19:29:53 +0000744 a = bytearray(orig)
Neal Norwitz6968b052007-02-27 19:02:19 +0000745 a.extend(a)
746 self.assertEqual(a, orig + orig)
747 self.assertEqual(a[5:], orig)
Alexandre Vassalotti09121e82007-12-04 05:51:13 +0000748 a = bytearray(b'')
749 # Test iterators that don't have a __length_hint__
750 a.extend(map(int, orig * 25))
751 a.extend(int(x) for x in orig * 25)
752 self.assertEqual(a, orig * 50)
753 self.assertEqual(a[-5:], orig)
754 a = bytearray(b'')
755 a.extend(iter(map(int, orig * 50)))
756 self.assertEqual(a, orig * 50)
757 self.assertEqual(a[-5:], orig)
758 a = bytearray(b'')
759 a.extend(list(map(int, orig * 50)))
760 self.assertEqual(a, orig * 50)
761 self.assertEqual(a[-5:], orig)
762 a = bytearray(b'')
763 self.assertRaises(ValueError, a.extend, [0, 1, 2, 256])
764 self.assertRaises(ValueError, a.extend, [0, 1, 2, -1])
765 self.assertEqual(len(a), 0)
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000766 a = bytearray(b'')
767 a.extend([Indexable(ord('a'))])
768 self.assertEqual(a, b'a')
Guido van Rossumad7d8d12007-04-13 01:39:34 +0000769
Neal Norwitz6968b052007-02-27 19:02:19 +0000770 def test_remove(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000771 b = bytearray(b'hello')
Neal Norwitz6968b052007-02-27 19:02:19 +0000772 b.remove(ord('l'))
773 self.assertEqual(b, b'helo')
774 b.remove(ord('l'))
775 self.assertEqual(b, b'heo')
776 self.assertRaises(ValueError, lambda: b.remove(ord('l')))
777 self.assertRaises(ValueError, lambda: b.remove(400))
Gregory P. Smith60d241f2007-10-16 06:31:30 +0000778 self.assertRaises(TypeError, lambda: b.remove('e'))
Neal Norwitz6968b052007-02-27 19:02:19 +0000779 # remove first and last
780 b.remove(ord('o'))
781 b.remove(ord('h'))
782 self.assertEqual(b, b'e')
Gregory P. Smith60d241f2007-10-16 06:31:30 +0000783 self.assertRaises(TypeError, lambda: b.remove(b'e'))
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000784 b.remove(Indexable(ord('e')))
785 self.assertEqual(b, b'')
Neal Norwitz6968b052007-02-27 19:02:19 +0000786
787 def test_pop(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000788 b = bytearray(b'world')
Neal Norwitz6968b052007-02-27 19:02:19 +0000789 self.assertEqual(b.pop(), ord('d'))
790 self.assertEqual(b.pop(0), ord('w'))
791 self.assertEqual(b.pop(-2), ord('r'))
792 self.assertRaises(IndexError, lambda: b.pop(10))
Guido van Rossum254348e2007-11-21 19:29:53 +0000793 self.assertRaises(OverflowError, lambda: bytearray().pop())
Mark Dickinson54a3db92009-09-06 10:19:23 +0000794 # test for issue #6846
795 self.assertEqual(bytearray(b'\xff').pop(), 0xff)
Neal Norwitz6968b052007-02-27 19:02:19 +0000796
797 def test_nosort(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000798 self.assertRaises(AttributeError, lambda: bytearray().sort())
Neal Norwitz6968b052007-02-27 19:02:19 +0000799
Neal Norwitz6968b052007-02-27 19:02:19 +0000800 def test_append(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000801 b = bytearray(b'hell')
Neal Norwitz6968b052007-02-27 19:02:19 +0000802 b.append(ord('o'))
803 self.assertEqual(b, b'hello')
804 self.assertEqual(b.append(100), None)
Guido van Rossum254348e2007-11-21 19:29:53 +0000805 b = bytearray()
Neal Norwitz6968b052007-02-27 19:02:19 +0000806 b.append(ord('A'))
807 self.assertEqual(len(b), 1)
Gregory P. Smith60d241f2007-10-16 06:31:30 +0000808 self.assertRaises(TypeError, lambda: b.append(b'o'))
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000809 b = bytearray()
810 b.append(Indexable(ord('A')))
811 self.assertEqual(b, b'A')
Neal Norwitz6968b052007-02-27 19:02:19 +0000812
813 def test_insert(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000814 b = bytearray(b'msssspp')
Neal Norwitz6968b052007-02-27 19:02:19 +0000815 b.insert(1, ord('i'))
816 b.insert(4, ord('i'))
817 b.insert(-2, ord('i'))
818 b.insert(1000, ord('i'))
819 self.assertEqual(b, b'mississippi')
Gregory P. Smith60d241f2007-10-16 06:31:30 +0000820 self.assertRaises(TypeError, lambda: b.insert(0, b'1'))
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000821 b = bytearray()
822 b.insert(0, Indexable(ord('A')))
823 self.assertEqual(b, b'A')
Neal Norwitz6968b052007-02-27 19:02:19 +0000824
Benjamin Peterson0f3641c2008-11-19 22:05:52 +0000825 def test_copied(self):
826 # Issue 4348. Make sure that operations that don't mutate the array
827 # copy the bytes.
828 b = bytearray(b'abc')
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000829 self.assertFalse(b is b.replace(b'abc', b'cde', 0))
Benjamin Peterson0f3641c2008-11-19 22:05:52 +0000830
831 t = bytearray([i for i in range(256)])
832 x = bytearray(b'')
833 self.assertFalse(x is x.translate(t))
834
Guido van Rossum254348e2007-11-21 19:29:53 +0000835 def test_partition_bytearray_doesnt_share_nullstring(self):
836 a, b, c = bytearray(b"x").partition(b"y")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000837 self.assertEqual(b, b"")
838 self.assertEqual(c, b"")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000839 self.assertTrue(b is not c)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000840 b += b"!"
841 self.assertEqual(c, b"")
Guido van Rossum254348e2007-11-21 19:29:53 +0000842 a, b, c = bytearray(b"x").partition(b"y")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000843 self.assertEqual(b, b"")
844 self.assertEqual(c, b"")
845 # Same for rpartition
Guido van Rossum254348e2007-11-21 19:29:53 +0000846 b, c, a = bytearray(b"x").rpartition(b"y")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000847 self.assertEqual(b, b"")
848 self.assertEqual(c, b"")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000849 self.assertTrue(b is not c)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000850 b += b"!"
851 self.assertEqual(c, b"")
Guido van Rossum254348e2007-11-21 19:29:53 +0000852 c, b, a = bytearray(b"x").rpartition(b"y")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000853 self.assertEqual(b, b"")
854 self.assertEqual(c, b"")
855
Antoine Pitrou5504e892008-12-06 21:27:53 +0000856 def test_resize_forbidden(self):
857 # #4509: can't resize a bytearray when there are buffer exports, even
858 # if it wouldn't reallocate the underlying buffer.
859 # Furthermore, no destructive changes to the buffer may be applied
860 # before raising the error.
861 b = bytearray(range(10))
862 v = memoryview(b)
863 def resize(n):
864 b[1:-1] = range(n + 1, 2*n - 1)
865 resize(10)
866 orig = b[:]
867 self.assertRaises(BufferError, resize, 11)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000868 self.assertEqual(b, orig)
Antoine Pitrou5504e892008-12-06 21:27:53 +0000869 self.assertRaises(BufferError, resize, 9)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000870 self.assertEqual(b, orig)
Antoine Pitrou5504e892008-12-06 21:27:53 +0000871 self.assertRaises(BufferError, resize, 0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000872 self.assertEqual(b, orig)
Antoine Pitrou5504e892008-12-06 21:27:53 +0000873 # Other operations implying resize
874 self.assertRaises(BufferError, b.pop, 0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000875 self.assertEqual(b, orig)
Antoine Pitrou5504e892008-12-06 21:27:53 +0000876 self.assertRaises(BufferError, b.remove, b[1])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000877 self.assertEqual(b, orig)
Antoine Pitrou5504e892008-12-06 21:27:53 +0000878 def delitem():
879 del b[1]
880 self.assertRaises(BufferError, delitem)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000881 self.assertEqual(b, orig)
Antoine Pitrou5504e892008-12-06 21:27:53 +0000882 # deleting a non-contiguous slice
883 def delslice():
884 b[1:-1:2] = b""
885 self.assertRaises(BufferError, delslice)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000886 self.assertEqual(b, orig)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000887
Antoine Pitroufc8d6f42010-01-17 12:38:54 +0000888
Christian Heimes510711d2008-01-30 11:57:58 +0000889class AssortedBytesTest(unittest.TestCase):
890 #
891 # Test various combinations of bytes and bytearray
892 #
893
Florent Xiclunaedf5f0d2010-09-03 20:00:37 +0000894 @check_bytes_warnings
Christian Heimes510711d2008-01-30 11:57:58 +0000895 def test_repr_str(self):
Florent Xiclunaedf5f0d2010-09-03 20:00:37 +0000896 for f in str, repr:
897 self.assertEqual(f(bytearray()), "bytearray(b'')")
898 self.assertEqual(f(bytearray([0])), "bytearray(b'\\x00')")
899 self.assertEqual(f(bytearray([0, 1, 254, 255])),
900 "bytearray(b'\\x00\\x01\\xfe\\xff')")
901 self.assertEqual(f(b"abc"), "b'abc'")
902 self.assertEqual(f(b"'"), '''b"'"''') # '''
903 self.assertEqual(f(b"'\""), r"""b'\'"'""") # '
Christian Heimes510711d2008-01-30 11:57:58 +0000904
905 def test_compare_bytes_to_bytearray(self):
906 self.assertEqual(b"abc" == bytes(b"abc"), True)
907 self.assertEqual(b"ab" != bytes(b"abc"), True)
908 self.assertEqual(b"ab" <= bytes(b"abc"), True)
909 self.assertEqual(b"ab" < bytes(b"abc"), True)
910 self.assertEqual(b"abc" >= bytes(b"ab"), True)
911 self.assertEqual(b"abc" > bytes(b"ab"), True)
912
913 self.assertEqual(b"abc" != bytes(b"abc"), False)
914 self.assertEqual(b"ab" == bytes(b"abc"), False)
915 self.assertEqual(b"ab" > bytes(b"abc"), False)
916 self.assertEqual(b"ab" >= bytes(b"abc"), False)
917 self.assertEqual(b"abc" < bytes(b"ab"), False)
918 self.assertEqual(b"abc" <= bytes(b"ab"), False)
919
920 self.assertEqual(bytes(b"abc") == b"abc", True)
921 self.assertEqual(bytes(b"ab") != b"abc", True)
922 self.assertEqual(bytes(b"ab") <= b"abc", True)
923 self.assertEqual(bytes(b"ab") < b"abc", True)
924 self.assertEqual(bytes(b"abc") >= b"ab", True)
925 self.assertEqual(bytes(b"abc") > b"ab", True)
926
927 self.assertEqual(bytes(b"abc") != b"abc", False)
928 self.assertEqual(bytes(b"ab") == b"abc", False)
929 self.assertEqual(bytes(b"ab") > b"abc", False)
930 self.assertEqual(bytes(b"ab") >= b"abc", False)
931 self.assertEqual(bytes(b"abc") < b"ab", False)
932 self.assertEqual(bytes(b"abc") <= b"ab", False)
933
934 def test_doc(self):
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000935 self.assertIsNotNone(bytearray.__doc__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000936 self.assertTrue(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000937 self.assertIsNotNone(bytes.__doc__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000938 self.assertTrue(bytes.__doc__.startswith("bytes("), bytes.__doc__)
Christian Heimes510711d2008-01-30 11:57:58 +0000939
940 def test_from_bytearray(self):
941 sample = bytes(b"Hello world\n\x80\x81\xfe\xff")
942 buf = memoryview(sample)
943 b = bytearray(buf)
944 self.assertEqual(b, bytearray(sample))
945
Florent Xiclunaedf5f0d2010-09-03 20:00:37 +0000946 @check_bytes_warnings
Christian Heimes510711d2008-01-30 11:57:58 +0000947 def test_to_str(self):
Florent Xiclunaedf5f0d2010-09-03 20:00:37 +0000948 self.assertEqual(str(b''), "b''")
949 self.assertEqual(str(b'x'), "b'x'")
950 self.assertEqual(str(b'\x80'), "b'\\x80'")
951 self.assertEqual(str(bytearray(b'')), "bytearray(b'')")
952 self.assertEqual(str(bytearray(b'x')), "bytearray(b'x')")
953 self.assertEqual(str(bytearray(b'\x80')), "bytearray(b'\\x80')")
Christian Heimes510711d2008-01-30 11:57:58 +0000954
955 def test_literal(self):
956 tests = [
957 (b"Wonderful spam", "Wonderful spam"),
958 (br"Wonderful spam too", "Wonderful spam too"),
959 (b"\xaa\x00\000\200", "\xaa\x00\000\200"),
960 (br"\xaa\x00\000\200", r"\xaa\x00\000\200"),
961 ]
962 for b, s in tests:
963 self.assertEqual(b, bytearray(s, 'latin-1'))
964 for c in range(128, 256):
965 self.assertRaises(SyntaxError, eval,
966 'b"%s"' % chr(c))
967
968 def test_translate(self):
969 b = b'hello'
Georg Brandlccc47b62008-12-28 11:44:14 +0000970 ba = bytearray(b)
Christian Heimes510711d2008-01-30 11:57:58 +0000971 rosetta = bytearray(range(0, 256))
972 rosetta[ord('o')] = ord('e')
973 c = b.translate(rosetta, b'l')
974 self.assertEqual(b, b'hello')
975 self.assertEqual(c, b'hee')
Georg Brandlccc47b62008-12-28 11:44:14 +0000976 c = ba.translate(rosetta, b'l')
977 self.assertEqual(ba, b'hello')
978 self.assertEqual(c, b'hee')
979 c = b.translate(None, b'e')
980 self.assertEqual(c, b'hllo')
981 c = ba.translate(None, b'e')
982 self.assertEqual(c, b'hllo')
983 self.assertRaises(TypeError, b.translate, None, None)
984 self.assertRaises(TypeError, ba.translate, None, None)
Christian Heimes510711d2008-01-30 11:57:58 +0000985
986 def test_split_bytearray(self):
987 self.assertEqual(b'a b'.split(memoryview(b' ')), [b'a', b'b'])
988
989 def test_rsplit_bytearray(self):
990 self.assertEqual(b'a b'.rsplit(memoryview(b' ')), [b'a', b'b'])
991
Georg Brandleb2c9642008-05-30 12:05:02 +0000992 def test_return_self(self):
993 # bytearray.replace must always return a new bytearray
994 b = bytearray()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000995 self.assertFalse(b.replace(b'', b'') is b)
Georg Brandleb2c9642008-05-30 12:05:02 +0000996
Barry Warsaw9e9dcd62008-10-17 01:50:37 +0000997 def test_compare(self):
998 if sys.flags.bytes_warning:
Florent Xiclunaedf5f0d2010-09-03 20:00:37 +0000999 def bytes_warning():
1000 return test.support.check_warnings(('', BytesWarning))
1001 with bytes_warning():
1002 b'' == ''
1003 with bytes_warning():
1004 b'' != ''
1005 with bytes_warning():
1006 bytearray(b'') == ''
1007 with bytes_warning():
1008 bytearray(b'') != ''
Barry Warsaw9e9dcd62008-10-17 01:50:37 +00001009 else:
Florent Xiclunaedf5f0d2010-09-03 20:00:37 +00001010 self.skipTest("BytesWarning is needed for this test: use -bb option")
Barry Warsaw9e9dcd62008-10-17 01:50:37 +00001011
Guido van Rossumd624f182006-04-24 13:47:05 +00001012 # Optimizations:
Guido van Rossume06b6b82006-04-23 07:43:54 +00001013 # __iter__? (optimization)
Guido van Rossumd624f182006-04-24 13:47:05 +00001014 # __reversed__? (optimization)
1015
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001016 # XXX More string methods? (Those that don't use character properties)
1017
Neal Norwitz6968b052007-02-27 19:02:19 +00001018 # There are tests in string_tests.py that are more
1019 # comprehensive for things like split, partition, etc.
1020 # Unfortunately they are all bundled with tests that
1021 # are not appropriate for bytes
Guido van Rossume06b6b82006-04-23 07:43:54 +00001022
Guido van Rossum254348e2007-11-21 19:29:53 +00001023 # I've started porting some of those into bytearray_tests.py, we should port
Gregory P. Smith60d241f2007-10-16 06:31:30 +00001024 # the rest that make sense (the code can be cleaned up to use modern
1025 # unittest methods at the same time).
1026
Guido van Rossum254348e2007-11-21 19:29:53 +00001027class BytearrayPEP3137Test(unittest.TestCase,
Gregory P. Smith60d241f2007-10-16 06:31:30 +00001028 test.buffer_tests.MixinBytesBufferCommonTests):
1029 def marshal(self, x):
Guido van Rossum254348e2007-11-21 19:29:53 +00001030 return bytearray(x)
Gregory P. Smith60d241f2007-10-16 06:31:30 +00001031
1032 def test_returns_new_copy(self):
1033 val = self.marshal(b'1234')
1034 # On immutable types these MAY return a reference to themselves
Guido van Rossum254348e2007-11-21 19:29:53 +00001035 # but on mutable types like bytearray they MUST return a new copy.
Gregory P. Smith60d241f2007-10-16 06:31:30 +00001036 for methname in ('zfill', 'rjust', 'ljust', 'center'):
1037 method = getattr(val, methname)
1038 newval = method(3)
1039 self.assertEqual(val, newval)
1040 self.assertTrue(val is not newval,
1041 methname+' returned self on a mutable object')
Antoine Pitroucbaa62502010-01-13 15:03:39 +00001042 for expr in ('val.split()[0]', 'val.rsplit()[0]',
1043 'val.partition(b".")[0]', 'val.rpartition(b".")[2]',
1044 'val.splitlines()[0]', 'val.replace(b"", b"")'):
1045 newval = eval(expr)
1046 self.assertEqual(val, newval)
1047 self.assertTrue(val is not newval,
1048 expr+' returned val on a mutable object')
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001049
Christian Heimes510711d2008-01-30 11:57:58 +00001050class FixedStringTest(test.string_tests.BaseTest):
Georg Brandlc7885542007-03-06 19:16:20 +00001051
Guido van Rossum9c627722007-08-27 18:31:48 +00001052 def fixtype(self, obj):
1053 if isinstance(obj, str):
1054 return obj.encode("utf-8")
1055 return super().fixtype(obj)
1056
Georg Brandlc7885542007-03-06 19:16:20 +00001057 # Currently the bytes containment testing uses a single integer
1058 # value. This may not be the final design, but until then the
1059 # bytes section with in a bytes containment not valid
1060 def test_contains(self):
1061 pass
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001062 def test_expandtabs(self):
1063 pass
1064 def test_upper(self):
1065 pass
1066 def test_lower(self):
1067 pass
Georg Brandlc7885542007-03-06 19:16:20 +00001068
Christian Heimes510711d2008-01-30 11:57:58 +00001069class ByteArrayAsStringTest(FixedStringTest):
1070 type2test = bytearray
1071
1072class BytesAsStringTest(FixedStringTest):
1073 type2test = bytes
1074
Georg Brandlc7885542007-03-06 19:16:20 +00001075
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001076class SubclassTest(unittest.TestCase):
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001077
1078 def test_basic(self):
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001079 self.assertTrue(issubclass(self.subclass2test, self.type2test))
Ezio Melottie9615932010-01-24 19:26:24 +00001080 self.assertIsInstance(self.subclass2test(), self.type2test)
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001081
1082 a, b = b"abcd", b"efgh"
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001083 _a, _b = self.subclass2test(a), self.subclass2test(b)
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001084
1085 # test comparison operators with subclass instances
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001086 self.assertTrue(_a == _a)
1087 self.assertTrue(_a != _b)
1088 self.assertTrue(_a < _b)
1089 self.assertTrue(_a <= _b)
1090 self.assertTrue(_b >= _a)
1091 self.assertTrue(_b > _a)
1092 self.assertTrue(_a is not a)
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001093
1094 # test concat of subclass instances
1095 self.assertEqual(a + b, _a + _b)
1096 self.assertEqual(a + b, a + _b)
1097 self.assertEqual(a + b, _a + b)
1098
1099 # test repeat
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001100 self.assertTrue(a*5 == _a*5)
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001101
1102 def test_join(self):
1103 # Make sure join returns a NEW object for single item sequences
1104 # involving a subclass.
1105 # Make sure that it is of the appropriate type.
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001106 s1 = self.subclass2test(b"abcd")
1107 s2 = self.type2test().join([s1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001108 self.assertTrue(s1 is not s2)
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001109 self.assertTrue(type(s2) is self.type2test, type(s2))
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001110
1111 # Test reverse, calling join on subclass
1112 s3 = s1.join([b"abcd"])
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001113 self.assertTrue(type(s3) is self.type2test)
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001114
1115 def test_pickle(self):
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001116 a = self.subclass2test(b"abcd")
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001117 a.x = 10
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001118 a.y = self.subclass2test(b"efgh")
Hirokazu Yamamotod0d0b652008-10-23 00:38:15 +00001119 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001120 b = pickle.loads(pickle.dumps(a, proto))
1121 self.assertNotEqual(id(a), id(b))
1122 self.assertEqual(a, b)
1123 self.assertEqual(a.x, b.x)
1124 self.assertEqual(a.y, b.y)
1125 self.assertEqual(type(a), type(b))
1126 self.assertEqual(type(a.y), type(b.y))
1127
1128 def test_copy(self):
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001129 a = self.subclass2test(b"abcd")
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001130 a.x = 10
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001131 a.y = self.subclass2test(b"efgh")
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001132 for copy_method in (copy.copy, copy.deepcopy):
1133 b = copy_method(a)
1134 self.assertNotEqual(id(a), id(b))
1135 self.assertEqual(a, b)
1136 self.assertEqual(a.x, b.x)
1137 self.assertEqual(a.y, b.y)
1138 self.assertEqual(type(a), type(b))
1139 self.assertEqual(type(a.y), type(b.y))
1140
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001141
1142class ByteArraySubclass(bytearray):
1143 pass
1144
1145class BytesSubclass(bytes):
1146 pass
1147
1148class ByteArraySubclassTest(SubclassTest):
1149 type2test = bytearray
1150 subclass2test = ByteArraySubclass
1151
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001152 def test_init_override(self):
Guido van Rossum254348e2007-11-21 19:29:53 +00001153 class subclass(bytearray):
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001154 def __init__(me, newarg=1, *args, **kwargs):
1155 bytearray.__init__(me, *args, **kwargs)
1156 x = subclass(4, b"abcd")
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001157 x = subclass(4, source=b"abcd")
1158 self.assertEqual(x, b"abcd")
1159 x = subclass(newarg=4, source=b"abcd")
1160 self.assertEqual(x, b"abcd")
1161
1162
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001163class BytesSubclassTest(SubclassTest):
1164 type2test = bytes
1165 subclass2test = BytesSubclass
1166
1167
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001168def test_main():
Antoine Pitrou403ce782009-10-14 17:14:16 +00001169 test.support.run_unittest(
1170 BytesTest, AssortedBytesTest, BytesAsStringTest,
Alexandre Vassalotti41f58a72010-01-12 01:23:09 +00001171 ByteArrayTest, ByteArrayAsStringTest, BytesSubclassTest,
1172 ByteArraySubclassTest, BytearrayPEP3137Test)
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001173
1174if __name__ == "__main__":
Guido van Rossuma6c04be2007-11-03 00:24:24 +00001175 test_main()