ยปCore Development>Code coverage>Lib/test/test_bytes.py

Python code coverage for Lib/test/test_bytes.py

#countcontent
1n/a"""Unit tests for the bytes and bytearray types.
2n/a
3n/aXXX This is a mess. Common tests should be unified with string_tests.py (and
4n/athe latter should be modernized).
5n/a"""
6n/a
7n/aimport array
8n/aimport os
9n/aimport re
10n/aimport sys
11n/aimport copy
12n/aimport functools
13n/aimport pickle
14n/aimport tempfile
15n/aimport unittest
16n/a
17n/aimport test.support
18n/aimport test.string_tests
19n/aimport test.list_tests
20n/afrom test.support import bigaddrspacetest, MAX_Py_ssize_t
21n/a
22n/a
23n/aif sys.flags.bytes_warning:
24n/a def check_bytes_warnings(func):
25n/a @functools.wraps(func)
26n/a def wrapper(*args, **kw):
27n/a with test.support.check_warnings(('', BytesWarning)):
28n/a return func(*args, **kw)
29n/a return wrapper
30n/aelse:
31n/a # no-op
32n/a def check_bytes_warnings(func):
33n/a return func
34n/a
35n/a
36n/aclass Indexable:
37n/a def __init__(self, value=0):
38n/a self.value = value
39n/a def __index__(self):
40n/a return self.value
41n/a
42n/a
43n/aclass BaseBytesTest:
44n/a
45n/a def test_basics(self):
46n/a b = self.type2test()
47n/a self.assertEqual(type(b), self.type2test)
48n/a self.assertEqual(b.__class__, self.type2test)
49n/a
50n/a def test_copy(self):
51n/a a = self.type2test(b"abcd")
52n/a for copy_method in (copy.copy, copy.deepcopy):
53n/a b = copy_method(a)
54n/a self.assertEqual(a, b)
55n/a self.assertEqual(type(a), type(b))
56n/a
57n/a def test_empty_sequence(self):
58n/a b = self.type2test()
59n/a self.assertEqual(len(b), 0)
60n/a self.assertRaises(IndexError, lambda: b[0])
61n/a self.assertRaises(IndexError, lambda: b[1])
62n/a self.assertRaises(IndexError, lambda: b[sys.maxsize])
63n/a self.assertRaises(IndexError, lambda: b[sys.maxsize+1])
64n/a self.assertRaises(IndexError, lambda: b[10**100])
65n/a self.assertRaises(IndexError, lambda: b[-1])
66n/a self.assertRaises(IndexError, lambda: b[-2])
67n/a self.assertRaises(IndexError, lambda: b[-sys.maxsize])
68n/a self.assertRaises(IndexError, lambda: b[-sys.maxsize-1])
69n/a self.assertRaises(IndexError, lambda: b[-sys.maxsize-2])
70n/a self.assertRaises(IndexError, lambda: b[-10**100])
71n/a
72n/a def test_from_list(self):
73n/a ints = list(range(256))
74n/a b = self.type2test(i for i in ints)
75n/a self.assertEqual(len(b), 256)
76n/a self.assertEqual(list(b), ints)
77n/a
78n/a def test_from_index(self):
79n/a b = self.type2test([Indexable(), Indexable(1), Indexable(254),
80n/a Indexable(255)])
81n/a self.assertEqual(list(b), [0, 1, 254, 255])
82n/a self.assertRaises(ValueError, self.type2test, [Indexable(-1)])
83n/a self.assertRaises(ValueError, self.type2test, [Indexable(256)])
84n/a
85n/a def test_from_buffer(self):
86n/a a = self.type2test(array.array('B', [1, 2, 3]))
87n/a self.assertEqual(a, b"\x01\x02\x03")
88n/a
89n/a # http://bugs.python.org/issue29159
90n/a # Fallback when __index__ raises exception other than OverflowError
91n/a class B(bytes):
92n/a def __index__(self):
93n/a raise TypeError
94n/a
95n/a self.assertEqual(self.type2test(B(b"foobar")), b"foobar")
96n/a
97n/a def test_from_ssize(self):
98n/a self.assertEqual(self.type2test(0), b'')
99n/a self.assertEqual(self.type2test(1), b'\x00')
100n/a self.assertEqual(self.type2test(5), b'\x00\x00\x00\x00\x00')
101n/a self.assertRaises(ValueError, self.type2test, -1)
102n/a
103n/a self.assertEqual(self.type2test('0', 'ascii'), b'0')
104n/a self.assertEqual(self.type2test(b'0'), b'0')
105n/a self.assertRaises(OverflowError, self.type2test, sys.maxsize + 1)
106n/a
107n/a def test_constructor_type_errors(self):
108n/a self.assertRaises(TypeError, self.type2test, 0.0)
109n/a class C:
110n/a pass
111n/a self.assertRaises(TypeError, self.type2test, ["0"])
112n/a self.assertRaises(TypeError, self.type2test, [0.0])
113n/a self.assertRaises(TypeError, self.type2test, [None])
114n/a self.assertRaises(TypeError, self.type2test, [C()])
115n/a self.assertRaises(TypeError, self.type2test, 0, 'ascii')
116n/a self.assertRaises(TypeError, self.type2test, b'', 'ascii')
117n/a self.assertRaises(TypeError, self.type2test, 0, errors='ignore')
118n/a self.assertRaises(TypeError, self.type2test, b'', errors='ignore')
119n/a self.assertRaises(TypeError, self.type2test, '')
120n/a self.assertRaises(TypeError, self.type2test, '', errors='ignore')
121n/a self.assertRaises(TypeError, self.type2test, '', b'ascii')
122n/a self.assertRaises(TypeError, self.type2test, '', 'ascii', b'ignore')
123n/a
124n/a def test_constructor_value_errors(self):
125n/a self.assertRaises(ValueError, self.type2test, [-1])
126n/a self.assertRaises(ValueError, self.type2test, [-sys.maxsize])
127n/a self.assertRaises(ValueError, self.type2test, [-sys.maxsize-1])
128n/a self.assertRaises(ValueError, self.type2test, [-sys.maxsize-2])
129n/a self.assertRaises(ValueError, self.type2test, [-10**100])
130n/a self.assertRaises(ValueError, self.type2test, [256])
131n/a self.assertRaises(ValueError, self.type2test, [257])
132n/a self.assertRaises(ValueError, self.type2test, [sys.maxsize])
133n/a self.assertRaises(ValueError, self.type2test, [sys.maxsize+1])
134n/a self.assertRaises(ValueError, self.type2test, [10**100])
135n/a
136n/a @bigaddrspacetest
137n/a def test_constructor_overflow(self):
138n/a size = MAX_Py_ssize_t
139n/a self.assertRaises((OverflowError, MemoryError), self.type2test, size)
140n/a try:
141n/a # Should either pass or raise an error (e.g. on debug builds with
142n/a # additional malloc() overhead), but shouldn't crash.
143n/a bytearray(size - 4)
144n/a except (OverflowError, MemoryError):
145n/a pass
146n/a
147n/a def test_compare(self):
148n/a b1 = self.type2test([1, 2, 3])
149n/a b2 = self.type2test([1, 2, 3])
150n/a b3 = self.type2test([1, 3])
151n/a
152n/a self.assertEqual(b1, b2)
153n/a self.assertTrue(b2 != b3)
154n/a self.assertTrue(b1 <= b2)
155n/a self.assertTrue(b1 <= b3)
156n/a self.assertTrue(b1 < b3)
157n/a self.assertTrue(b1 >= b2)
158n/a self.assertTrue(b3 >= b2)
159n/a self.assertTrue(b3 > b2)
160n/a
161n/a self.assertFalse(b1 != b2)
162n/a self.assertFalse(b2 == b3)
163n/a self.assertFalse(b1 > b2)
164n/a self.assertFalse(b1 > b3)
165n/a self.assertFalse(b1 >= b3)
166n/a self.assertFalse(b1 < b2)
167n/a self.assertFalse(b3 < b2)
168n/a self.assertFalse(b3 <= b2)
169n/a
170n/a @check_bytes_warnings
171n/a def test_compare_to_str(self):
172n/a # Byte comparisons with unicode should always fail!
173n/a # Test this for all expected byte orders and Unicode character
174n/a # sizes.
175n/a self.assertEqual(self.type2test(b"\0a\0b\0c") == "abc", False)
176n/a self.assertEqual(self.type2test(b"\0\0\0a\0\0\0b\0\0\0c") == "abc",
177n/a False)
178n/a self.assertEqual(self.type2test(b"a\0b\0c\0") == "abc", False)
179n/a self.assertEqual(self.type2test(b"a\0\0\0b\0\0\0c\0\0\0") == "abc",
180n/a False)
181n/a self.assertEqual(self.type2test() == str(), False)
182n/a self.assertEqual(self.type2test() != str(), True)
183n/a
184n/a def test_reversed(self):
185n/a input = list(map(ord, "Hello"))
186n/a b = self.type2test(input)
187n/a output = list(reversed(b))
188n/a input.reverse()
189n/a self.assertEqual(output, input)
190n/a
191n/a def test_getslice(self):
192n/a def by(s):
193n/a return self.type2test(map(ord, s))
194n/a b = by("Hello, world")
195n/a
196n/a self.assertEqual(b[:5], by("Hello"))
197n/a self.assertEqual(b[1:5], by("ello"))
198n/a self.assertEqual(b[5:7], by(", "))
199n/a self.assertEqual(b[7:], by("world"))
200n/a self.assertEqual(b[7:12], by("world"))
201n/a self.assertEqual(b[7:100], by("world"))
202n/a
203n/a self.assertEqual(b[:-7], by("Hello"))
204n/a self.assertEqual(b[-11:-7], by("ello"))
205n/a self.assertEqual(b[-7:-5], by(", "))
206n/a self.assertEqual(b[-5:], by("world"))
207n/a self.assertEqual(b[-5:12], by("world"))
208n/a self.assertEqual(b[-5:100], by("world"))
209n/a self.assertEqual(b[-100:5], by("Hello"))
210n/a
211n/a def test_extended_getslice(self):
212n/a # Test extended slicing by comparing with list slicing.
213n/a L = list(range(255))
214n/a b = self.type2test(L)
215n/a indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
216n/a for start in indices:
217n/a for stop in indices:
218n/a # Skip step 0 (invalid)
219n/a for step in indices[1:]:
220n/a self.assertEqual(b[start:stop:step], self.type2test(L[start:stop:step]))
221n/a
222n/a def test_encoding(self):
223n/a sample = "Hello world\n\u1234\u5678\u9abc"
224n/a for enc in ("utf-8", "utf-16"):
225n/a b = self.type2test(sample, enc)
226n/a self.assertEqual(b, self.type2test(sample.encode(enc)))
227n/a self.assertRaises(UnicodeEncodeError, self.type2test, sample, "latin-1")
228n/a b = self.type2test(sample, "latin-1", "ignore")
229n/a self.assertEqual(b, self.type2test(sample[:-3], "utf-8"))
230n/a
231n/a def test_decode(self):
232n/a sample = "Hello world\n\u1234\u5678\u9abc"
233n/a for enc in ("utf-8", "utf-16"):
234n/a b = self.type2test(sample, enc)
235n/a self.assertEqual(b.decode(enc), sample)
236n/a sample = "Hello world\n\x80\x81\xfe\xff"
237n/a b = self.type2test(sample, "latin-1")
238n/a self.assertRaises(UnicodeDecodeError, b.decode, "utf-8")
239n/a self.assertEqual(b.decode("utf-8", "ignore"), "Hello world\n")
240n/a self.assertEqual(b.decode(errors="ignore", encoding="utf-8"),
241n/a "Hello world\n")
242n/a # Default encoding is utf-8
243n/a self.assertEqual(self.type2test(b'\xe2\x98\x83').decode(), '\u2603')
244n/a
245n/a def test_from_int(self):
246n/a b = self.type2test(0)
247n/a self.assertEqual(b, self.type2test())
248n/a b = self.type2test(10)
249n/a self.assertEqual(b, self.type2test([0]*10))
250n/a b = self.type2test(10000)
251n/a self.assertEqual(b, self.type2test([0]*10000))
252n/a
253n/a def test_concat(self):
254n/a b1 = self.type2test(b"abc")
255n/a b2 = self.type2test(b"def")
256n/a self.assertEqual(b1 + b2, b"abcdef")
257n/a self.assertEqual(b1 + bytes(b"def"), b"abcdef")
258n/a self.assertEqual(bytes(b"def") + b1, b"defabc")
259n/a self.assertRaises(TypeError, lambda: b1 + "def")
260n/a self.assertRaises(TypeError, lambda: "abc" + b2)
261n/a
262n/a def test_repeat(self):
263n/a for b in b"abc", self.type2test(b"abc"):
264n/a self.assertEqual(b * 3, b"abcabcabc")
265n/a self.assertEqual(b * 0, b"")
266n/a self.assertEqual(b * -1, b"")
267n/a self.assertRaises(TypeError, lambda: b * 3.14)
268n/a self.assertRaises(TypeError, lambda: 3.14 * b)
269n/a # XXX Shouldn't bytes and bytearray agree on what to raise?
270n/a with self.assertRaises((OverflowError, MemoryError)):
271n/a c = b * sys.maxsize
272n/a with self.assertRaises((OverflowError, MemoryError)):
273n/a b *= sys.maxsize
274n/a
275n/a def test_repeat_1char(self):
276n/a self.assertEqual(self.type2test(b'x')*100, self.type2test([ord('x')]*100))
277n/a
278n/a def test_contains(self):
279n/a b = self.type2test(b"abc")
280n/a self.assertIn(ord('a'), b)
281n/a self.assertIn(int(ord('a')), b)
282n/a self.assertNotIn(200, b)
283n/a self.assertRaises(ValueError, lambda: 300 in b)
284n/a self.assertRaises(ValueError, lambda: -1 in b)
285n/a self.assertRaises(ValueError, lambda: sys.maxsize+1 in b)
286n/a self.assertRaises(TypeError, lambda: None in b)
287n/a self.assertRaises(TypeError, lambda: float(ord('a')) in b)
288n/a self.assertRaises(TypeError, lambda: "a" in b)
289n/a for f in bytes, bytearray:
290n/a self.assertIn(f(b""), b)
291n/a self.assertIn(f(b"a"), b)
292n/a self.assertIn(f(b"b"), b)
293n/a self.assertIn(f(b"c"), b)
294n/a self.assertIn(f(b"ab"), b)
295n/a self.assertIn(f(b"bc"), b)
296n/a self.assertIn(f(b"abc"), b)
297n/a self.assertNotIn(f(b"ac"), b)
298n/a self.assertNotIn(f(b"d"), b)
299n/a self.assertNotIn(f(b"dab"), b)
300n/a self.assertNotIn(f(b"abd"), b)
301n/a
302n/a def test_fromhex(self):
303n/a self.assertRaises(TypeError, self.type2test.fromhex)
304n/a self.assertRaises(TypeError, self.type2test.fromhex, 1)
305n/a self.assertEqual(self.type2test.fromhex(''), self.type2test())
306n/a b = bytearray([0x1a, 0x2b, 0x30])
307n/a self.assertEqual(self.type2test.fromhex('1a2B30'), b)
308n/a self.assertEqual(self.type2test.fromhex(' 1A 2B 30 '), b)
309n/a
310n/a # check that ASCII whitespace is ignored
311n/a self.assertEqual(self.type2test.fromhex(' 1A\n2B\t30\v'), b)
312n/a for c in "\x09\x0A\x0B\x0C\x0D\x20":
313n/a self.assertEqual(self.type2test.fromhex(c), self.type2test())
314n/a for c in "\x1C\x1D\x1E\x1F\x85\xa0\u2000\u2002\u2028":
315n/a self.assertRaises(ValueError, self.type2test.fromhex, c)
316n/a
317n/a self.assertEqual(self.type2test.fromhex('0000'), b'\0\0')
318n/a self.assertRaises(TypeError, self.type2test.fromhex, b'1B')
319n/a self.assertRaises(ValueError, self.type2test.fromhex, 'a')
320n/a self.assertRaises(ValueError, self.type2test.fromhex, 'rt')
321n/a self.assertRaises(ValueError, self.type2test.fromhex, '1a b cd')
322n/a self.assertRaises(ValueError, self.type2test.fromhex, '\x00')
323n/a self.assertRaises(ValueError, self.type2test.fromhex, '12 \x00 34')
324n/a
325n/a for data, pos in (
326n/a # invalid first hexadecimal character
327n/a ('12 x4 56', 3),
328n/a # invalid second hexadecimal character
329n/a ('12 3x 56', 4),
330n/a # two invalid hexadecimal characters
331n/a ('12 xy 56', 3),
332n/a # test non-ASCII string
333n/a ('12 3\xff 56', 4),
334n/a ):
335n/a with self.assertRaises(ValueError) as cm:
336n/a self.type2test.fromhex(data)
337n/a self.assertIn('at position %s' % pos, str(cm.exception))
338n/a
339n/a def test_hex(self):
340n/a self.assertRaises(TypeError, self.type2test.hex)
341n/a self.assertRaises(TypeError, self.type2test.hex, 1)
342n/a self.assertEqual(self.type2test(b"").hex(), "")
343n/a self.assertEqual(bytearray([0x1a, 0x2b, 0x30]).hex(), '1a2b30')
344n/a self.assertEqual(self.type2test(b"\x1a\x2b\x30").hex(), '1a2b30')
345n/a self.assertEqual(memoryview(b"\x1a\x2b\x30").hex(), '1a2b30')
346n/a
347n/a def test_join(self):
348n/a self.assertEqual(self.type2test(b"").join([]), b"")
349n/a self.assertEqual(self.type2test(b"").join([b""]), b"")
350n/a for lst in [[b"abc"], [b"a", b"bc"], [b"ab", b"c"], [b"a", b"b", b"c"]]:
351n/a lst = list(map(self.type2test, lst))
352n/a self.assertEqual(self.type2test(b"").join(lst), b"abc")
353n/a self.assertEqual(self.type2test(b"").join(tuple(lst)), b"abc")
354n/a self.assertEqual(self.type2test(b"").join(iter(lst)), b"abc")
355n/a dot_join = self.type2test(b".:").join
356n/a self.assertEqual(dot_join([b"ab", b"cd"]), b"ab.:cd")
357n/a self.assertEqual(dot_join([memoryview(b"ab"), b"cd"]), b"ab.:cd")
358n/a self.assertEqual(dot_join([b"ab", memoryview(b"cd")]), b"ab.:cd")
359n/a self.assertEqual(dot_join([bytearray(b"ab"), b"cd"]), b"ab.:cd")
360n/a self.assertEqual(dot_join([b"ab", bytearray(b"cd")]), b"ab.:cd")
361n/a # Stress it with many items
362n/a seq = [b"abc"] * 1000
363n/a expected = b"abc" + b".:abc" * 999
364n/a self.assertEqual(dot_join(seq), expected)
365n/a self.assertRaises(TypeError, self.type2test(b" ").join, None)
366n/a # Error handling and cleanup when some item in the middle of the
367n/a # sequence has the wrong type.
368n/a with self.assertRaises(TypeError):
369n/a dot_join([bytearray(b"ab"), "cd", b"ef"])
370n/a with self.assertRaises(TypeError):
371n/a dot_join([memoryview(b"ab"), "cd", b"ef"])
372n/a
373n/a def test_count(self):
374n/a b = self.type2test(b'mississippi')
375n/a i = 105
376n/a p = 112
377n/a w = 119
378n/a
379n/a self.assertEqual(b.count(b'i'), 4)
380n/a self.assertEqual(b.count(b'ss'), 2)
381n/a self.assertEqual(b.count(b'w'), 0)
382n/a
383n/a self.assertEqual(b.count(i), 4)
384n/a self.assertEqual(b.count(w), 0)
385n/a
386n/a self.assertEqual(b.count(b'i', 6), 2)
387n/a self.assertEqual(b.count(b'p', 6), 2)
388n/a self.assertEqual(b.count(b'i', 1, 3), 1)
389n/a self.assertEqual(b.count(b'p', 7, 9), 1)
390n/a
391n/a self.assertEqual(b.count(i, 6), 2)
392n/a self.assertEqual(b.count(p, 6), 2)
393n/a self.assertEqual(b.count(i, 1, 3), 1)
394n/a self.assertEqual(b.count(p, 7, 9), 1)
395n/a
396n/a def test_startswith(self):
397n/a b = self.type2test(b'hello')
398n/a self.assertFalse(self.type2test().startswith(b"anything"))
399n/a self.assertTrue(b.startswith(b"hello"))
400n/a self.assertTrue(b.startswith(b"hel"))
401n/a self.assertTrue(b.startswith(b"h"))
402n/a self.assertFalse(b.startswith(b"hellow"))
403n/a self.assertFalse(b.startswith(b"ha"))
404n/a with self.assertRaises(TypeError) as cm:
405n/a b.startswith([b'h'])
406n/a exc = str(cm.exception)
407n/a self.assertIn('bytes', exc)
408n/a self.assertIn('tuple', exc)
409n/a
410n/a def test_endswith(self):
411n/a b = self.type2test(b'hello')
412n/a self.assertFalse(bytearray().endswith(b"anything"))
413n/a self.assertTrue(b.endswith(b"hello"))
414n/a self.assertTrue(b.endswith(b"llo"))
415n/a self.assertTrue(b.endswith(b"o"))
416n/a self.assertFalse(b.endswith(b"whello"))
417n/a self.assertFalse(b.endswith(b"no"))
418n/a with self.assertRaises(TypeError) as cm:
419n/a b.endswith([b'o'])
420n/a exc = str(cm.exception)
421n/a self.assertIn('bytes', exc)
422n/a self.assertIn('tuple', exc)
423n/a
424n/a def test_find(self):
425n/a b = self.type2test(b'mississippi')
426n/a i = 105
427n/a w = 119
428n/a
429n/a self.assertEqual(b.find(b'ss'), 2)
430n/a self.assertEqual(b.find(b'w'), -1)
431n/a self.assertEqual(b.find(b'mississippian'), -1)
432n/a
433n/a self.assertEqual(b.find(i), 1)
434n/a self.assertEqual(b.find(w), -1)
435n/a
436n/a self.assertEqual(b.find(b'ss', 3), 5)
437n/a self.assertEqual(b.find(b'ss', 1, 7), 2)
438n/a self.assertEqual(b.find(b'ss', 1, 3), -1)
439n/a
440n/a self.assertEqual(b.find(i, 6), 7)
441n/a self.assertEqual(b.find(i, 1, 3), 1)
442n/a self.assertEqual(b.find(w, 1, 3), -1)
443n/a
444n/a for index in (-1, 256, sys.maxsize + 1):
445n/a self.assertRaisesRegex(
446n/a ValueError, r'byte must be in range\(0, 256\)',
447n/a b.find, index)
448n/a
449n/a def test_rfind(self):
450n/a b = self.type2test(b'mississippi')
451n/a i = 105
452n/a w = 119
453n/a
454n/a self.assertEqual(b.rfind(b'ss'), 5)
455n/a self.assertEqual(b.rfind(b'w'), -1)
456n/a self.assertEqual(b.rfind(b'mississippian'), -1)
457n/a
458n/a self.assertEqual(b.rfind(i), 10)
459n/a self.assertEqual(b.rfind(w), -1)
460n/a
461n/a self.assertEqual(b.rfind(b'ss', 3), 5)
462n/a self.assertEqual(b.rfind(b'ss', 0, 6), 2)
463n/a
464n/a self.assertEqual(b.rfind(i, 1, 3), 1)
465n/a self.assertEqual(b.rfind(i, 3, 9), 7)
466n/a self.assertEqual(b.rfind(w, 1, 3), -1)
467n/a
468n/a def test_index(self):
469n/a b = self.type2test(b'mississippi')
470n/a i = 105
471n/a w = 119
472n/a
473n/a self.assertEqual(b.index(b'ss'), 2)
474n/a self.assertRaises(ValueError, b.index, b'w')
475n/a self.assertRaises(ValueError, b.index, b'mississippian')
476n/a
477n/a self.assertEqual(b.index(i), 1)
478n/a self.assertRaises(ValueError, b.index, w)
479n/a
480n/a self.assertEqual(b.index(b'ss', 3), 5)
481n/a self.assertEqual(b.index(b'ss', 1, 7), 2)
482n/a self.assertRaises(ValueError, b.index, b'ss', 1, 3)
483n/a
484n/a self.assertEqual(b.index(i, 6), 7)
485n/a self.assertEqual(b.index(i, 1, 3), 1)
486n/a self.assertRaises(ValueError, b.index, w, 1, 3)
487n/a
488n/a def test_rindex(self):
489n/a b = self.type2test(b'mississippi')
490n/a i = 105
491n/a w = 119
492n/a
493n/a self.assertEqual(b.rindex(b'ss'), 5)
494n/a self.assertRaises(ValueError, b.rindex, b'w')
495n/a self.assertRaises(ValueError, b.rindex, b'mississippian')
496n/a
497n/a self.assertEqual(b.rindex(i), 10)
498n/a self.assertRaises(ValueError, b.rindex, w)
499n/a
500n/a self.assertEqual(b.rindex(b'ss', 3), 5)
501n/a self.assertEqual(b.rindex(b'ss', 0, 6), 2)
502n/a
503n/a self.assertEqual(b.rindex(i, 1, 3), 1)
504n/a self.assertEqual(b.rindex(i, 3, 9), 7)
505n/a self.assertRaises(ValueError, b.rindex, w, 1, 3)
506n/a
507n/a def test_mod(self):
508n/a b = self.type2test(b'hello, %b!')
509n/a orig = b
510n/a b = b % b'world'
511n/a self.assertEqual(b, b'hello, world!')
512n/a self.assertEqual(orig, b'hello, %b!')
513n/a self.assertFalse(b is orig)
514n/a b = self.type2test(b'%s / 100 = %d%%')
515n/a a = b % (b'seventy-nine', 79)
516n/a self.assertEqual(a, b'seventy-nine / 100 = 79%')
517n/a self.assertIs(type(a), self.type2test)
518n/a
519n/a def test_imod(self):
520n/a b = self.type2test(b'hello, %b!')
521n/a orig = b
522n/a b %= b'world'
523n/a self.assertEqual(b, b'hello, world!')
524n/a self.assertEqual(orig, b'hello, %b!')
525n/a self.assertFalse(b is orig)
526n/a b = self.type2test(b'%s / 100 = %d%%')
527n/a b %= (b'seventy-nine', 79)
528n/a self.assertEqual(b, b'seventy-nine / 100 = 79%')
529n/a self.assertIs(type(b), self.type2test)
530n/a
531n/a def test_rmod(self):
532n/a with self.assertRaises(TypeError):
533n/a object() % self.type2test(b'abc')
534n/a self.assertIs(self.type2test(b'abc').__rmod__('%r'), NotImplemented)
535n/a
536n/a def test_replace(self):
537n/a b = self.type2test(b'mississippi')
538n/a self.assertEqual(b.replace(b'i', b'a'), b'massassappa')
539n/a self.assertEqual(b.replace(b'ss', b'x'), b'mixixippi')
540n/a
541n/a def test_split_string_error(self):
542n/a self.assertRaises(TypeError, self.type2test(b'a b').split, ' ')
543n/a
544n/a def test_split_unicodewhitespace(self):
545n/a for b in (b'a\x1Cb', b'a\x1Db', b'a\x1Eb', b'a\x1Fb'):
546n/a b = self.type2test(b)
547n/a self.assertEqual(b.split(), [b])
548n/a b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F")
549n/a self.assertEqual(b.split(), [b'\x1c\x1d\x1e\x1f'])
550n/a
551n/a def test_rsplit_string_error(self):
552n/a self.assertRaises(TypeError, self.type2test(b'a b').rsplit, ' ')
553n/a
554n/a def test_rsplit_unicodewhitespace(self):
555n/a b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F")
556n/a self.assertEqual(b.rsplit(), [b'\x1c\x1d\x1e\x1f'])
557n/a
558n/a def test_partition(self):
559n/a b = self.type2test(b'mississippi')
560n/a self.assertEqual(b.partition(b'ss'), (b'mi', b'ss', b'issippi'))
561n/a self.assertEqual(b.partition(b'w'), (b'mississippi', b'', b''))
562n/a
563n/a def test_rpartition(self):
564n/a b = self.type2test(b'mississippi')
565n/a self.assertEqual(b.rpartition(b'ss'), (b'missi', b'ss', b'ippi'))
566n/a self.assertEqual(b.rpartition(b'i'), (b'mississipp', b'i', b''))
567n/a self.assertEqual(b.rpartition(b'w'), (b'', b'', b'mississippi'))
568n/a
569n/a def test_pickling(self):
570n/a for proto in range(pickle.HIGHEST_PROTOCOL + 1):
571n/a for b in b"", b"a", b"abc", b"\xffab\x80", b"\0\0\377\0\0":
572n/a b = self.type2test(b)
573n/a ps = pickle.dumps(b, proto)
574n/a q = pickle.loads(ps)
575n/a self.assertEqual(b, q)
576n/a
577n/a def test_iterator_pickling(self):
578n/a for proto in range(pickle.HIGHEST_PROTOCOL + 1):
579n/a for b in b"", b"a", b"abc", b"\xffab\x80", b"\0\0\377\0\0":
580n/a it = itorg = iter(self.type2test(b))
581n/a data = list(self.type2test(b))
582n/a d = pickle.dumps(it, proto)
583n/a it = pickle.loads(d)
584n/a self.assertEqual(type(itorg), type(it))
585n/a self.assertEqual(list(it), data)
586n/a
587n/a it = pickle.loads(d)
588n/a if not b:
589n/a continue
590n/a next(it)
591n/a d = pickle.dumps(it, proto)
592n/a it = pickle.loads(d)
593n/a self.assertEqual(list(it), data[1:])
594n/a
595n/a def test_strip_bytearray(self):
596n/a self.assertEqual(self.type2test(b'abc').strip(memoryview(b'ac')), b'b')
597n/a self.assertEqual(self.type2test(b'abc').lstrip(memoryview(b'ac')), b'bc')
598n/a self.assertEqual(self.type2test(b'abc').rstrip(memoryview(b'ac')), b'ab')
599n/a
600n/a def test_strip_string_error(self):
601n/a self.assertRaises(TypeError, self.type2test(b'abc').strip, 'b')
602n/a self.assertRaises(TypeError, self.type2test(b'abc').lstrip, 'b')
603n/a self.assertRaises(TypeError, self.type2test(b'abc').rstrip, 'b')
604n/a
605n/a def test_center(self):
606n/a # Fill character can be either bytes or bytearray (issue 12380)
607n/a b = self.type2test(b'abc')
608n/a for fill_type in (bytes, bytearray):
609n/a self.assertEqual(b.center(7, fill_type(b'-')),
610n/a self.type2test(b'--abc--'))
611n/a
612n/a def test_ljust(self):
613n/a # Fill character can be either bytes or bytearray (issue 12380)
614n/a b = self.type2test(b'abc')
615n/a for fill_type in (bytes, bytearray):
616n/a self.assertEqual(b.ljust(7, fill_type(b'-')),
617n/a self.type2test(b'abc----'))
618n/a
619n/a def test_rjust(self):
620n/a # Fill character can be either bytes or bytearray (issue 12380)
621n/a b = self.type2test(b'abc')
622n/a for fill_type in (bytes, bytearray):
623n/a self.assertEqual(b.rjust(7, fill_type(b'-')),
624n/a self.type2test(b'----abc'))
625n/a
626n/a def test_ord(self):
627n/a b = self.type2test(b'\0A\x7f\x80\xff')
628n/a self.assertEqual([ord(b[i:i+1]) for i in range(len(b))],
629n/a [0, 65, 127, 128, 255])
630n/a
631n/a def test_maketrans(self):
632n/a 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'
633n/a self.assertEqual(self.type2test.maketrans(b'abc', b'xyz'), transtable)
634n/a 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'
635n/a self.assertEqual(self.type2test.maketrans(b'\375\376\377', b'xyz'), transtable)
636n/a self.assertRaises(ValueError, self.type2test.maketrans, b'abc', b'xyzq')
637n/a self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def')
638n/a
639n/a def test_none_arguments(self):
640n/a # issue 11828
641n/a b = self.type2test(b'hello')
642n/a l = self.type2test(b'l')
643n/a h = self.type2test(b'h')
644n/a x = self.type2test(b'x')
645n/a o = self.type2test(b'o')
646n/a
647n/a self.assertEqual(2, b.find(l, None))
648n/a self.assertEqual(3, b.find(l, -2, None))
649n/a self.assertEqual(2, b.find(l, None, -2))
650n/a self.assertEqual(0, b.find(h, None, None))
651n/a
652n/a self.assertEqual(3, b.rfind(l, None))
653n/a self.assertEqual(3, b.rfind(l, -2, None))
654n/a self.assertEqual(2, b.rfind(l, None, -2))
655n/a self.assertEqual(0, b.rfind(h, None, None))
656n/a
657n/a self.assertEqual(2, b.index(l, None))
658n/a self.assertEqual(3, b.index(l, -2, None))
659n/a self.assertEqual(2, b.index(l, None, -2))
660n/a self.assertEqual(0, b.index(h, None, None))
661n/a
662n/a self.assertEqual(3, b.rindex(l, None))
663n/a self.assertEqual(3, b.rindex(l, -2, None))
664n/a self.assertEqual(2, b.rindex(l, None, -2))
665n/a self.assertEqual(0, b.rindex(h, None, None))
666n/a
667n/a self.assertEqual(2, b.count(l, None))
668n/a self.assertEqual(1, b.count(l, -2, None))
669n/a self.assertEqual(1, b.count(l, None, -2))
670n/a self.assertEqual(0, b.count(x, None, None))
671n/a
672n/a self.assertEqual(True, b.endswith(o, None))
673n/a self.assertEqual(True, b.endswith(o, -2, None))
674n/a self.assertEqual(True, b.endswith(l, None, -2))
675n/a self.assertEqual(False, b.endswith(x, None, None))
676n/a
677n/a self.assertEqual(True, b.startswith(h, None))
678n/a self.assertEqual(True, b.startswith(l, -2, None))
679n/a self.assertEqual(True, b.startswith(h, None, -2))
680n/a self.assertEqual(False, b.startswith(x, None, None))
681n/a
682n/a def test_integer_arguments_out_of_byte_range(self):
683n/a b = self.type2test(b'hello')
684n/a
685n/a for method in (b.count, b.find, b.index, b.rfind, b.rindex):
686n/a self.assertRaises(ValueError, method, -1)
687n/a self.assertRaises(ValueError, method, 256)
688n/a self.assertRaises(ValueError, method, 9999)
689n/a
690n/a def test_find_etc_raise_correct_error_messages(self):
691n/a # issue 11828
692n/a b = self.type2test(b'hello')
693n/a x = self.type2test(b'x')
694n/a self.assertRaisesRegex(TypeError, r'\bfind\b', b.find,
695n/a x, None, None, None)
696n/a self.assertRaisesRegex(TypeError, r'\brfind\b', b.rfind,
697n/a x, None, None, None)
698n/a self.assertRaisesRegex(TypeError, r'\bindex\b', b.index,
699n/a x, None, None, None)
700n/a self.assertRaisesRegex(TypeError, r'\brindex\b', b.rindex,
701n/a x, None, None, None)
702n/a self.assertRaisesRegex(TypeError, r'\bcount\b', b.count,
703n/a x, None, None, None)
704n/a self.assertRaisesRegex(TypeError, r'\bstartswith\b', b.startswith,
705n/a x, None, None, None)
706n/a self.assertRaisesRegex(TypeError, r'\bendswith\b', b.endswith,
707n/a x, None, None, None)
708n/a
709n/a def test_free_after_iterating(self):
710n/a test.support.check_free_after_iterating(self, iter, self.type2test)
711n/a test.support.check_free_after_iterating(self, reversed, self.type2test)
712n/a
713n/a def test_translate(self):
714n/a b = self.type2test(b'hello')
715n/a rosetta = bytearray(range(256))
716n/a rosetta[ord('o')] = ord('e')
717n/a
718n/a self.assertRaises(TypeError, b.translate)
719n/a self.assertRaises(TypeError, b.translate, None, None)
720n/a self.assertRaises(ValueError, b.translate, bytes(range(255)))
721n/a
722n/a c = b.translate(rosetta, b'hello')
723n/a self.assertEqual(b, b'hello')
724n/a self.assertIsInstance(c, self.type2test)
725n/a
726n/a c = b.translate(rosetta)
727n/a d = b.translate(rosetta, b'')
728n/a self.assertEqual(c, d)
729n/a self.assertEqual(c, b'helle')
730n/a
731n/a c = b.translate(rosetta, b'l')
732n/a self.assertEqual(c, b'hee')
733n/a c = b.translate(None, b'e')
734n/a self.assertEqual(c, b'hllo')
735n/a
736n/a # test delete as a keyword argument
737n/a c = b.translate(rosetta, delete=b'')
738n/a self.assertEqual(c, b'helle')
739n/a c = b.translate(rosetta, delete=b'l')
740n/a self.assertEqual(c, b'hee')
741n/a c = b.translate(None, delete=b'e')
742n/a self.assertEqual(c, b'hllo')
743n/a
744n/a
745n/aclass BytesTest(BaseBytesTest, unittest.TestCase):
746n/a type2test = bytes
747n/a
748n/a def test_getitem_error(self):
749n/a msg = "byte indices must be integers or slices"
750n/a with self.assertRaisesRegex(TypeError, msg):
751n/a b'python'['a']
752n/a
753n/a def test_buffer_is_readonly(self):
754n/a fd = os.open(__file__, os.O_RDONLY)
755n/a with open(fd, "rb", buffering=0) as f:
756n/a self.assertRaises(TypeError, f.readinto, b"")
757n/a
758n/a def test_custom(self):
759n/a class A:
760n/a def __bytes__(self):
761n/a return b'abc'
762n/a self.assertEqual(bytes(A()), b'abc')
763n/a class A: pass
764n/a self.assertRaises(TypeError, bytes, A())
765n/a class A:
766n/a def __bytes__(self):
767n/a return None
768n/a self.assertRaises(TypeError, bytes, A())
769n/a class A:
770n/a def __bytes__(self):
771n/a return b'a'
772n/a def __index__(self):
773n/a return 42
774n/a self.assertEqual(bytes(A()), b'a')
775n/a # Issue #25766
776n/a class A(str):
777n/a def __bytes__(self):
778n/a return b'abc'
779n/a self.assertEqual(bytes(A('\u20ac')), b'abc')
780n/a self.assertEqual(bytes(A('\u20ac'), 'iso8859-15'), b'\xa4')
781n/a # Issue #24731
782n/a class A:
783n/a def __bytes__(self):
784n/a return OtherBytesSubclass(b'abc')
785n/a self.assertEqual(bytes(A()), b'abc')
786n/a self.assertIs(type(bytes(A())), OtherBytesSubclass)
787n/a self.assertEqual(BytesSubclass(A()), b'abc')
788n/a self.assertIs(type(BytesSubclass(A())), BytesSubclass)
789n/a
790n/a # Test PyBytes_FromFormat()
791n/a def test_from_format(self):
792n/a ctypes = test.support.import_module('ctypes')
793n/a _testcapi = test.support.import_module('_testcapi')
794n/a from ctypes import pythonapi, py_object
795n/a from ctypes import (
796n/a c_int, c_uint,
797n/a c_long, c_ulong,
798n/a c_size_t, c_ssize_t,
799n/a c_char_p)
800n/a
801n/a PyBytes_FromFormat = pythonapi.PyBytes_FromFormat
802n/a PyBytes_FromFormat.restype = py_object
803n/a
804n/a # basic tests
805n/a self.assertEqual(PyBytes_FromFormat(b'format'),
806n/a b'format')
807n/a self.assertEqual(PyBytes_FromFormat(b'Hello %s !', b'world'),
808n/a b'Hello world !')
809n/a
810n/a # test formatters
811n/a self.assertEqual(PyBytes_FromFormat(b'c=%c', c_int(0)),
812n/a b'c=\0')
813n/a self.assertEqual(PyBytes_FromFormat(b'c=%c', c_int(ord('@'))),
814n/a b'c=@')
815n/a self.assertEqual(PyBytes_FromFormat(b'c=%c', c_int(255)),
816n/a b'c=\xff')
817n/a self.assertEqual(PyBytes_FromFormat(b'd=%d ld=%ld zd=%zd',
818n/a c_int(1), c_long(2),
819n/a c_size_t(3)),
820n/a b'd=1 ld=2 zd=3')
821n/a self.assertEqual(PyBytes_FromFormat(b'd=%d ld=%ld zd=%zd',
822n/a c_int(-1), c_long(-2),
823n/a c_size_t(-3)),
824n/a b'd=-1 ld=-2 zd=-3')
825n/a self.assertEqual(PyBytes_FromFormat(b'u=%u lu=%lu zu=%zu',
826n/a c_uint(123), c_ulong(456),
827n/a c_size_t(789)),
828n/a b'u=123 lu=456 zu=789')
829n/a self.assertEqual(PyBytes_FromFormat(b'i=%i', c_int(123)),
830n/a b'i=123')
831n/a self.assertEqual(PyBytes_FromFormat(b'i=%i', c_int(-123)),
832n/a b'i=-123')
833n/a self.assertEqual(PyBytes_FromFormat(b'x=%x', c_int(0xabc)),
834n/a b'x=abc')
835n/a
836n/a sizeof_ptr = ctypes.sizeof(c_char_p)
837n/a
838n/a if os.name == 'nt':
839n/a # Windows (MSCRT)
840n/a ptr_format = '0x%0{}X'.format(2 * sizeof_ptr)
841n/a def ptr_formatter(ptr):
842n/a return (ptr_format % ptr)
843n/a else:
844n/a # UNIX (glibc)
845n/a def ptr_formatter(ptr):
846n/a return '%#x' % ptr
847n/a
848n/a ptr = 0xabcdef
849n/a self.assertEqual(PyBytes_FromFormat(b'ptr=%p', c_char_p(ptr)),
850n/a ('ptr=' + ptr_formatter(ptr)).encode('ascii'))
851n/a self.assertEqual(PyBytes_FromFormat(b's=%s', c_char_p(b'cstr')),
852n/a b's=cstr')
853n/a
854n/a # test minimum and maximum integer values
855n/a size_max = c_size_t(-1).value
856n/a for formatstr, ctypes_type, value, py_formatter in (
857n/a (b'%d', c_int, _testcapi.INT_MIN, str),
858n/a (b'%d', c_int, _testcapi.INT_MAX, str),
859n/a (b'%ld', c_long, _testcapi.LONG_MIN, str),
860n/a (b'%ld', c_long, _testcapi.LONG_MAX, str),
861n/a (b'%lu', c_ulong, _testcapi.ULONG_MAX, str),
862n/a (b'%zd', c_ssize_t, _testcapi.PY_SSIZE_T_MIN, str),
863n/a (b'%zd', c_ssize_t, _testcapi.PY_SSIZE_T_MAX, str),
864n/a (b'%zu', c_size_t, size_max, str),
865n/a (b'%p', c_char_p, size_max, ptr_formatter),
866n/a ):
867n/a self.assertEqual(PyBytes_FromFormat(formatstr, ctypes_type(value)),
868n/a py_formatter(value).encode('ascii')),
869n/a
870n/a # width and precision (width is currently ignored)
871n/a self.assertEqual(PyBytes_FromFormat(b'%5s', b'a'),
872n/a b'a')
873n/a self.assertEqual(PyBytes_FromFormat(b'%.3s', b'abcdef'),
874n/a b'abc')
875n/a
876n/a # '%%' formatter
877n/a self.assertEqual(PyBytes_FromFormat(b'%%'),
878n/a b'%')
879n/a self.assertEqual(PyBytes_FromFormat(b'[%%]'),
880n/a b'[%]')
881n/a self.assertEqual(PyBytes_FromFormat(b'%%%c', c_int(ord('_'))),
882n/a b'%_')
883n/a self.assertEqual(PyBytes_FromFormat(b'%%s'),
884n/a b'%s')
885n/a
886n/a # Invalid formats and partial formatting
887n/a self.assertEqual(PyBytes_FromFormat(b'%'), b'%')
888n/a self.assertEqual(PyBytes_FromFormat(b'x=%i y=%', c_int(2), c_int(3)),
889n/a b'x=2 y=%')
890n/a
891n/a # Issue #19969: %c must raise OverflowError for values
892n/a # not in the range [0; 255]
893n/a self.assertRaises(OverflowError,
894n/a PyBytes_FromFormat, b'%c', c_int(-1))
895n/a self.assertRaises(OverflowError,
896n/a PyBytes_FromFormat, b'%c', c_int(256))
897n/a
898n/a def test_bytes_blocking(self):
899n/a class IterationBlocked(list):
900n/a __bytes__ = None
901n/a i = [0, 1, 2, 3]
902n/a self.assertEqual(bytes(i), b'\x00\x01\x02\x03')
903n/a self.assertRaises(TypeError, bytes, IterationBlocked(i))
904n/a
905n/a # At least in CPython, because bytes.__new__ and the C API
906n/a # PyBytes_FromObject have different fallback rules, integer
907n/a # fallback is handled specially, so test separately.
908n/a class IntBlocked(int):
909n/a __bytes__ = None
910n/a self.assertEqual(bytes(3), b'\0\0\0')
911n/a self.assertRaises(TypeError, bytes, IntBlocked(3))
912n/a
913n/a # While there is no separately-defined rule for handling bytes
914n/a # subclasses differently from other buffer-interface classes,
915n/a # an implementation may well special-case them (as CPython 2.x
916n/a # str did), so test them separately.
917n/a class BytesSubclassBlocked(bytes):
918n/a __bytes__ = None
919n/a self.assertEqual(bytes(b'ab'), b'ab')
920n/a self.assertRaises(TypeError, bytes, BytesSubclassBlocked(b'ab'))
921n/a
922n/a class BufferBlocked(bytearray):
923n/a __bytes__ = None
924n/a ba, bb = bytearray(b'ab'), BufferBlocked(b'ab')
925n/a self.assertEqual(bytes(ba), b'ab')
926n/a self.assertRaises(TypeError, bytes, bb)
927n/a
928n/a
929n/aclass ByteArrayTest(BaseBytesTest, unittest.TestCase):
930n/a type2test = bytearray
931n/a
932n/a def test_getitem_error(self):
933n/a msg = "bytearray indices must be integers or slices"
934n/a with self.assertRaisesRegex(TypeError, msg):
935n/a bytearray(b'python')['a']
936n/a
937n/a def test_setitem_error(self):
938n/a msg = "bytearray indices must be integers or slices"
939n/a with self.assertRaisesRegex(TypeError, msg):
940n/a b = bytearray(b'python')
941n/a b['a'] = "python"
942n/a
943n/a def test_nohash(self):
944n/a self.assertRaises(TypeError, hash, bytearray())
945n/a
946n/a def test_bytearray_api(self):
947n/a short_sample = b"Hello world\n"
948n/a sample = short_sample + b"\0"*(20 - len(short_sample))
949n/a tfn = tempfile.mktemp()
950n/a try:
951n/a # Prepare
952n/a with open(tfn, "wb") as f:
953n/a f.write(short_sample)
954n/a # Test readinto
955n/a with open(tfn, "rb") as f:
956n/a b = bytearray(20)
957n/a n = f.readinto(b)
958n/a self.assertEqual(n, len(short_sample))
959n/a self.assertEqual(list(b), list(sample))
960n/a # Test writing in binary mode
961n/a with open(tfn, "wb") as f:
962n/a f.write(b)
963n/a with open(tfn, "rb") as f:
964n/a self.assertEqual(f.read(), sample)
965n/a # Text mode is ambiguous; don't test
966n/a finally:
967n/a try:
968n/a os.remove(tfn)
969n/a except OSError:
970n/a pass
971n/a
972n/a def test_reverse(self):
973n/a b = bytearray(b'hello')
974n/a self.assertEqual(b.reverse(), None)
975n/a self.assertEqual(b, b'olleh')
976n/a b = bytearray(b'hello1') # test even number of items
977n/a b.reverse()
978n/a self.assertEqual(b, b'1olleh')
979n/a b = bytearray()
980n/a b.reverse()
981n/a self.assertFalse(b)
982n/a
983n/a def test_clear(self):
984n/a b = bytearray(b'python')
985n/a b.clear()
986n/a self.assertEqual(b, b'')
987n/a
988n/a b = bytearray(b'')
989n/a b.clear()
990n/a self.assertEqual(b, b'')
991n/a
992n/a b = bytearray(b'')
993n/a b.append(ord('r'))
994n/a b.clear()
995n/a b.append(ord('p'))
996n/a self.assertEqual(b, b'p')
997n/a
998n/a def test_copy(self):
999n/a b = bytearray(b'abc')
1000n/a bb = b.copy()
1001n/a self.assertEqual(bb, b'abc')
1002n/a
1003n/a b = bytearray(b'')
1004n/a bb = b.copy()
1005n/a self.assertEqual(bb, b'')
1006n/a
1007n/a # test that it's indeed a copy and not a reference
1008n/a b = bytearray(b'abc')
1009n/a bb = b.copy()
1010n/a self.assertEqual(b, bb)
1011n/a self.assertIsNot(b, bb)
1012n/a bb.append(ord('d'))
1013n/a self.assertEqual(bb, b'abcd')
1014n/a self.assertEqual(b, b'abc')
1015n/a
1016n/a def test_regexps(self):
1017n/a def by(s):
1018n/a return bytearray(map(ord, s))
1019n/a b = by("Hello, world")
1020n/a self.assertEqual(re.findall(br"\w+", b), [by("Hello"), by("world")])
1021n/a
1022n/a def test_setitem(self):
1023n/a b = bytearray([1, 2, 3])
1024n/a b[1] = 100
1025n/a self.assertEqual(b, bytearray([1, 100, 3]))
1026n/a b[-1] = 200
1027n/a self.assertEqual(b, bytearray([1, 100, 200]))
1028n/a b[0] = Indexable(10)
1029n/a self.assertEqual(b, bytearray([10, 100, 200]))
1030n/a try:
1031n/a b[3] = 0
1032n/a self.fail("Didn't raise IndexError")
1033n/a except IndexError:
1034n/a pass
1035n/a try:
1036n/a b[-10] = 0
1037n/a self.fail("Didn't raise IndexError")
1038n/a except IndexError:
1039n/a pass
1040n/a try:
1041n/a b[0] = 256
1042n/a self.fail("Didn't raise ValueError")
1043n/a except ValueError:
1044n/a pass
1045n/a try:
1046n/a b[0] = Indexable(-1)
1047n/a self.fail("Didn't raise ValueError")
1048n/a except ValueError:
1049n/a pass
1050n/a try:
1051n/a b[0] = None
1052n/a self.fail("Didn't raise TypeError")
1053n/a except TypeError:
1054n/a pass
1055n/a
1056n/a def test_delitem(self):
1057n/a b = bytearray(range(10))
1058n/a del b[0]
1059n/a self.assertEqual(b, bytearray(range(1, 10)))
1060n/a del b[-1]
1061n/a self.assertEqual(b, bytearray(range(1, 9)))
1062n/a del b[4]
1063n/a self.assertEqual(b, bytearray([1, 2, 3, 4, 6, 7, 8]))
1064n/a
1065n/a def test_setslice(self):
1066n/a b = bytearray(range(10))
1067n/a self.assertEqual(list(b), list(range(10)))
1068n/a
1069n/a b[0:5] = bytearray([1, 1, 1, 1, 1])
1070n/a self.assertEqual(b, bytearray([1, 1, 1, 1, 1, 5, 6, 7, 8, 9]))
1071n/a
1072n/a del b[0:-5]
1073n/a self.assertEqual(b, bytearray([5, 6, 7, 8, 9]))
1074n/a
1075n/a b[0:0] = bytearray([0, 1, 2, 3, 4])
1076n/a self.assertEqual(b, bytearray(range(10)))
1077n/a
1078n/a b[-7:-3] = bytearray([100, 101])
1079n/a self.assertEqual(b, bytearray([0, 1, 2, 100, 101, 7, 8, 9]))
1080n/a
1081n/a b[3:5] = [3, 4, 5, 6]
1082n/a self.assertEqual(b, bytearray(range(10)))
1083n/a
1084n/a b[3:0] = [42, 42, 42]
1085n/a self.assertEqual(b, bytearray([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9]))
1086n/a
1087n/a b[3:] = b'foo'
1088n/a self.assertEqual(b, bytearray([0, 1, 2, 102, 111, 111]))
1089n/a
1090n/a b[:3] = memoryview(b'foo')
1091n/a self.assertEqual(b, bytearray([102, 111, 111, 102, 111, 111]))
1092n/a
1093n/a b[3:4] = []
1094n/a self.assertEqual(b, bytearray([102, 111, 111, 111, 111]))
1095n/a
1096n/a for elem in [5, -5, 0, int(10e20), 'str', 2.3,
1097n/a ['a', 'b'], [b'a', b'b'], [[]]]:
1098n/a with self.assertRaises(TypeError):
1099n/a b[3:4] = elem
1100n/a
1101n/a for elem in [[254, 255, 256], [-256, 9000]]:
1102n/a with self.assertRaises(ValueError):
1103n/a b[3:4] = elem
1104n/a
1105n/a def test_setslice_extend(self):
1106n/a # Exercise the resizing logic (see issue #19087)
1107n/a b = bytearray(range(100))
1108n/a self.assertEqual(list(b), list(range(100)))
1109n/a del b[:10]
1110n/a self.assertEqual(list(b), list(range(10, 100)))
1111n/a b.extend(range(100, 110))
1112n/a self.assertEqual(list(b), list(range(10, 110)))
1113n/a
1114n/a def test_fifo_overrun(self):
1115n/a # Test for issue #23985, a buffer overrun when implementing a FIFO
1116n/a # Build Python in pydebug mode for best results.
1117n/a b = bytearray(10)
1118n/a b.pop() # Defeat expanding buffer off-by-one quirk
1119n/a del b[:1] # Advance start pointer without reallocating
1120n/a b += bytes(2) # Append exactly the number of deleted bytes
1121n/a del b # Free memory buffer, allowing pydebug verification
1122n/a
1123n/a def test_del_expand(self):
1124n/a # Reducing the size should not expand the buffer (issue #23985)
1125n/a b = bytearray(10)
1126n/a size = sys.getsizeof(b)
1127n/a del b[:1]
1128n/a self.assertLessEqual(sys.getsizeof(b), size)
1129n/a
1130n/a def test_extended_set_del_slice(self):
1131n/a indices = (0, None, 1, 3, 19, 300, 1<<333, -1, -2, -31, -300)
1132n/a for start in indices:
1133n/a for stop in indices:
1134n/a # Skip invalid step 0
1135n/a for step in indices[1:]:
1136n/a L = list(range(255))
1137n/a b = bytearray(L)
1138n/a # Make sure we have a slice of exactly the right length,
1139n/a # but with different data.
1140n/a data = L[start:stop:step]
1141n/a data.reverse()
1142n/a L[start:stop:step] = data
1143n/a b[start:stop:step] = data
1144n/a self.assertEqual(b, bytearray(L))
1145n/a
1146n/a del L[start:stop:step]
1147n/a del b[start:stop:step]
1148n/a self.assertEqual(b, bytearray(L))
1149n/a
1150n/a def test_setslice_trap(self):
1151n/a # This test verifies that we correctly handle assigning self
1152n/a # to a slice of self (the old Lambert Meertens trap).
1153n/a b = bytearray(range(256))
1154n/a b[8:] = b
1155n/a self.assertEqual(b, bytearray(list(range(8)) + list(range(256))))
1156n/a
1157n/a def test_iconcat(self):
1158n/a b = bytearray(b"abc")
1159n/a b1 = b
1160n/a b += b"def"
1161n/a self.assertEqual(b, b"abcdef")
1162n/a self.assertEqual(b, b1)
1163n/a self.assertTrue(b is b1)
1164n/a b += b"xyz"
1165n/a self.assertEqual(b, b"abcdefxyz")
1166n/a try:
1167n/a b += ""
1168n/a except TypeError:
1169n/a pass
1170n/a else:
1171n/a self.fail("bytes += unicode didn't raise TypeError")
1172n/a
1173n/a def test_irepeat(self):
1174n/a b = bytearray(b"abc")
1175n/a b1 = b
1176n/a b *= 3
1177n/a self.assertEqual(b, b"abcabcabc")
1178n/a self.assertEqual(b, b1)
1179n/a self.assertTrue(b is b1)
1180n/a
1181n/a def test_irepeat_1char(self):
1182n/a b = bytearray(b"x")
1183n/a b1 = b
1184n/a b *= 100
1185n/a self.assertEqual(b, b"x"*100)
1186n/a self.assertEqual(b, b1)
1187n/a self.assertTrue(b is b1)
1188n/a
1189n/a def test_alloc(self):
1190n/a b = bytearray()
1191n/a alloc = b.__alloc__()
1192n/a self.assertTrue(alloc >= 0)
1193n/a seq = [alloc]
1194n/a for i in range(100):
1195n/a b += b"x"
1196n/a alloc = b.__alloc__()
1197n/a self.assertGreater(alloc, len(b)) # including trailing null byte
1198n/a if alloc not in seq:
1199n/a seq.append(alloc)
1200n/a
1201n/a def test_init_alloc(self):
1202n/a b = bytearray()
1203n/a def g():
1204n/a for i in range(1, 100):
1205n/a yield i
1206n/a a = list(b)
1207n/a self.assertEqual(a, list(range(1, len(a)+1)))
1208n/a self.assertEqual(len(b), len(a))
1209n/a self.assertLessEqual(len(b), i)
1210n/a alloc = b.__alloc__()
1211n/a self.assertGreater(alloc, len(b)) # including trailing null byte
1212n/a b.__init__(g())
1213n/a self.assertEqual(list(b), list(range(1, 100)))
1214n/a self.assertEqual(len(b), 99)
1215n/a alloc = b.__alloc__()
1216n/a self.assertGreater(alloc, len(b))
1217n/a
1218n/a def test_extend(self):
1219n/a orig = b'hello'
1220n/a a = bytearray(orig)
1221n/a a.extend(a)
1222n/a self.assertEqual(a, orig + orig)
1223n/a self.assertEqual(a[5:], orig)
1224n/a a = bytearray(b'')
1225n/a # Test iterators that don't have a __length_hint__
1226n/a a.extend(map(int, orig * 25))
1227n/a a.extend(int(x) for x in orig * 25)
1228n/a self.assertEqual(a, orig * 50)
1229n/a self.assertEqual(a[-5:], orig)
1230n/a a = bytearray(b'')
1231n/a a.extend(iter(map(int, orig * 50)))
1232n/a self.assertEqual(a, orig * 50)
1233n/a self.assertEqual(a[-5:], orig)
1234n/a a = bytearray(b'')
1235n/a a.extend(list(map(int, orig * 50)))
1236n/a self.assertEqual(a, orig * 50)
1237n/a self.assertEqual(a[-5:], orig)
1238n/a a = bytearray(b'')
1239n/a self.assertRaises(ValueError, a.extend, [0, 1, 2, 256])
1240n/a self.assertRaises(ValueError, a.extend, [0, 1, 2, -1])
1241n/a self.assertEqual(len(a), 0)
1242n/a a = bytearray(b'')
1243n/a a.extend([Indexable(ord('a'))])
1244n/a self.assertEqual(a, b'a')
1245n/a
1246n/a def test_remove(self):
1247n/a b = bytearray(b'hello')
1248n/a b.remove(ord('l'))
1249n/a self.assertEqual(b, b'helo')
1250n/a b.remove(ord('l'))
1251n/a self.assertEqual(b, b'heo')
1252n/a self.assertRaises(ValueError, lambda: b.remove(ord('l')))
1253n/a self.assertRaises(ValueError, lambda: b.remove(400))
1254n/a self.assertRaises(TypeError, lambda: b.remove('e'))
1255n/a # remove first and last
1256n/a b.remove(ord('o'))
1257n/a b.remove(ord('h'))
1258n/a self.assertEqual(b, b'e')
1259n/a self.assertRaises(TypeError, lambda: b.remove(b'e'))
1260n/a b.remove(Indexable(ord('e')))
1261n/a self.assertEqual(b, b'')
1262n/a
1263n/a # test values outside of the ascii range: (0, 127)
1264n/a c = bytearray([126, 127, 128, 129])
1265n/a c.remove(127)
1266n/a self.assertEqual(c, bytes([126, 128, 129]))
1267n/a c.remove(129)
1268n/a self.assertEqual(c, bytes([126, 128]))
1269n/a
1270n/a def test_pop(self):
1271n/a b = bytearray(b'world')
1272n/a self.assertEqual(b.pop(), ord('d'))
1273n/a self.assertEqual(b.pop(0), ord('w'))
1274n/a self.assertEqual(b.pop(-2), ord('r'))
1275n/a self.assertRaises(IndexError, lambda: b.pop(10))
1276n/a self.assertRaises(IndexError, lambda: bytearray().pop())
1277n/a # test for issue #6846
1278n/a self.assertEqual(bytearray(b'\xff').pop(), 0xff)
1279n/a
1280n/a def test_nosort(self):
1281n/a self.assertRaises(AttributeError, lambda: bytearray().sort())
1282n/a
1283n/a def test_append(self):
1284n/a b = bytearray(b'hell')
1285n/a b.append(ord('o'))
1286n/a self.assertEqual(b, b'hello')
1287n/a self.assertEqual(b.append(100), None)
1288n/a b = bytearray()
1289n/a b.append(ord('A'))
1290n/a self.assertEqual(len(b), 1)
1291n/a self.assertRaises(TypeError, lambda: b.append(b'o'))
1292n/a b = bytearray()
1293n/a b.append(Indexable(ord('A')))
1294n/a self.assertEqual(b, b'A')
1295n/a
1296n/a def test_insert(self):
1297n/a b = bytearray(b'msssspp')
1298n/a b.insert(1, ord('i'))
1299n/a b.insert(4, ord('i'))
1300n/a b.insert(-2, ord('i'))
1301n/a b.insert(1000, ord('i'))
1302n/a self.assertEqual(b, b'mississippi')
1303n/a self.assertRaises(TypeError, lambda: b.insert(0, b'1'))
1304n/a b = bytearray()
1305n/a b.insert(0, Indexable(ord('A')))
1306n/a self.assertEqual(b, b'A')
1307n/a
1308n/a def test_copied(self):
1309n/a # Issue 4348. Make sure that operations that don't mutate the array
1310n/a # copy the bytes.
1311n/a b = bytearray(b'abc')
1312n/a self.assertFalse(b is b.replace(b'abc', b'cde', 0))
1313n/a
1314n/a t = bytearray([i for i in range(256)])
1315n/a x = bytearray(b'')
1316n/a self.assertFalse(x is x.translate(t))
1317n/a
1318n/a def test_partition_bytearray_doesnt_share_nullstring(self):
1319n/a a, b, c = bytearray(b"x").partition(b"y")
1320n/a self.assertEqual(b, b"")
1321n/a self.assertEqual(c, b"")
1322n/a self.assertTrue(b is not c)
1323n/a b += b"!"
1324n/a self.assertEqual(c, b"")
1325n/a a, b, c = bytearray(b"x").partition(b"y")
1326n/a self.assertEqual(b, b"")
1327n/a self.assertEqual(c, b"")
1328n/a # Same for rpartition
1329n/a b, c, a = bytearray(b"x").rpartition(b"y")
1330n/a self.assertEqual(b, b"")
1331n/a self.assertEqual(c, b"")
1332n/a self.assertTrue(b is not c)
1333n/a b += b"!"
1334n/a self.assertEqual(c, b"")
1335n/a c, b, a = bytearray(b"x").rpartition(b"y")
1336n/a self.assertEqual(b, b"")
1337n/a self.assertEqual(c, b"")
1338n/a
1339n/a def test_resize_forbidden(self):
1340n/a # #4509: can't resize a bytearray when there are buffer exports, even
1341n/a # if it wouldn't reallocate the underlying buffer.
1342n/a # Furthermore, no destructive changes to the buffer may be applied
1343n/a # before raising the error.
1344n/a b = bytearray(range(10))
1345n/a v = memoryview(b)
1346n/a def resize(n):
1347n/a b[1:-1] = range(n + 1, 2*n - 1)
1348n/a resize(10)
1349n/a orig = b[:]
1350n/a self.assertRaises(BufferError, resize, 11)
1351n/a self.assertEqual(b, orig)
1352n/a self.assertRaises(BufferError, resize, 9)
1353n/a self.assertEqual(b, orig)
1354n/a self.assertRaises(BufferError, resize, 0)
1355n/a self.assertEqual(b, orig)
1356n/a # Other operations implying resize
1357n/a self.assertRaises(BufferError, b.pop, 0)
1358n/a self.assertEqual(b, orig)
1359n/a self.assertRaises(BufferError, b.remove, b[1])
1360n/a self.assertEqual(b, orig)
1361n/a def delitem():
1362n/a del b[1]
1363n/a self.assertRaises(BufferError, delitem)
1364n/a self.assertEqual(b, orig)
1365n/a # deleting a non-contiguous slice
1366n/a def delslice():
1367n/a b[1:-1:2] = b""
1368n/a self.assertRaises(BufferError, delslice)
1369n/a self.assertEqual(b, orig)
1370n/a
1371n/a @test.support.cpython_only
1372n/a def test_obsolete_write_lock(self):
1373n/a from _testcapi import getbuffer_with_null_view
1374n/a self.assertRaises(BufferError, getbuffer_with_null_view, bytearray())
1375n/a
1376n/a def test_iterator_pickling2(self):
1377n/a orig = bytearray(b'abc')
1378n/a data = list(b'qwerty')
1379n/a for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1380n/a # initial iterator
1381n/a itorig = iter(orig)
1382n/a d = pickle.dumps((itorig, orig), proto)
1383n/a it, b = pickle.loads(d)
1384n/a b[:] = data
1385n/a self.assertEqual(type(it), type(itorig))
1386n/a self.assertEqual(list(it), data)
1387n/a
1388n/a # running iterator
1389n/a next(itorig)
1390n/a d = pickle.dumps((itorig, orig), proto)
1391n/a it, b = pickle.loads(d)
1392n/a b[:] = data
1393n/a self.assertEqual(type(it), type(itorig))
1394n/a self.assertEqual(list(it), data[1:])
1395n/a
1396n/a # empty iterator
1397n/a for i in range(1, len(orig)):
1398n/a next(itorig)
1399n/a d = pickle.dumps((itorig, orig), proto)
1400n/a it, b = pickle.loads(d)
1401n/a b[:] = data
1402n/a self.assertEqual(type(it), type(itorig))
1403n/a self.assertEqual(list(it), data[len(orig):])
1404n/a
1405n/a # exhausted iterator
1406n/a self.assertRaises(StopIteration, next, itorig)
1407n/a d = pickle.dumps((itorig, orig), proto)
1408n/a it, b = pickle.loads(d)
1409n/a b[:] = data
1410n/a self.assertEqual(list(it), [])
1411n/a
1412n/a test_exhausted_iterator = test.list_tests.CommonTest.test_exhausted_iterator
1413n/a
1414n/a def test_iterator_length_hint(self):
1415n/a # Issue 27443: __length_hint__ can return negative integer
1416n/a ba = bytearray(b'ab')
1417n/a it = iter(ba)
1418n/a next(it)
1419n/a ba.clear()
1420n/a # Shouldn't raise an error
1421n/a self.assertEqual(list(it), [])
1422n/a
1423n/a
1424n/aclass AssortedBytesTest(unittest.TestCase):
1425n/a #
1426n/a # Test various combinations of bytes and bytearray
1427n/a #
1428n/a
1429n/a @check_bytes_warnings
1430n/a def test_repr_str(self):
1431n/a for f in str, repr:
1432n/a self.assertEqual(f(bytearray()), "bytearray(b'')")
1433n/a self.assertEqual(f(bytearray([0])), "bytearray(b'\\x00')")
1434n/a self.assertEqual(f(bytearray([0, 1, 254, 255])),
1435n/a "bytearray(b'\\x00\\x01\\xfe\\xff')")
1436n/a self.assertEqual(f(b"abc"), "b'abc'")
1437n/a self.assertEqual(f(b"'"), '''b"'"''') # '''
1438n/a self.assertEqual(f(b"'\""), r"""b'\'"'""") # '
1439n/a
1440n/a @check_bytes_warnings
1441n/a def test_format(self):
1442n/a for b in b'abc', bytearray(b'abc'):
1443n/a self.assertEqual(format(b), str(b))
1444n/a self.assertEqual(format(b, ''), str(b))
1445n/a with self.assertRaisesRegex(TypeError,
1446n/a r'\b%s\b' % re.escape(type(b).__name__)):
1447n/a format(b, 's')
1448n/a
1449n/a def test_compare_bytes_to_bytearray(self):
1450n/a self.assertEqual(b"abc" == bytes(b"abc"), True)
1451n/a self.assertEqual(b"ab" != bytes(b"abc"), True)
1452n/a self.assertEqual(b"ab" <= bytes(b"abc"), True)
1453n/a self.assertEqual(b"ab" < bytes(b"abc"), True)
1454n/a self.assertEqual(b"abc" >= bytes(b"ab"), True)
1455n/a self.assertEqual(b"abc" > bytes(b"ab"), True)
1456n/a
1457n/a self.assertEqual(b"abc" != bytes(b"abc"), False)
1458n/a self.assertEqual(b"ab" == bytes(b"abc"), False)
1459n/a self.assertEqual(b"ab" > bytes(b"abc"), False)
1460n/a self.assertEqual(b"ab" >= bytes(b"abc"), False)
1461n/a self.assertEqual(b"abc" < bytes(b"ab"), False)
1462n/a self.assertEqual(b"abc" <= bytes(b"ab"), False)
1463n/a
1464n/a self.assertEqual(bytes(b"abc") == b"abc", True)
1465n/a self.assertEqual(bytes(b"ab") != b"abc", True)
1466n/a self.assertEqual(bytes(b"ab") <= b"abc", True)
1467n/a self.assertEqual(bytes(b"ab") < b"abc", True)
1468n/a self.assertEqual(bytes(b"abc") >= b"ab", True)
1469n/a self.assertEqual(bytes(b"abc") > b"ab", True)
1470n/a
1471n/a self.assertEqual(bytes(b"abc") != b"abc", False)
1472n/a self.assertEqual(bytes(b"ab") == b"abc", False)
1473n/a self.assertEqual(bytes(b"ab") > b"abc", False)
1474n/a self.assertEqual(bytes(b"ab") >= b"abc", False)
1475n/a self.assertEqual(bytes(b"abc") < b"ab", False)
1476n/a self.assertEqual(bytes(b"abc") <= b"ab", False)
1477n/a
1478n/a @test.support.requires_docstrings
1479n/a def test_doc(self):
1480n/a self.assertIsNotNone(bytearray.__doc__)
1481n/a self.assertTrue(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__)
1482n/a self.assertIsNotNone(bytes.__doc__)
1483n/a self.assertTrue(bytes.__doc__.startswith("bytes("), bytes.__doc__)
1484n/a
1485n/a def test_from_bytearray(self):
1486n/a sample = bytes(b"Hello world\n\x80\x81\xfe\xff")
1487n/a buf = memoryview(sample)
1488n/a b = bytearray(buf)
1489n/a self.assertEqual(b, bytearray(sample))
1490n/a
1491n/a @check_bytes_warnings
1492n/a def test_to_str(self):
1493n/a self.assertEqual(str(b''), "b''")
1494n/a self.assertEqual(str(b'x'), "b'x'")
1495n/a self.assertEqual(str(b'\x80'), "b'\\x80'")
1496n/a self.assertEqual(str(bytearray(b'')), "bytearray(b'')")
1497n/a self.assertEqual(str(bytearray(b'x')), "bytearray(b'x')")
1498n/a self.assertEqual(str(bytearray(b'\x80')), "bytearray(b'\\x80')")
1499n/a
1500n/a def test_literal(self):
1501n/a tests = [
1502n/a (b"Wonderful spam", "Wonderful spam"),
1503n/a (br"Wonderful spam too", "Wonderful spam too"),
1504n/a (b"\xaa\x00\000\200", "\xaa\x00\000\200"),
1505n/a (br"\xaa\x00\000\200", r"\xaa\x00\000\200"),
1506n/a ]
1507n/a for b, s in tests:
1508n/a self.assertEqual(b, bytearray(s, 'latin-1'))
1509n/a for c in range(128, 256):
1510n/a self.assertRaises(SyntaxError, eval,
1511n/a 'b"%s"' % chr(c))
1512n/a
1513n/a def test_split_bytearray(self):
1514n/a self.assertEqual(b'a b'.split(memoryview(b' ')), [b'a', b'b'])
1515n/a
1516n/a def test_rsplit_bytearray(self):
1517n/a self.assertEqual(b'a b'.rsplit(memoryview(b' ')), [b'a', b'b'])
1518n/a
1519n/a def test_return_self(self):
1520n/a # bytearray.replace must always return a new bytearray
1521n/a b = bytearray()
1522n/a self.assertFalse(b.replace(b'', b'') is b)
1523n/a
1524n/a @unittest.skipUnless(sys.flags.bytes_warning,
1525n/a "BytesWarning is needed for this test: use -bb option")
1526n/a def test_compare(self):
1527n/a def bytes_warning():
1528n/a return test.support.check_warnings(('', BytesWarning))
1529n/a with bytes_warning():
1530n/a b'' == ''
1531n/a with bytes_warning():
1532n/a '' == b''
1533n/a with bytes_warning():
1534n/a b'' != ''
1535n/a with bytes_warning():
1536n/a '' != b''
1537n/a with bytes_warning():
1538n/a bytearray(b'') == ''
1539n/a with bytes_warning():
1540n/a '' == bytearray(b'')
1541n/a with bytes_warning():
1542n/a bytearray(b'') != ''
1543n/a with bytes_warning():
1544n/a '' != bytearray(b'')
1545n/a with bytes_warning():
1546n/a b'\0' == 0
1547n/a with bytes_warning():
1548n/a 0 == b'\0'
1549n/a with bytes_warning():
1550n/a b'\0' != 0
1551n/a with bytes_warning():
1552n/a 0 != b'\0'
1553n/a
1554n/a # Optimizations:
1555n/a # __iter__? (optimization)
1556n/a # __reversed__? (optimization)
1557n/a
1558n/a # XXX More string methods? (Those that don't use character properties)
1559n/a
1560n/a # There are tests in string_tests.py that are more
1561n/a # comprehensive for things like partition, etc.
1562n/a # Unfortunately they are all bundled with tests that
1563n/a # are not appropriate for bytes
1564n/a
1565n/a # I've started porting some of those into bytearray_tests.py, we should port
1566n/a # the rest that make sense (the code can be cleaned up to use modern
1567n/a # unittest methods at the same time).
1568n/a
1569n/aclass BytearrayPEP3137Test(unittest.TestCase):
1570n/a def marshal(self, x):
1571n/a return bytearray(x)
1572n/a
1573n/a def test_returns_new_copy(self):
1574n/a val = self.marshal(b'1234')
1575n/a # On immutable types these MAY return a reference to themselves
1576n/a # but on mutable types like bytearray they MUST return a new copy.
1577n/a for methname in ('zfill', 'rjust', 'ljust', 'center'):
1578n/a method = getattr(val, methname)
1579n/a newval = method(3)
1580n/a self.assertEqual(val, newval)
1581n/a self.assertTrue(val is not newval,
1582n/a methname+' returned self on a mutable object')
1583n/a for expr in ('val.split()[0]', 'val.rsplit()[0]',
1584n/a 'val.partition(b".")[0]', 'val.rpartition(b".")[2]',
1585n/a 'val.splitlines()[0]', 'val.replace(b"", b"")'):
1586n/a newval = eval(expr)
1587n/a self.assertEqual(val, newval)
1588n/a self.assertTrue(val is not newval,
1589n/a expr+' returned val on a mutable object')
1590n/a sep = self.marshal(b'')
1591n/a newval = sep.join([val])
1592n/a self.assertEqual(val, newval)
1593n/a self.assertIsNot(val, newval)
1594n/a
1595n/a
1596n/aclass FixedStringTest(test.string_tests.BaseTest):
1597n/a def fixtype(self, obj):
1598n/a if isinstance(obj, str):
1599n/a return self.type2test(obj.encode("utf-8"))
1600n/a return super().fixtype(obj)
1601n/a
1602n/a contains_bytes = True
1603n/a
1604n/aclass ByteArrayAsStringTest(FixedStringTest, unittest.TestCase):
1605n/a type2test = bytearray
1606n/a
1607n/aclass BytesAsStringTest(FixedStringTest, unittest.TestCase):
1608n/a type2test = bytes
1609n/a
1610n/a
1611n/aclass SubclassTest:
1612n/a
1613n/a def test_basic(self):
1614n/a self.assertTrue(issubclass(self.type2test, self.basetype))
1615n/a self.assertIsInstance(self.type2test(), self.basetype)
1616n/a
1617n/a a, b = b"abcd", b"efgh"
1618n/a _a, _b = self.type2test(a), self.type2test(b)
1619n/a
1620n/a # test comparison operators with subclass instances
1621n/a self.assertTrue(_a == _a)
1622n/a self.assertTrue(_a != _b)
1623n/a self.assertTrue(_a < _b)
1624n/a self.assertTrue(_a <= _b)
1625n/a self.assertTrue(_b >= _a)
1626n/a self.assertTrue(_b > _a)
1627n/a self.assertTrue(_a is not a)
1628n/a
1629n/a # test concat of subclass instances
1630n/a self.assertEqual(a + b, _a + _b)
1631n/a self.assertEqual(a + b, a + _b)
1632n/a self.assertEqual(a + b, _a + b)
1633n/a
1634n/a # test repeat
1635n/a self.assertTrue(a*5 == _a*5)
1636n/a
1637n/a def test_join(self):
1638n/a # Make sure join returns a NEW object for single item sequences
1639n/a # involving a subclass.
1640n/a # Make sure that it is of the appropriate type.
1641n/a s1 = self.type2test(b"abcd")
1642n/a s2 = self.basetype().join([s1])
1643n/a self.assertTrue(s1 is not s2)
1644n/a self.assertTrue(type(s2) is self.basetype, type(s2))
1645n/a
1646n/a # Test reverse, calling join on subclass
1647n/a s3 = s1.join([b"abcd"])
1648n/a self.assertTrue(type(s3) is self.basetype)
1649n/a
1650n/a def test_pickle(self):
1651n/a a = self.type2test(b"abcd")
1652n/a a.x = 10
1653n/a a.y = self.type2test(b"efgh")
1654n/a for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1655n/a b = pickle.loads(pickle.dumps(a, proto))
1656n/a self.assertNotEqual(id(a), id(b))
1657n/a self.assertEqual(a, b)
1658n/a self.assertEqual(a.x, b.x)
1659n/a self.assertEqual(a.y, b.y)
1660n/a self.assertEqual(type(a), type(b))
1661n/a self.assertEqual(type(a.y), type(b.y))
1662n/a
1663n/a def test_copy(self):
1664n/a a = self.type2test(b"abcd")
1665n/a a.x = 10
1666n/a a.y = self.type2test(b"efgh")
1667n/a for copy_method in (copy.copy, copy.deepcopy):
1668n/a b = copy_method(a)
1669n/a self.assertNotEqual(id(a), id(b))
1670n/a self.assertEqual(a, b)
1671n/a self.assertEqual(a.x, b.x)
1672n/a self.assertEqual(a.y, b.y)
1673n/a self.assertEqual(type(a), type(b))
1674n/a self.assertEqual(type(a.y), type(b.y))
1675n/a
1676n/a def test_fromhex(self):
1677n/a b = self.type2test.fromhex('1a2B30')
1678n/a self.assertEqual(b, b'\x1a\x2b\x30')
1679n/a self.assertIs(type(b), self.type2test)
1680n/a
1681n/a class B1(self.basetype):
1682n/a def __new__(cls, value):
1683n/a me = self.basetype.__new__(cls, value)
1684n/a me.foo = 'bar'
1685n/a return me
1686n/a
1687n/a b = B1.fromhex('1a2B30')
1688n/a self.assertEqual(b, b'\x1a\x2b\x30')
1689n/a self.assertIs(type(b), B1)
1690n/a self.assertEqual(b.foo, 'bar')
1691n/a
1692n/a class B2(self.basetype):
1693n/a def __init__(me, *args, **kwargs):
1694n/a if self.basetype is not bytes:
1695n/a self.basetype.__init__(me, *args, **kwargs)
1696n/a me.foo = 'bar'
1697n/a
1698n/a b = B2.fromhex('1a2B30')
1699n/a self.assertEqual(b, b'\x1a\x2b\x30')
1700n/a self.assertIs(type(b), B2)
1701n/a self.assertEqual(b.foo, 'bar')
1702n/a
1703n/a
1704n/aclass ByteArraySubclass(bytearray):
1705n/a pass
1706n/a
1707n/aclass BytesSubclass(bytes):
1708n/a pass
1709n/a
1710n/aclass OtherBytesSubclass(bytes):
1711n/a pass
1712n/a
1713n/aclass ByteArraySubclassTest(SubclassTest, unittest.TestCase):
1714n/a basetype = bytearray
1715n/a type2test = ByteArraySubclass
1716n/a
1717n/a def test_init_override(self):
1718n/a class subclass(bytearray):
1719n/a def __init__(me, newarg=1, *args, **kwargs):
1720n/a bytearray.__init__(me, *args, **kwargs)
1721n/a x = subclass(4, b"abcd")
1722n/a x = subclass(4, source=b"abcd")
1723n/a self.assertEqual(x, b"abcd")
1724n/a x = subclass(newarg=4, source=b"abcd")
1725n/a self.assertEqual(x, b"abcd")
1726n/a
1727n/a
1728n/aclass BytesSubclassTest(SubclassTest, unittest.TestCase):
1729n/a basetype = bytes
1730n/a type2test = BytesSubclass
1731n/a
1732n/a
1733n/aif __name__ == "__main__":
1734n/a unittest.main()