summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
Diffstat (limited to 'Lib')
-rwxr-xr-xLib/base64.py26
-rw-r--r--Lib/dumbdbm.py2
-rw-r--r--Lib/encodings/idna.py4
-rw-r--r--Lib/encodings/punycode.py6
-rw-r--r--Lib/io.py12
-rw-r--r--Lib/pickle.py2
-rw-r--r--Lib/plat-mac/aepack.py2
-rw-r--r--Lib/plat-mac/aetypes.py2
-rw-r--r--Lib/string.py2
-rw-r--r--Lib/tarfile.py2
-rw-r--r--Lib/test/string_tests.py4
-rw-r--r--Lib/test/test_audioop.py8
-rwxr-xr-xLib/test/test_binascii.py6
-rw-r--r--Lib/test/test_bytes.py316
-rw-r--r--Lib/test/test_codeccallbacks.py16
-rw-r--r--Lib/test/test_collections.py2
-rw-r--r--Lib/test/test_datetime.py8
-rw-r--r--Lib/test/test_exceptions.py4
-rw-r--r--Lib/test/test_float.py8
-rw-r--r--Lib/test/test_io.py8
-rw-r--r--Lib/test/test_marshal.py2
-rw-r--r--Lib/test/test_struct.py6
-rw-r--r--Lib/test/test_unicode.py4
-rw-r--r--Lib/test/test_unicodedata.py2
-rw-r--r--Lib/test/test_zipimport.py6
-rw-r--r--Lib/uuid.py2
26 files changed, 231 insertions, 231 deletions
diff --git a/Lib/base64.py b/Lib/base64.py
index 18beffc..fc05ea9 100755
--- a/Lib/base64.py
+++ b/Lib/base64.py
@@ -27,13 +27,13 @@ __all__ = [
]
-bytes_buffer = (bytes, buffer) # Types acceptable as binary data
+bytes_types = (bytes, bytearray) # Types acceptable as binary data
def _translate(s, altchars):
- if not isinstance(s, bytes_buffer):
+ if not isinstance(s, bytes_types):
raise TypeError("expected bytes, not %s" % s.__class__.__name__)
- translation = buffer(range(256))
+ translation = bytearray(range(256))
for k, v in altchars.items():
translation[ord(k)] = v[0]
return s.translate(translation)
@@ -52,12 +52,12 @@ def b64encode(s, altchars=None):
The encoded byte string is returned.
"""
- if not isinstance(s, bytes_buffer):
+ if not isinstance(s, bytes_types):
s = bytes(s, "ascii")
# Strip off the trailing newline
encoded = binascii.b2a_base64(s)[:-1]
if altchars is not None:
- if not isinstance(altchars, bytes_buffer):
+ if not isinstance(altchars, bytes_types):
altchars = bytes(altchars, "ascii")
assert len(altchars) == 2, repr(altchars)
return _translate(encoded, {'+': altchars[0:1], '/': altchars[1:2]})
@@ -75,10 +75,10 @@ def b64decode(s, altchars=None):
s were incorrectly padded or if there are non-alphabet characters
present in the string.
"""
- if not isinstance(s, bytes_buffer):
+ if not isinstance(s, bytes_types):
s = bytes(s)
if altchars is not None:
- if not isinstance(altchars, bytes_buffer):
+ if not isinstance(altchars, bytes_types):
altchars = bytes(altchars, "ascii")
assert len(altchars) == 2, repr(altchars)
s = _translate(s, {chr(altchars[0]): b'+', chr(altchars[1]): b'/'})
@@ -147,7 +147,7 @@ def b32encode(s):
s is the byte string to encode. The encoded byte string is returned.
"""
- if not isinstance(s, bytes_buffer):
+ if not isinstance(s, bytes_types):
s = bytes(s)
quanta, leftover = divmod(len(s), 5)
# Pad the last quantum with zero bits if necessary
@@ -204,7 +204,7 @@ def b32decode(s, casefold=False, map01=None):
the input is incorrectly padded or if there are non-alphabet
characters present in the input.
"""
- if not isinstance(s, bytes_buffer):
+ if not isinstance(s, bytes_types):
s = bytes(s)
quanta, leftover = divmod(len(s), 8)
if leftover:
@@ -213,7 +213,7 @@ def b32decode(s, casefold=False, map01=None):
# False, or the character to map the digit 1 (one) to. It should be
# either L (el) or I (eye).
if map01:
- if not isinstance(map01, bytes_buffer):
+ if not isinstance(map01, bytes_types):
map01 = bytes(map01)
assert len(map01) == 1, repr(map01)
s = _translate(s, {b'0': b'O', b'1': map01})
@@ -283,7 +283,7 @@ def b16decode(s, casefold=False):
s were incorrectly padded or if there are non-alphabet characters
present in the string.
"""
- if not isinstance(s, bytes_buffer):
+ if not isinstance(s, bytes_types):
s = bytes(s)
if casefold:
s = s.upper()
@@ -330,7 +330,7 @@ def encodestring(s):
Argument and return value are bytes.
"""
- if not isinstance(s, bytes_buffer):
+ if not isinstance(s, bytes_types):
raise TypeError("expected bytes, not %s" % s.__class__.__name__)
pieces = []
for i in range(0, len(s), MAXBINSIZE):
@@ -344,7 +344,7 @@ def decodestring(s):
Argument and return value are bytes.
"""
- if not isinstance(s, bytes_buffer):
+ if not isinstance(s, bytes_types):
raise TypeError("expected bytes, not %s" % s.__class__.__name__)
return binascii.a2b_base64(s)
diff --git a/Lib/dumbdbm.py b/Lib/dumbdbm.py
index 78e4999..7741fbb 100644
--- a/Lib/dumbdbm.py
+++ b/Lib/dumbdbm.py
@@ -163,7 +163,7 @@ class _Database(UserDict.DictMixin):
if not isinstance(key, bytes):
raise TypeError("keys must be bytes")
key = key.decode("latin-1") # hashable bytes
- if not isinstance(val, (buffer, bytes)):
+ if not isinstance(val, (bytes, bytearray)):
raise TypeError("values must be byte strings")
if key not in self._index:
self._addkey(key, self._addval(val))
diff --git a/Lib/encodings/idna.py b/Lib/encodings/idna.py
index 30f507a..c2ba1da 100644
--- a/Lib/encodings/idna.py
+++ b/Lib/encodings/idna.py
@@ -153,7 +153,7 @@ class Codec(codecs.Codec):
if not input:
return b'', 0
- result = buffer()
+ result = bytearray()
labels = dots.split(input)
if labels and not labels[-1]:
trailing_dot = b'.'
@@ -216,7 +216,7 @@ class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
if labels:
trailing_dot = b'.'
- result = buffer()
+ result = bytearray()
size = 0
for label in labels:
if size:
diff --git a/Lib/encodings/punycode.py b/Lib/encodings/punycode.py
index 56e6958..b801a46 100644
--- a/Lib/encodings/punycode.py
+++ b/Lib/encodings/punycode.py
@@ -10,7 +10,7 @@ import codecs
def segregate(str):
"""3.1 Basic code point segregation"""
- base = buffer()
+ base = bytearray()
extended = set()
for c in str:
if ord(c) < 128:
@@ -78,7 +78,7 @@ def T(j, bias):
digits = b"abcdefghijklmnopqrstuvwxyz0123456789"
def generate_generalized_integer(N, bias):
"""3.3 Generalized variable-length integers"""
- result = buffer()
+ result = bytearray()
j = 0
while 1:
t = T(j, bias)
@@ -107,7 +107,7 @@ def adapt(delta, first, numchars):
def generate_integers(baselen, deltas):
"""3.4 Bias adaptation"""
# Punycode parameters: initial bias = 72, damp = 700, skew = 38
- result = buffer()
+ result = bytearray()
bias = 72
for points, delta in enumerate(deltas):
s = generate_generalized_integer(delta, bias)
diff --git a/Lib/io.py b/Lib/io.py
index 364e6d0..f66f48b 100644
--- a/Lib/io.py
+++ b/Lib/io.py
@@ -391,7 +391,7 @@ class IOBase(metaclass=abc.ABCMeta):
return 1
if limit is None:
limit = -1
- res = buffer()
+ res = bytearray()
while limit < 0 or len(res) < limit:
b = self.read(nreadahead())
if not b:
@@ -454,14 +454,14 @@ class RawIOBase(IOBase):
n = -1
if n < 0:
return self.readall()
- b = buffer(n.__index__())
+ b = bytearray(n.__index__())
n = self.readinto(b)
del b[n:]
return bytes(b)
def readall(self):
"""readall() -> bytes. Read until EOF, using multiple read() call."""
- res = buffer()
+ res = bytearray()
while True:
data = self.read(DEFAULT_BUFFER_SIZE)
if not data:
@@ -655,7 +655,7 @@ class BytesIO(BufferedIOBase):
# XXX More docs
def __init__(self, initial_bytes=None):
- buf = buffer()
+ buf = bytearray()
if initial_bytes is not None:
buf += initial_bytes
self._buffer = buf
@@ -823,7 +823,7 @@ class BufferedWriter(_BufferedIOMixin):
self.max_buffer_size = (2*buffer_size
if max_buffer_size is None
else max_buffer_size)
- self._write_buf = buffer()
+ self._write_buf = bytearray()
def write(self, b):
if self.closed:
@@ -1276,7 +1276,7 @@ class TextIOWrapper(TextIOBase):
try:
decoder.setstate((b"", decoder_state))
n = 0
- bb = buffer(1)
+ bb = bytearray(1)
for i, bb[0] in enumerate(readahead):
n += len(decoder.decode(bb))
if n >= needed:
diff --git a/Lib/pickle.py b/Lib/pickle.py
index d7bf24e..e3c112f 100644
--- a/Lib/pickle.py
+++ b/Lib/pickle.py
@@ -39,7 +39,7 @@ __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
"Unpickler", "dump", "dumps", "load", "loads"]
# Shortcut for use in isinstance testing
-bytes_types = (bytes, buffer, memoryview)
+bytes_types = (bytes, bytearray, memoryview)
# These are purely informational; no code uses these.
format_version = "2.0" # File format version we write
diff --git a/Lib/plat-mac/aepack.py b/Lib/plat-mac/aepack.py
index e958b85..5f8efd2 100644
--- a/Lib/plat-mac/aepack.py
+++ b/Lib/plat-mac/aepack.py
@@ -98,7 +98,7 @@ def pack(x, forcetype = None):
return AE.AECreateDesc(b'long', struct.pack('l', x))
if isinstance(x, float):
return AE.AECreateDesc(b'doub', struct.pack('d', x))
- if isinstance(x, (bytes, buffer)):
+ if isinstance(x, (bytes, bytearray)):
return AE.AECreateDesc(b'TEXT', x)
if isinstance(x, str):
# See http://developer.apple.com/documentation/Carbon/Reference/Apple_Event_Manager/Reference/reference.html#//apple_ref/doc/constant_group/typeUnicodeText
diff --git a/Lib/plat-mac/aetypes.py b/Lib/plat-mac/aetypes.py
index d29ea97..6c031a1 100644
--- a/Lib/plat-mac/aetypes.py
+++ b/Lib/plat-mac/aetypes.py
@@ -22,7 +22,7 @@ def _four_char_code(four_chars):
four_chars must contain only ASCII characters.
"""
- if isinstance(four_chars, (bytes, buffer)):
+ if isinstance(four_chars, (bytes, bytearray)):
b = bytes(four_chars[:4])
n = len(b)
if n < 4:
diff --git a/Lib/string.py b/Lib/string.py
index 6117ac0..7f67abd 100644
--- a/Lib/string.py
+++ b/Lib/string.py
@@ -53,7 +53,7 @@ def maketrans(frm: bytes, to: bytes) -> bytes:
raise ValueError("maketrans arguments must have same length")
if not (isinstance(frm, bytes) and isinstance(to, bytes)):
raise TypeError("maketrans arguments must be bytes objects")
- L = buffer(range(256))
+ L = bytearray(range(256))
for i, c in enumerate(frm):
L[c] = to[i]
return bytes(L)
diff --git a/Lib/tarfile.py b/Lib/tarfile.py
index aef8f94..23252f4 100644
--- a/Lib/tarfile.py
+++ b/Lib/tarfile.py
@@ -222,7 +222,7 @@ def itn(n, digits=8, format=DEFAULT_FORMAT):
# this could raise OverflowError.
n = struct.unpack("L", struct.pack("l", n))[0]
- s = buffer()
+ s = bytearray()
for i in range(digits - 1):
s.insert(0, n & 0o377)
n >>= 8
diff --git a/Lib/test/string_tests.py b/Lib/test/string_tests.py
index 116145e..e9285a6 100644
--- a/Lib/test/string_tests.py
+++ b/Lib/test/string_tests.py
@@ -532,8 +532,8 @@ class BaseTest(unittest.TestCase):
# XXX Commented out. Is there any reason to support buffer objects
# as arguments for str.replace()? GvR
-## ba = buffer('a')
-## bb = buffer('b')
+## ba = bytearray('a')
+## bb = bytearray('b')
## EQ("bbc", "abc", "replace", ba, bb)
## EQ("aac", "abc", "replace", bb, ba)
diff --git a/Lib/test/test_audioop.py b/Lib/test/test_audioop.py
index fada40c..ffb1cd5 100644
--- a/Lib/test/test_audioop.py
+++ b/Lib/test/test_audioop.py
@@ -87,7 +87,7 @@ def testadd(data):
print('add')
data2 = []
for d in data:
- str = buffer(len(d))
+ str = bytearray(len(d))
for i,b in enumerate(d):
str[i] = 2*b
data2.append(str)
@@ -177,7 +177,7 @@ def testmul(data):
print('mul')
data2 = []
for d in data:
- str = buffer(len(d))
+ str = bytearray(len(d))
for i,b in enumerate(d):
str[i] = 2*b
data2.append(str)
@@ -207,7 +207,7 @@ def testreverse(data):
def testtomono(data):
if verbose:
print('tomono')
- data2 = buffer()
+ data2 = bytearray()
for d in data[0]:
data2.append(d)
data2.append(d)
@@ -218,7 +218,7 @@ def testtomono(data):
def testtostereo(data):
if verbose:
print('tostereo')
- data2 = buffer()
+ data2 = bytearray()
for d in data[0]:
data2.append(d)
data2.append(d)
diff --git a/Lib/test/test_binascii.py b/Lib/test/test_binascii.py
index fa13563..fb9a666 100755
--- a/Lib/test/test_binascii.py
+++ b/Lib/test/test_binascii.py
@@ -56,7 +56,7 @@ class BinASCIITest(unittest.TestCase):
a = binascii.b2a_base64(b)
lines.append(a)
- fillers = buffer()
+ fillers = bytearray()
valid = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/"
for i in range(256):
if i not in valid:
@@ -64,7 +64,7 @@ class BinASCIITest(unittest.TestCase):
def addnoise(line):
noise = fillers
ratio = len(line) // len(noise)
- res = buffer()
+ res = bytearray()
while line and noise:
if len(line) // len(noise) > ratio:
c, line = line[0], line[1:]
@@ -72,7 +72,7 @@ class BinASCIITest(unittest.TestCase):
c, noise = noise[0], noise[1:]
res.append(c)
return res + noise + line
- res = buffer()
+ res = bytearray()
for line in map(addnoise, lines):
b = binascii.a2b_base64(line)
res += b
diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py
index b3c13b3..5c3a3ae 100644
--- a/Lib/test/test_bytes.py
+++ b/Lib/test/test_bytes.py
@@ -1,4 +1,4 @@
-"""Unit tests for the bytes and buffer types.
+"""Unit tests for the bytes and bytearray types.
XXX This is a mess. Common tests should be moved to buffer_tests.py,
which itself ought to be unified with string_tests.py (and the latter
@@ -27,12 +27,12 @@ class BytesTest(unittest.TestCase):
warnings.filters = self.warning_filters
def test_basics(self):
- b = buffer()
- self.assertEqual(type(b), buffer)
- self.assertEqual(b.__class__, buffer)
+ b = bytearray()
+ self.assertEqual(type(b), bytearray)
+ self.assertEqual(b.__class__, bytearray)
def test_empty_sequence(self):
- b = buffer()
+ b = bytearray()
self.assertEqual(len(b), 0)
self.assertRaises(IndexError, lambda: b[0])
self.assertRaises(IndexError, lambda: b[1])
@@ -48,7 +48,7 @@ class BytesTest(unittest.TestCase):
def test_from_list(self):
ints = list(range(256))
- b = buffer(i for i in ints)
+ b = bytearray(i for i in ints)
self.assertEqual(len(b), 256)
self.assertEqual(list(b), ints)
@@ -58,57 +58,57 @@ class BytesTest(unittest.TestCase):
self.i = i
def __index__(self):
return self.i
- b = buffer([C(), C(1), C(254), C(255)])
+ b = bytearray([C(), C(1), C(254), C(255)])
self.assertEqual(list(b), [0, 1, 254, 255])
- self.assertRaises(ValueError, buffer, [C(-1)])
- self.assertRaises(ValueError, buffer, [C(256)])
+ self.assertRaises(ValueError, bytearray, [C(-1)])
+ self.assertRaises(ValueError, bytearray, [C(256)])
def test_from_ssize(self):
- self.assertEqual(buffer(0), b'')
- self.assertEqual(buffer(1), b'\x00')
- self.assertEqual(buffer(5), b'\x00\x00\x00\x00\x00')
- self.assertRaises(ValueError, buffer, -1)
+ self.assertEqual(bytearray(0), b'')
+ self.assertEqual(bytearray(1), b'\x00')
+ self.assertEqual(bytearray(5), b'\x00\x00\x00\x00\x00')
+ self.assertRaises(ValueError, bytearray, -1)
- self.assertEqual(buffer('0', 'ascii'), b'0')
- self.assertEqual(buffer(b'0'), b'0')
+ self.assertEqual(bytearray('0', 'ascii'), b'0')
+ self.assertEqual(bytearray(b'0'), b'0')
def test_constructor_type_errors(self):
- self.assertRaises(TypeError, buffer, 0.0)
+ self.assertRaises(TypeError, bytearray, 0.0)
class C:
pass
- self.assertRaises(TypeError, buffer, ["0"])
- self.assertRaises(TypeError, buffer, [0.0])
- self.assertRaises(TypeError, buffer, [None])
- self.assertRaises(TypeError, buffer, [C()])
+ self.assertRaises(TypeError, bytearray, ["0"])
+ self.assertRaises(TypeError, bytearray, [0.0])
+ self.assertRaises(TypeError, bytearray, [None])
+ self.assertRaises(TypeError, bytearray, [C()])
def test_constructor_value_errors(self):
- self.assertRaises(ValueError, buffer, [-1])
- self.assertRaises(ValueError, buffer, [-sys.maxint])
- self.assertRaises(ValueError, buffer, [-sys.maxint-1])
- self.assertRaises(ValueError, buffer, [-sys.maxint-2])
- self.assertRaises(ValueError, buffer, [-10**100])
- self.assertRaises(ValueError, buffer, [256])
- self.assertRaises(ValueError, buffer, [257])
- self.assertRaises(ValueError, buffer, [sys.maxint])
- self.assertRaises(ValueError, buffer, [sys.maxint+1])
- self.assertRaises(ValueError, buffer, [10**100])
+ self.assertRaises(ValueError, bytearray, [-1])
+ self.assertRaises(ValueError, bytearray, [-sys.maxint])
+ self.assertRaises(ValueError, bytearray, [-sys.maxint-1])
+ self.assertRaises(ValueError, bytearray, [-sys.maxint-2])
+ self.assertRaises(ValueError, bytearray, [-10**100])
+ self.assertRaises(ValueError, bytearray, [256])
+ self.assertRaises(ValueError, bytearray, [257])
+ self.assertRaises(ValueError, bytearray, [sys.maxint])
+ self.assertRaises(ValueError, bytearray, [sys.maxint+1])
+ self.assertRaises(ValueError, bytearray, [10**100])
def test_repr_str(self):
warnings.simplefilter('ignore', BytesWarning)
for f in str, repr:
- self.assertEqual(f(buffer()), "buffer(b'')")
- self.assertEqual(f(buffer([0])), "buffer(b'\\x00')")
- self.assertEqual(f(buffer([0, 1, 254, 255])),
- "buffer(b'\\x00\\x01\\xfe\\xff')")
+ self.assertEqual(f(bytearray()), "bytearray(b'')")
+ self.assertEqual(f(bytearray([0])), "bytearray(b'\\x00')")
+ self.assertEqual(f(bytearray([0, 1, 254, 255])),
+ "bytearray(b'\\x00\\x01\\xfe\\xff')")
self.assertEqual(f(b"abc"), "b'abc'")
self.assertEqual(f(b"'"), '''b"'"''')
self.assertEqual(f(b"'\""), r"""b'\'"'""")
def test_compare(self):
- b1 = buffer([1, 2, 3])
- b2 = buffer([1, 2, 3])
- b3 = buffer([1, 3])
+ b1 = bytearray([1, 2, 3])
+ b2 = bytearray([1, 2, 3])
+ b3 = bytearray([1, 3])
self.assertEqual(b1, b2)
self.failUnless(b2 != b3)
@@ -128,7 +128,7 @@ class BytesTest(unittest.TestCase):
self.failIf(b3 < b2)
self.failIf(b3 <= b2)
- def test_compare_bytes_to_buffer(self):
+ def test_compare_bytes_to_bytearray(self):
self.assertEqual(b"abc" == bytes(b"abc"), True)
self.assertEqual(b"ab" != bytes(b"abc"), True)
self.assertEqual(b"ab" <= bytes(b"abc"), True)
@@ -165,19 +165,19 @@ class BytesTest(unittest.TestCase):
self.assertEqual(b"\0\0\0a\0\0\0b\0\0\0c" == "abc", False)
self.assertEqual(b"a\0b\0c\0" == "abc", False)
self.assertEqual(b"a\0\0\0b\0\0\0c\0\0\0" == "abc", False)
- self.assertEqual(buffer() == str(), False)
- self.assertEqual(buffer() != str(), True)
+ self.assertEqual(bytearray() == str(), False)
+ self.assertEqual(bytearray() != str(), True)
def test_nohash(self):
- self.assertRaises(TypeError, hash, buffer())
+ self.assertRaises(TypeError, hash, bytearray())
def test_doc(self):
- self.failUnless(buffer.__doc__ != None)
- self.failUnless(buffer.__doc__.startswith("buffer("), buffer.__doc__)
+ self.failUnless(bytearray.__doc__ != None)
+ self.failUnless(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__)
self.failUnless(bytes.__doc__ != None)
self.failUnless(bytes.__doc__.startswith("bytes("), bytes.__doc__)
- def test_buffer_api(self):
+ def test_bytearray_api(self):
short_sample = b"Hello world\n"
sample = short_sample + b"\0"*(20 - len(short_sample))
tfn = tempfile.mktemp()
@@ -187,7 +187,7 @@ class BytesTest(unittest.TestCase):
f.write(short_sample)
# Test readinto
with open(tfn, "rb") as f:
- b = buffer(20)
+ b = bytearray(20)
n = f.readinto(b)
self.assertEqual(n, len(short_sample))
self.assertEqual(list(b), list(sample))
@@ -205,25 +205,25 @@ class BytesTest(unittest.TestCase):
def test_reversed(self):
input = list(map(ord, "Hello"))
- b = buffer(input)
+ b = bytearray(input)
output = list(reversed(b))
input.reverse()
self.assertEqual(output, input)
def test_reverse(self):
- b = buffer(b'hello')
+ b = bytearray(b'hello')
self.assertEqual(b.reverse(), None)
self.assertEqual(b, b'olleh')
- b = buffer(b'hello1') # test even number of items
+ b = bytearray(b'hello1') # test even number of items
b.reverse()
self.assertEqual(b, b'1olleh')
- b = buffer()
+ b = bytearray()
b.reverse()
self.assertFalse(b)
def test_getslice(self):
def by(s):
- return buffer(map(ord, s))
+ return bytearray(map(ord, s))
b = by("Hello, world")
self.assertEqual(b[:5], by("Hello"))
@@ -244,33 +244,33 @@ class BytesTest(unittest.TestCase):
def test_extended_getslice(self):
# Test extended slicing by comparing with list slicing.
L = list(range(255))
- b = buffer(L)
+ b = bytearray(L)
indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
for start in indices:
for stop in indices:
# Skip step 0 (invalid)
for step in indices[1:]:
- self.assertEqual(b[start:stop:step], buffer(L[start:stop:step]))
+ self.assertEqual(b[start:stop:step], bytearray(L[start:stop:step]))
def test_regexps(self):
def by(s):
- return buffer(map(ord, s))
+ return bytearray(map(ord, s))
b = by("Hello, world")
self.assertEqual(re.findall(r"\w+", b), [by("Hello"), by("world")])
def test_setitem(self):
- b = buffer([1, 2, 3])
+ b = bytearray([1, 2, 3])
b[1] = 100
- self.assertEqual(b, buffer([1, 100, 3]))
+ self.assertEqual(b, bytearray([1, 100, 3]))
b[-1] = 200
- self.assertEqual(b, buffer([1, 100, 200]))
+ self.assertEqual(b, bytearray([1, 100, 200]))
class C:
def __init__(self, i=0):
self.i = i
def __index__(self):
return self.i
b[0] = C(10)
- self.assertEqual(b, buffer([10, 100, 200]))
+ self.assertEqual(b, bytearray([10, 100, 200]))
try:
b[3] = 0
self.fail("Didn't raise IndexError")
@@ -298,35 +298,35 @@ class BytesTest(unittest.TestCase):
pass
def test_delitem(self):
- b = buffer(range(10))
+ b = bytearray(range(10))
del b[0]
- self.assertEqual(b, buffer(range(1, 10)))
+ self.assertEqual(b, bytearray(range(1, 10)))
del b[-1]
- self.assertEqual(b, buffer(range(1, 9)))
+ self.assertEqual(b, bytearray(range(1, 9)))
del b[4]
- self.assertEqual(b, buffer([1, 2, 3, 4, 6, 7, 8]))
+ self.assertEqual(b, bytearray([1, 2, 3, 4, 6, 7, 8]))
def test_setslice(self):
- b = buffer(range(10))
+ b = bytearray(range(10))
self.assertEqual(list(b), list(range(10)))
- b[0:5] = buffer([1, 1, 1, 1, 1])
- self.assertEqual(b, buffer([1, 1, 1, 1, 1, 5, 6, 7, 8, 9]))
+ b[0:5] = bytearray([1, 1, 1, 1, 1])
+ self.assertEqual(b, bytearray([1, 1, 1, 1, 1, 5, 6, 7, 8, 9]))
del b[0:-5]
- self.assertEqual(b, buffer([5, 6, 7, 8, 9]))
+ self.assertEqual(b, bytearray([5, 6, 7, 8, 9]))
- b[0:0] = buffer([0, 1, 2, 3, 4])
- self.assertEqual(b, buffer(range(10)))
+ b[0:0] = bytearray([0, 1, 2, 3, 4])
+ self.assertEqual(b, bytearray(range(10)))
- b[-7:-3] = buffer([100, 101])
- self.assertEqual(b, buffer([0, 1, 2, 100, 101, 7, 8, 9]))
+ b[-7:-3] = bytearray([100, 101])
+ self.assertEqual(b, bytearray([0, 1, 2, 100, 101, 7, 8, 9]))
b[3:5] = [3, 4, 5, 6]
- self.assertEqual(b, buffer(range(10)))
+ self.assertEqual(b, bytearray(range(10)))
b[3:0] = [42, 42, 42]
- self.assertEqual(b, buffer([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9]))
+ self.assertEqual(b, bytearray([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9]))
def test_extended_set_del_slice(self):
indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
@@ -335,50 +335,50 @@ class BytesTest(unittest.TestCase):
# Skip invalid step 0
for step in indices[1:]:
L = list(range(255))
- b = buffer(L)
+ b = bytearray(L)
# Make sure we have a slice of exactly the right length,
# but with different data.
data = L[start:stop:step]
data.reverse()
L[start:stop:step] = data
b[start:stop:step] = data
- self.assertEquals(b, buffer(L))
+ self.assertEquals(b, bytearray(L))
del L[start:stop:step]
del b[start:stop:step]
- self.assertEquals(b, buffer(L))
+ self.assertEquals(b, bytearray(L))
def test_setslice_trap(self):
# This test verifies that we correctly handle assigning self
# to a slice of self (the old Lambert Meertens trap).
- b = buffer(range(256))
+ b = bytearray(range(256))
b[8:] = b
- self.assertEqual(b, buffer(list(range(8)) + list(range(256))))
+ self.assertEqual(b, bytearray(list(range(8)) + list(range(256))))
def test_encoding(self):
sample = "Hello world\n\u1234\u5678\u9abc\udef0"
for enc in ("utf8", "utf16"):
- b = buffer(sample, enc)
- self.assertEqual(b, buffer(sample.encode(enc)))
- self.assertRaises(UnicodeEncodeError, buffer, sample, "latin1")
- b = buffer(sample, "latin1", "ignore")
- self.assertEqual(b, buffer(sample[:-4], "utf-8"))
+ b = bytearray(sample, enc)
+ self.assertEqual(b, bytearray(sample.encode(enc)))
+ self.assertRaises(UnicodeEncodeError, bytearray, sample, "latin1")
+ b = bytearray(sample, "latin1", "ignore")
+ self.assertEqual(b, bytearray(sample[:-4], "utf-8"))
def test_decode(self):
sample = "Hello world\n\u1234\u5678\u9abc\def0\def0"
for enc in ("utf8", "utf16"):
- b = buffer(sample, enc)
+ b = bytearray(sample, enc)
self.assertEqual(b.decode(enc), sample)
sample = "Hello world\n\x80\x81\xfe\xff"
- b = buffer(sample, "latin1")
+ b = bytearray(sample, "latin1")
self.assertRaises(UnicodeDecodeError, b.decode, "utf8")
self.assertEqual(b.decode("utf8", "ignore"), "Hello world\n")
- def test_from_buffer(self):
+ def test_from_bytearray(self):
sample = bytes(b"Hello world\n\x80\x81\xfe\xff")
buf = memoryview(sample)
- b = buffer(buf)
- self.assertEqual(b, buffer(sample))
+ b = bytearray(buf)
+ self.assertEqual(b, bytearray(sample))
def test_to_str(self):
warnings.simplefilter('ignore', BytesWarning)
@@ -387,12 +387,12 @@ class BytesTest(unittest.TestCase):
self.assertEqual(str(b'\x80'), "b'\\x80'")
def test_from_int(self):
- b = buffer(0)
- self.assertEqual(b, buffer())
- b = buffer(10)
- self.assertEqual(b, buffer([0]*10))
- b = buffer(10000)
- self.assertEqual(b, buffer([0]*10000))
+ b = bytearray(0)
+ self.assertEqual(b, bytearray())
+ b = bytearray(10)
+ self.assertEqual(b, bytearray([0]*10))
+ b = bytearray(10000)
+ self.assertEqual(b, bytearray([0]*10000))
def test_concat(self):
b1 = b"abc"
@@ -404,21 +404,21 @@ class BytesTest(unittest.TestCase):
self.assertRaises(TypeError, lambda: "abc" + b2)
def test_repeat(self):
- for b in b"abc", buffer(b"abc"):
+ for b in b"abc", bytearray(b"abc"):
self.assertEqual(b * 3, b"abcabcabc")
self.assertEqual(b * 0, b"")
self.assertEqual(b * -1, b"")
self.assertRaises(TypeError, lambda: b * 3.14)
self.assertRaises(TypeError, lambda: 3.14 * b)
- # XXX Shouldn't bytes and buffer agree on what to raise?
+ # XXX Shouldn't bytes and bytearray agree on what to raise?
self.assertRaises((OverflowError, MemoryError),
lambda: b * sys.maxint)
def test_repeat_1char(self):
- self.assertEqual(b'x'*100, buffer([ord('x')]*100))
+ self.assertEqual(b'x'*100, bytearray([ord('x')]*100))
def test_iconcat(self):
- b = buffer(b"abc")
+ b = bytearray(b"abc")
b1 = b
b += b"def"
self.assertEqual(b, b"abcdef")
@@ -434,7 +434,7 @@ class BytesTest(unittest.TestCase):
self.fail("bytes += unicode didn't raise TypeError")
def test_irepeat(self):
- b = buffer(b"abc")
+ b = bytearray(b"abc")
b1 = b
b *= 3
self.assertEqual(b, b"abcabcabc")
@@ -442,7 +442,7 @@ class BytesTest(unittest.TestCase):
self.failUnless(b is b1)
def test_irepeat_1char(self):
- b = buffer(b"x")
+ b = bytearray(b"x")
b1 = b
b *= 100
self.assertEqual(b, b"x"*100)
@@ -450,7 +450,7 @@ class BytesTest(unittest.TestCase):
self.failUnless(b is b1)
def test_contains(self):
- for b in b"abc", buffer(b"abc"):
+ for b in b"abc", bytearray(b"abc"):
self.failUnless(ord('a') in b)
self.failUnless(int(ord('a')) in b)
self.failIf(200 in b)
@@ -460,7 +460,7 @@ class BytesTest(unittest.TestCase):
self.assertRaises(TypeError, lambda: None in b)
self.assertRaises(TypeError, lambda: float(ord('a')) in b)
self.assertRaises(TypeError, lambda: "a" in b)
- for f in bytes, buffer:
+ for f in bytes, bytearray:
self.failUnless(f(b"") in b)
self.failUnless(f(b"a") in b)
self.failUnless(f(b"b") in b)
@@ -474,7 +474,7 @@ class BytesTest(unittest.TestCase):
self.failIf(f(b"abd") in b)
def test_alloc(self):
- b = buffer()
+ b = bytearray()
alloc = b.__alloc__()
self.assert_(alloc >= 0)
seq = [alloc]
@@ -486,19 +486,19 @@ class BytesTest(unittest.TestCase):
seq.append(alloc)
def test_fromhex(self):
- self.assertRaises(TypeError, buffer.fromhex)
- self.assertRaises(TypeError, buffer.fromhex, 1)
- self.assertEquals(buffer.fromhex(''), buffer())
- b = buffer([0x1a, 0x2b, 0x30])
- self.assertEquals(buffer.fromhex('1a2B30'), b)
- self.assertEquals(buffer.fromhex(' 1A 2B 30 '), b)
- self.assertEquals(buffer.fromhex('0000'), b'\0\0')
- self.assertRaises(TypeError, buffer.fromhex, b'1B')
- self.assertRaises(ValueError, buffer.fromhex, 'a')
- self.assertRaises(ValueError, buffer.fromhex, 'rt')
- self.assertRaises(ValueError, buffer.fromhex, '1a b cd')
- self.assertRaises(ValueError, buffer.fromhex, '\x00')
- self.assertRaises(ValueError, buffer.fromhex, '12 \x00 34')
+ self.assertRaises(TypeError, bytearray.fromhex)
+ self.assertRaises(TypeError, bytearray.fromhex, 1)
+ self.assertEquals(bytearray.fromhex(''), bytearray())
+ b = bytearray([0x1a, 0x2b, 0x30])
+ self.assertEquals(bytearray.fromhex('1a2B30'), b)
+ self.assertEquals(bytearray.fromhex(' 1A 2B 30 '), b)
+ self.assertEquals(bytearray.fromhex('0000'), b'\0\0')
+ self.assertRaises(TypeError, bytearray.fromhex, b'1B')
+ self.assertRaises(ValueError, bytearray.fromhex, 'a')
+ self.assertRaises(ValueError, bytearray.fromhex, 'rt')
+ self.assertRaises(ValueError, bytearray.fromhex, '1a b cd')
+ self.assertRaises(ValueError, bytearray.fromhex, '\x00')
+ self.assertRaises(ValueError, bytearray.fromhex, '12 \x00 34')
def test_join(self):
self.assertEqual(b"".join([]), b"")
@@ -518,20 +518,20 @@ class BytesTest(unittest.TestCase):
(br"\xaa\x00\000\200", r"\xaa\x00\000\200"),
]
for b, s in tests:
- self.assertEqual(b, buffer(s, 'latin-1'))
+ self.assertEqual(b, bytearray(s, 'latin-1'))
for c in range(128, 256):
self.assertRaises(SyntaxError, eval,
'b"%s"' % chr(c))
def test_extend(self):
orig = b'hello'
- a = buffer(orig)
+ a = bytearray(orig)
a.extend(a)
self.assertEqual(a, orig + orig)
self.assertEqual(a[5:], orig)
def test_remove(self):
- b = buffer(b'hello')
+ b = bytearray(b'hello')
b.remove(ord('l'))
self.assertEqual(b, b'helo')
b.remove(ord('l'))
@@ -546,15 +546,15 @@ class BytesTest(unittest.TestCase):
self.assertRaises(TypeError, lambda: b.remove(b'e'))
def test_pop(self):
- b = buffer(b'world')
+ b = bytearray(b'world')
self.assertEqual(b.pop(), ord('d'))
self.assertEqual(b.pop(0), ord('w'))
self.assertEqual(b.pop(-2), ord('r'))
self.assertRaises(IndexError, lambda: b.pop(10))
- self.assertRaises(OverflowError, lambda: buffer().pop())
+ self.assertRaises(OverflowError, lambda: bytearray().pop())
def test_nosort(self):
- self.assertRaises(AttributeError, lambda: buffer().sort())
+ self.assertRaises(AttributeError, lambda: bytearray().sort())
def test_index(self):
b = b'parrot'
@@ -570,17 +570,17 @@ class BytesTest(unittest.TestCase):
self.assertEqual(b.count(b'w'), 0)
def test_append(self):
- b = buffer(b'hell')
+ b = bytearray(b'hell')
b.append(ord('o'))
self.assertEqual(b, b'hello')
self.assertEqual(b.append(100), None)
- b = buffer()
+ b = bytearray()
b.append(ord('A'))
self.assertEqual(len(b), 1)
self.assertRaises(TypeError, lambda: b.append(b'o'))
def test_insert(self):
- b = buffer(b'msssspp')
+ b = bytearray(b'msssspp')
b.insert(1, ord('i'))
b.insert(4, ord('i'))
b.insert(-2, ord('i'))
@@ -590,7 +590,7 @@ class BytesTest(unittest.TestCase):
def test_startswith(self):
b = b'hello'
- self.assertFalse(buffer().startswith(b"anything"))
+ self.assertFalse(bytearray().startswith(b"anything"))
self.assertTrue(b.startswith(b"hello"))
self.assertTrue(b.startswith(b"hel"))
self.assertTrue(b.startswith(b"h"))
@@ -599,7 +599,7 @@ class BytesTest(unittest.TestCase):
def test_endswith(self):
b = b'hello'
- self.assertFalse(buffer().endswith(b"anything"))
+ self.assertFalse(bytearray().endswith(b"anything"))
self.assertTrue(b.endswith(b"hello"))
self.assertTrue(b.endswith(b"llo"))
self.assertTrue(b.endswith(b"o"))
@@ -645,7 +645,7 @@ class BytesTest(unittest.TestCase):
def test_translate(self):
b = b'hello'
- rosetta = buffer(range(0, 256))
+ rosetta = bytearray(range(0, 256))
rosetta[ord('o')] = ord('e')
c = b.translate(rosetta, b'l')
self.assertEqual(b, b'hello')
@@ -668,7 +668,7 @@ class BytesTest(unittest.TestCase):
self.assertEqual(b' a bb c '.split(None, 2), [b'a', b'bb', b'c '])
self.assertEqual(b' a bb c '.split(None, 3), [b'a', b'bb', b'c'])
- def test_split_buffer(self):
+ def test_split_bytearray(self):
self.assertEqual(b'a b'.split(memoryview(b' ')), [b'a', b'b'])
def test_split_string_error(self):
@@ -691,7 +691,7 @@ class BytesTest(unittest.TestCase):
self.assertEqual(b' a bb c '.rsplit(None,2), [b' a', b'bb', b'c'])
self.assertEqual(b' a bb c '.rsplit(None, 3), [b'a', b'bb', b'c'])
- def test_rsplit_buffer(self):
+ def test_rsplit_bytearray(self):
self.assertEqual(b'a b'.rsplit(memoryview(b' ')), [b'a', b'b'])
def test_rsplit_string_error(self):
@@ -745,7 +745,7 @@ class BytesTest(unittest.TestCase):
self.assertEqual(b.lstrip(), b'abc \t\n\r\f\v')
self.assertEqual(b.rstrip(), b' \t\n\r\f\vabc')
- def test_strip_buffer(self):
+ def test_strip_bytearray(self):
self.assertEqual(b'abc'.strip(memoryview(b'ac')), b'b')
self.assertEqual(b'abc'.lstrip(memoryview(b'ac')), b'bc')
self.assertEqual(b'abc'.rstrip(memoryview(b'ac')), b'ab')
@@ -760,24 +760,24 @@ class BytesTest(unittest.TestCase):
self.assertEqual([ord(b[i:i+1]) for i in range(len(b))],
[0, 65, 127, 128, 255])
- def test_partition_buffer_doesnt_share_nullstring(self):
- a, b, c = buffer(b"x").partition(b"y")
+ def test_partition_bytearray_doesnt_share_nullstring(self):
+ a, b, c = bytearray(b"x").partition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
self.assert_(b is not c)
b += b"!"
self.assertEqual(c, b"")
- a, b, c = buffer(b"x").partition(b"y")
+ a, b, c = bytearray(b"x").partition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
# Same for rpartition
- b, c, a = buffer(b"x").rpartition(b"y")
+ b, c, a = bytearray(b"x").rpartition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
self.assert_(b is not c)
b += b"!"
self.assertEqual(c, b"")
- c, b, a = buffer(b"x").rpartition(b"y")
+ c, b, a = bytearray(b"x").rpartition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
@@ -793,22 +793,22 @@ class BytesTest(unittest.TestCase):
# Unfortunately they are all bundled with tests that
# are not appropriate for bytes
- # I've started porting some of those into buffer_tests.py, we should port
+ # I've started porting some of those into bytearray_tests.py, we should port
# the rest that make sense (the code can be cleaned up to use modern
# unittest methods at the same time).
-class BufferPEP3137Test(unittest.TestCase,
+class BytearrayPEP3137Test(unittest.TestCase,
test.buffer_tests.MixinBytesBufferCommonTests):
def marshal(self, x):
- return buffer(x)
+ return bytearray(x)
# TODO this should become:
- #return buffer(x)
- # once the bytes -> buffer and str8 -> bytes rename happens
+ #return bytearray(x)
+ # once the bytes -> bytearray and str8 -> bytes rename happens
def test_returns_new_copy(self):
val = self.marshal(b'1234')
# On immutable types these MAY return a reference to themselves
- # but on mutable types like buffer they MUST return a new copy.
+ # but on mutable types like bytearray they MUST return a new copy.
for methname in ('zfill', 'rjust', 'ljust', 'center'):
method = getattr(val, methname)
newval = method(3)
@@ -818,7 +818,7 @@ class BufferPEP3137Test(unittest.TestCase,
class BytesAsStringTest(test.string_tests.BaseTest):
- type2test = buffer
+ type2test = bytearray
def fixtype(self, obj):
if isinstance(obj, str):
@@ -838,17 +838,17 @@ class BytesAsStringTest(test.string_tests.BaseTest):
pass
-class BufferSubclass(buffer):
+class ByteArraySubclass(bytearray):
pass
-class BufferSubclassTest(unittest.TestCase):
+class ByteArraySubclassTest(unittest.TestCase):
def test_basic(self):
- self.assert_(issubclass(BufferSubclass, buffer))
- self.assert_(isinstance(BufferSubclass(), buffer))
+ self.assert_(issubclass(ByteArraySubclass, bytearray))
+ self.assert_(isinstance(ByteArraySubclass(), bytearray))
a, b = b"abcd", b"efgh"
- _a, _b = BufferSubclass(a), BufferSubclass(b)
+ _a, _b = ByteArraySubclass(a), ByteArraySubclass(b)
# test comparison operators with subclass instances
self.assert_(_a == _a)
@@ -871,19 +871,19 @@ class BufferSubclassTest(unittest.TestCase):
# Make sure join returns a NEW object for single item sequences
# involving a subclass.
# Make sure that it is of the appropriate type.
- s1 = BufferSubclass(b"abcd")
- s2 = buffer().join([s1])
+ s1 = ByteArraySubclass(b"abcd")
+ s2 = bytearray().join([s1])
self.assert_(s1 is not s2)
- self.assert_(type(s2) is buffer, type(s2))
+ self.assert_(type(s2) is bytearray, type(s2))
# Test reverse, calling join on subclass
s3 = s1.join([b"abcd"])
- self.assert_(type(s3) is buffer)
+ self.assert_(type(s3) is bytearray)
def test_pickle(self):
- a = BufferSubclass(b"abcd")
+ a = ByteArraySubclass(b"abcd")
a.x = 10
- a.y = BufferSubclass(b"efgh")
+ a.y = ByteArraySubclass(b"efgh")
for proto in range(pickle.HIGHEST_PROTOCOL):
b = pickle.loads(pickle.dumps(a, proto))
self.assertNotEqual(id(a), id(b))
@@ -894,9 +894,9 @@ class BufferSubclassTest(unittest.TestCase):
self.assertEqual(type(a.y), type(b.y))
def test_copy(self):
- a = BufferSubclass(b"abcd")
+ a = ByteArraySubclass(b"abcd")
a.x = 10
- a.y = BufferSubclass(b"efgh")
+ a.y = ByteArraySubclass(b"efgh")
for copy_method in (copy.copy, copy.deepcopy):
b = copy_method(a)
self.assertNotEqual(id(a), id(b))
@@ -907,9 +907,9 @@ class BufferSubclassTest(unittest.TestCase):
self.assertEqual(type(a.y), type(b.y))
def test_init_override(self):
- class subclass(buffer):
+ class subclass(bytearray):
def __init__(self, newarg=1, *args, **kwargs):
- buffer.__init__(self, *args, **kwargs)
+ bytearray.__init__(self, *args, **kwargs)
x = subclass(4, source=b"abcd")
self.assertEqual(x, b"abcd")
x = subclass(newarg=4, source=b"abcd")
@@ -919,8 +919,8 @@ class BufferSubclassTest(unittest.TestCase):
def test_main():
test.test_support.run_unittest(BytesTest)
test.test_support.run_unittest(BytesAsStringTest)
- test.test_support.run_unittest(BufferSubclassTest)
- test.test_support.run_unittest(BufferPEP3137Test)
+ test.test_support.run_unittest(ByteArraySubclassTest)
+ test.test_support.run_unittest(BytearrayPEP3137Test)
if __name__ == "__main__":
test_main()
diff --git a/Lib/test/test_codeccallbacks.py b/Lib/test/test_codeccallbacks.py
index 218bfc5..12eb068 100644
--- a/Lib/test/test_codeccallbacks.py
+++ b/Lib/test/test_codeccallbacks.py
@@ -33,13 +33,13 @@ class BadObjectUnicodeEncodeError(UnicodeEncodeError):
# A UnicodeDecodeError object without an end attribute
class NoEndUnicodeDecodeError(UnicodeDecodeError):
def __init__(self):
- UnicodeDecodeError.__init__(self, "ascii", buffer(b""), 0, 1, "bad")
+ UnicodeDecodeError.__init__(self, "ascii", bytearray(b""), 0, 1, "bad")
del self.end
# A UnicodeDecodeError object with a bad object attribute
class BadObjectUnicodeDecodeError(UnicodeDecodeError):
def __init__(self):
- UnicodeDecodeError.__init__(self, "ascii", buffer(b""), 0, 1, "bad")
+ UnicodeDecodeError.__init__(self, "ascii", bytearray(b""), 0, 1, "bad")
self.object = []
# A UnicodeTranslateError object without a start attribute
@@ -363,12 +363,12 @@ class CodecCallbackTest(unittest.TestCase):
def test_unicodedecodeerror(self):
self.check_exceptionobjectargs(
UnicodeDecodeError,
- ["ascii", buffer(b"g\xfcrk"), 1, 2, "ouch"],
+ ["ascii", bytearray(b"g\xfcrk"), 1, 2, "ouch"],
"'ascii' codec can't decode byte 0xfc in position 1: ouch"
)
self.check_exceptionobjectargs(
UnicodeDecodeError,
- ["ascii", buffer(b"g\xfcrk"), 1, 3, "ouch"],
+ ["ascii", bytearray(b"g\xfcrk"), 1, 3, "ouch"],
"'ascii' codec can't decode bytes in position 1-2: ouch"
)
@@ -442,7 +442,7 @@ class CodecCallbackTest(unittest.TestCase):
)
self.assertEquals(
codecs.ignore_errors(
- UnicodeDecodeError("ascii", buffer(b"\xff"), 0, 1, "ouch")),
+ UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")),
("", 1)
)
self.assertEquals(
@@ -482,7 +482,7 @@ class CodecCallbackTest(unittest.TestCase):
)
self.assertEquals(
codecs.replace_errors(
- UnicodeDecodeError("ascii", buffer(b"\xff"), 0, 1, "ouch")),
+ UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")),
("\ufffd", 1)
)
self.assertEquals(
@@ -508,7 +508,7 @@ class CodecCallbackTest(unittest.TestCase):
self.assertRaises(
TypeError,
codecs.xmlcharrefreplace_errors,
- UnicodeDecodeError("ascii", buffer(b"\xff"), 0, 1, "ouch")
+ UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")
)
self.assertRaises(
TypeError,
@@ -542,7 +542,7 @@ class CodecCallbackTest(unittest.TestCase):
self.assertRaises(
TypeError,
codecs.backslashreplace_errors,
- UnicodeDecodeError("ascii", buffer(b"\xff"), 0, 1, "ouch")
+ UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")
)
self.assertRaises(
TypeError,
diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py
index 0243134..3ccc06c 100644
--- a/Lib/test/test_collections.py
+++ b/Lib/test/test_collections.py
@@ -99,7 +99,7 @@ class TestOneTrickPonyABCs(unittest.TestCase):
def test_Hashable(self):
# Check some non-hashables
- non_samples = [buffer(), list(), set(), dict()]
+ non_samples = [bytearray(), list(), set(), dict()]
for x in non_samples:
self.failIf(isinstance(x, Hashable), repr(x))
self.failIf(issubclass(type(x), Hashable), repr(type(x)))
diff --git a/Lib/test/test_datetime.py b/Lib/test/test_datetime.py
index 6e5b990..7c08f9e 100644
--- a/Lib/test/test_datetime.py
+++ b/Lib/test/test_datetime.py
@@ -1093,7 +1093,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
self.assertEqual(orig, derived)
def test_backdoor_resistance(self):
- # For fast unpickling, the constructor accepts a pickle string.
+ # For fast unpickling, the constructor accepts a pickle byte string.
# This is a low-overhead backdoor. A user can (by intent or
# mistake) pass a string directly, which (if it's the right length)
# will get treated like a pickle, and bypass the normal sanity
@@ -1101,17 +1101,17 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
# The constructor doesn't want to burn the time to validate all
# fields, but does check the month field. This stops, e.g.,
# datetime.datetime('1995-03-25') from yielding an insane object.
- base = '1995-03-25'
+ base = b'1995-03-25'
if not issubclass(self.theclass, datetime):
base = base[:4]
- for month_byte in '9', chr(0), chr(13), '\xff':
+ for month_byte in b'9', b'\0', b'\r', b'\xff':
self.assertRaises(TypeError, self.theclass,
base[:2] + month_byte + base[3:])
for ord_byte in range(1, 13):
# This shouldn't blow up because of the month byte alone. If
# the implementation changes to do more-careful checking, it may
# blow up because other fields are insane.
- self.theclass(buffer(base[:2] + chr(ord_byte) + base[3:], "ascii"))
+ self.theclass(base[:2] + bytes([ord_byte]) + base[3:])
#############################################################################
# datetime tests
diff --git a/Lib/test/test_exceptions.py b/Lib/test/test_exceptions.py
index c405ac9..d1f9b1a 100644
--- a/Lib/test/test_exceptions.py
+++ b/Lib/test/test_exceptions.py
@@ -253,9 +253,9 @@ class ExceptionTests(unittest.TestCase):
'ordinal not in range'),
'encoding' : 'ascii', 'object' : 'a',
'start' : 0, 'reason' : 'ordinal not in range'}),
- (UnicodeDecodeError, ('ascii', buffer(b'\xff'), 0, 1,
+ (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
'ordinal not in range'),
- {'args' : ('ascii', buffer(b'\xff'), 0, 1,
+ {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
'ordinal not in range'),
'encoding' : 'ascii', 'object' : b'\xff',
'start' : 0, 'reason' : 'ordinal not in range'}),
diff --git a/Lib/test/test_float.py b/Lib/test/test_float.py
index ca5e537..4360c54 100644
--- a/Lib/test/test_float.py
+++ b/Lib/test/test_float.py
@@ -40,14 +40,14 @@ class FormatFunctionsTestCase(unittest.TestCase):
'chicken', 'unknown')
BE_DOUBLE_INF = b'\x7f\xf0\x00\x00\x00\x00\x00\x00'
-LE_DOUBLE_INF = bytes(reversed(buffer(BE_DOUBLE_INF)))
+LE_DOUBLE_INF = bytes(reversed(BE_DOUBLE_INF))
BE_DOUBLE_NAN = b'\x7f\xf8\x00\x00\x00\x00\x00\x00'
-LE_DOUBLE_NAN = bytes(reversed(buffer(BE_DOUBLE_NAN)))
+LE_DOUBLE_NAN = bytes(reversed(BE_DOUBLE_NAN))
BE_FLOAT_INF = b'\x7f\x80\x00\x00'
-LE_FLOAT_INF = bytes(reversed(buffer(BE_FLOAT_INF)))
+LE_FLOAT_INF = bytes(reversed(BE_FLOAT_INF))
BE_FLOAT_NAN = b'\x7f\xc0\x00\x00'
-LE_FLOAT_NAN = bytes(reversed(buffer(BE_FLOAT_NAN)))
+LE_FLOAT_NAN = bytes(reversed(BE_FLOAT_NAN))
# on non-IEEE platforms, attempting to unpack a bit pattern
# representing an infinity or a NaN should raise an exception.
diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py
index 697f69e..7ca3fbb 100644
--- a/Lib/test/test_io.py
+++ b/Lib/test/test_io.py
@@ -88,7 +88,7 @@ class IOTest(unittest.TestCase):
self.assertEqual(f.tell(), 6)
self.assertEqual(f.seek(-1, 1), 5)
self.assertEqual(f.tell(), 5)
- self.assertEqual(f.write(buffer(b" world\n\n\n")), 9)
+ self.assertEqual(f.write(bytearray(b" world\n\n\n")), 9)
self.assertEqual(f.seek(0), 0)
self.assertEqual(f.write(b"h"), 1)
self.assertEqual(f.seek(-1, 2), 13)
@@ -100,7 +100,7 @@ class IOTest(unittest.TestCase):
def read_ops(self, f, buffered=False):
data = f.read(5)
self.assertEqual(data, b"hello")
- data = buffer(data)
+ data = bytearray(data)
self.assertEqual(f.readinto(data), 5)
self.assertEqual(data, b" worl")
self.assertEqual(f.readinto(data), 2)
@@ -109,11 +109,11 @@ class IOTest(unittest.TestCase):
self.assertEqual(f.seek(0), 0)
self.assertEqual(f.read(20), b"hello world\n")
self.assertEqual(f.read(1), b"")
- self.assertEqual(f.readinto(buffer(b"x")), 0)
+ self.assertEqual(f.readinto(bytearray(b"x")), 0)
self.assertEqual(f.seek(-6, 2), 6)
self.assertEqual(f.read(5), b"world")
self.assertEqual(f.read(0), b"")
- self.assertEqual(f.readinto(buffer()), 0)
+ self.assertEqual(f.readinto(bytearray()), 0)
self.assertEqual(f.seek(-6, 1), 5)
self.assertEqual(f.read(5), b" worl")
self.assertEqual(f.tell(), 10)
diff --git a/Lib/test/test_marshal.py b/Lib/test/test_marshal.py
index fb70ced..d14d50d 100644
--- a/Lib/test/test_marshal.py
+++ b/Lib/test/test_marshal.py
@@ -39,7 +39,7 @@ class IntTestCase(unittest.TestCase, HelperMixin):
# we're running the test on a 32-bit box, of course.
def to_little_endian_string(value, nbytes):
- b = buffer()
+ b = bytearray()
for i in range(nbytes):
b.append(value & 0xff)
value >>= 8
diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py
index db6a97d..34596e0 100644
--- a/Lib/test/test_struct.py
+++ b/Lib/test/test_struct.py
@@ -560,11 +560,11 @@ def test_unpack_from():
test_string = b'abcd01234'
fmt = '4s'
s = struct.Struct(fmt)
- for cls in (buffer, bytes):
+ for cls in (bytes, bytearray):
if verbose:
print("test_unpack_from using", cls.__name__)
data = cls(test_string)
- if not isinstance(data, (buffer, bytes)):
+ if not isinstance(data, (bytes, bytearray)):
bytes_data = bytes(data, 'latin1')
else:
bytes_data = data
@@ -575,7 +575,7 @@ def test_unpack_from():
vereq(s.unpack_from(data, i), (bytes_data[i:i+4],))
for i in range(6, len(test_string) + 1):
simple_err(s.unpack_from, data, i)
- for cls in (buffer, bytes):
+ for cls in (bytes, bytearray):
data = cls(test_string)
vereq(struct.unpack_from(fmt, data), (b'abcd',))
vereq(struct.unpack_from(fmt, data, 2), (b'cd01',))
diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py
index d53317f..7475535 100644
--- a/Lib/test/test_unicode.py
+++ b/Lib/test/test_unicode.py
@@ -218,8 +218,8 @@ class UnicodeTest(
warnings.simplefilter('ignore', BytesWarning)
self.assertEqual('abc' == b'abc', False)
self.assertEqual('abc' != b'abc', True)
- self.assertEqual('abc' == buffer(b'abc'), False)
- self.assertEqual('abc' != buffer(b'abc'), True)
+ self.assertEqual('abc' == bytearray(b'abc'), False)
+ self.assertEqual('abc' != bytearray(b'abc'), True)
def test_comparison(self):
# Comparisons:
diff --git a/Lib/test/test_unicodedata.py b/Lib/test/test_unicodedata.py
index ba97e5d..c4ea816 100644
--- a/Lib/test/test_unicodedata.py
+++ b/Lib/test/test_unicodedata.py
@@ -177,7 +177,7 @@ class UnicodeFunctionsTest(UnicodeDatabaseTest):
def test_east_asian_width(self):
eaw = self.db.east_asian_width
self.assertRaises(TypeError, eaw, b'a')
- self.assertRaises(TypeError, eaw, buffer())
+ self.assertRaises(TypeError, eaw, bytearray())
self.assertRaises(TypeError, eaw, '')
self.assertRaises(TypeError, eaw, 'ra')
self.assertEqual(eaw('\x1e'), 'N')
diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py
index cb20222..4019440 100644
--- a/Lib/test/test_zipimport.py
+++ b/Lib/test/test_zipimport.py
@@ -153,7 +153,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
def testBadMagic(self):
# make pyc magic word invalid, forcing loading from .py
- badmagic_pyc = buffer(test_pyc)
+ badmagic_pyc = bytearray(test_pyc)
badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
files = {TESTMOD + ".py": (NOW, test_src),
TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
@@ -161,7 +161,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
def testBadMagic2(self):
# make pyc magic word invalid, causing an ImportError
- badmagic_pyc = buffer(test_pyc)
+ badmagic_pyc = bytearray(test_pyc)
badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
files = {TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
try:
@@ -172,7 +172,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
self.fail("expected ImportError; import from bad pyc")
def testBadMTime(self):
- badtime_pyc = buffer(test_pyc)
+ badtime_pyc = bytearray(test_pyc)
badtime_pyc[7] ^= 0x02 # flip the second bit -- not the first as that one
# isn't stored in the .py's mtime in the zip archive.
files = {TESTMOD + ".py": (NOW, test_src),
diff --git a/Lib/uuid.py b/Lib/uuid.py
index 06115c7..eaf7c88 100644
--- a/Lib/uuid.py
+++ b/Lib/uuid.py
@@ -234,7 +234,7 @@ class UUID(object):
@property
def bytes(self):
- bytes = buffer()
+ bytes = bytearray()
for shift in range(0, 128, 8):
bytes.insert(0, (self.int >> shift) & 0xff)
return bytes