this repo has no description
1#!/usr/bin/env python3
2# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
3import unittest
4import warnings
5from unittest.mock import Mock
6
7
8class BytesTests(unittest.TestCase):
9 def test_center_without_growth_returns_original_bytes(self):
10 foo = b"foo"
11 self.assertIs(foo.center(-1), foo)
12 self.assertIs(foo.center(0), foo)
13 self.assertIs(foo.center(1), foo)
14 self.assertIs(foo.center(2), foo)
15 self.assertIs(foo.center(3), foo)
16
17 def test_center_with_both_odd_centers_bytes(self):
18 self.assertEqual(b"abc".center(5), b" abc ")
19 self.assertEqual(b"abc".center(7), b" abc ")
20
21 def test_center_with_both_even_centers_bytes(self):
22 self.assertEqual(b"".center(4), b" ")
23 self.assertEqual(b"abcd".center(8), b" abcd ")
24
25 def test_center_with_odd_length_and_even_number_centers_bytes(self):
26 self.assertEqual(b"foo".center(4), b"foo ")
27 self.assertEqual(b"\t \n".center(6), b" \t \n ")
28
29 def test_center_with_even_length_and_odd_number_centers_bytes(self):
30 self.assertEqual(b"food".center(5), b" food")
31 self.assertEqual(b"\t \n".center(7), b" \t \n ")
32
33 def test_center_with_custom_fillchar_returns_bytes(self):
34 self.assertEqual(b"ba".center(7, b"@"), b"@@@ba@@")
35
36 def test_center_with_non_bytes_fillchar_raises_type_error(self):
37 with self.assertRaises(TypeError) as context:
38 b"".center(2, ord(" "))
39 self.assertEqual(
40 str(context.exception),
41 "center() argument 2 must be a byte string of length 1, not int",
42 )
43
44 def test_center_with_wrong_length_fillchar_raises_type_error(self):
45 with self.assertRaises(TypeError) as context:
46 b"".center(2, b",,")
47 self.assertEqual(
48 str(context.exception),
49 "center() argument 2 must be a byte string of length 1, not bytes",
50 )
51
52 def test_decode_finds_ascii(self):
53 self.assertEqual(b"abc".decode("ascii"), "abc")
54
55 def test_decode_finds_latin_1(self):
56 self.assertEqual(b"abc\xE5".decode("latin-1"), "abc\xE5")
57
58 def test_dunder_add_with_bytes_like_other_returns_bytes(self):
59 self.assertEqual(b"123".__add__(bytearray(b"456")), b"123456")
60
61 def test_dunder_add_with_non_bytes_like_other_raises_type_error(self):
62 with self.assertRaises(TypeError) as context:
63 b"".__add__(2)
64 self.assertEqual(str(context.exception), "can't concat int to bytes")
65
66 def test_dunder_contains_with_non_bytes_raises_type_error(self):
67 with self.assertRaises(TypeError):
68 bytes.__contains__("not_bytes", 123)
69
70 def test_dunder_contains_with_element_in_bytes_returns_true(self):
71 self.assertTrue(b"abc".__contains__(ord("a")))
72
73 def test_dunder_contains_with_element_not_in_bytes_returns_false(self):
74 self.assertFalse(b"abc".__contains__(ord("z")))
75
76 def test_dunder_contains_calls_dunder_index(self):
77 class C:
78 __index__ = Mock(name="__index__", return_value=ord("a"))
79
80 c = C()
81 self.assertTrue(b"abc".__contains__(c))
82 c.__index__.assert_called_once()
83
84 def test_dunder_contains_calls_dunder_index_before_checking_byteslike(self):
85 class C(bytearray):
86 __index__ = Mock(name="__index__", return_value=ord("a"))
87
88 c = C(b"q")
89 self.assertTrue(b"abc".__contains__(c))
90 c.__index__.assert_called_once()
91
92 def test_dunder_contains_ignores_errors_from_dunder_index(self):
93 class C:
94 __index__ = Mock(name="__index__", side_effect=MemoryError("foo"))
95
96 c = C()
97 container = b"abc"
98 with self.assertRaises(TypeError):
99 container.__contains__(c)
100 c.__index__.assert_called_once()
101
102 def test_dunder_contains_with_single_byte_byteslike_returns_true(self):
103 self.assertTrue(b"abc".__contains__(b"a"))
104 self.assertTrue(b"abc".__contains__(bytearray(b"a")))
105
106 def test_dunder_contains_with_single_byte_byteslike_returns_false(self):
107 self.assertFalse(b"abc".__contains__(b"z"))
108 self.assertFalse(b"abc".__contains__(bytearray(b"z")))
109
110 def test_dunder_contains_with_byteslike_returns_true(self):
111 self.assertTrue(b"foobar".__contains__(b"foo"))
112 self.assertTrue(b"foobar".__contains__(bytearray(b"bar")))
113
114 def test_dunder_contains_with_byteslike_returns_false(self):
115 self.assertFalse(b"foobar".__contains__(b"baz"))
116 self.assertFalse(b"foobar".__contains__(bytearray(b"baz")))
117
118 def test_dunder_getitem_with_non_bytes_raises_type_error(self):
119 self.assertRaisesRegex(
120 TypeError,
121 "'__getitem__' .* 'bytes' object.* a 'str'",
122 bytes.__getitem__,
123 "not a bytes",
124 1,
125 )
126
127 def test_dunder_iter_returns_iterator(self):
128 b = b"123"
129 it = b.__iter__()
130 self.assertTrue(hasattr(it, "__next__"))
131 self.assertIs(iter(it), it)
132
133 def test_dunder_mul_with_non_bytes_raises_type_error(self):
134 self.assertRaisesRegex(
135 TypeError,
136 "'__mul__' .* 'bytes' object.* a 'str'",
137 bytes.__mul__,
138 "not a bytes",
139 2,
140 )
141
142 def test_dunder_new_with_str_without_encoding_raises_type_error(self):
143 with self.assertRaises(TypeError):
144 bytes("foo")
145
146 def test_dunder_new_with_str_and_encoding_returns_bytes(self):
147 self.assertEqual(bytes("foo", "ascii"), b"foo")
148
149 def test_dunder_new_with_ignore_errors_returns_bytes(self):
150 self.assertEqual(bytes("fo\x80o", "ascii", "ignore"), b"foo")
151
152 def test_dunder_new_with_bytes_subclass_returns_bytes_subclass(self):
153 class A(bytes):
154 pass
155
156 class B(bytes):
157 pass
158
159 class C:
160 def __bytes__(self):
161 return B()
162
163 self.assertIsInstance(bytes.__new__(A, b""), A)
164 self.assertIsInstance(bytes.__new__(B, 2), B)
165 self.assertIsInstance(bytes.__new__(A, C()), A)
166
167 def test_dunder_repr_with_non_bytes_raises_type_error(self):
168 self.assertRaisesRegex(
169 TypeError,
170 "'__repr__' .* 'bytes' object.* a 'str'",
171 bytes.__repr__,
172 "not a bytes",
173 )
174
175 def test_dunder_str_returns_same_as_dunder_repr(self):
176 b = b"foobar\x80"
177 b_str = b.__repr__()
178 self.assertEqual(b_str, "b'foobar\\x80'")
179 self.assertEqual(b_str, b.__str__())
180
181 def test_count_with_bytearray_self_raises_type_error(self):
182 self.assertRaisesRegex(
183 TypeError,
184 "'count' .* 'bytes' object.* a 'bytearray'",
185 bytes.count,
186 bytearray(),
187 b"",
188 )
189
190 def test_count_with_nonbyte_int_raises_value_error(self):
191 haystack = b""
192 needle = 266
193 with self.assertRaises(ValueError) as context:
194 haystack.count(needle)
195 self.assertEqual(str(context.exception), "byte must be in range(0, 256)")
196
197 def test_count_with_string_raises_type_error(self):
198 haystack = b""
199 needle = "133"
200 with self.assertRaises(TypeError) as context:
201 haystack.count(needle)
202 self.assertEqual(
203 str(context.exception),
204 "argument should be integer or bytes-like object, not 'str'",
205 )
206
207 def test_count_with_non_number_index(self):
208 class Idx:
209 def __index__(self):
210 return ord("a")
211
212 haystack = b"abc"
213 needle = Idx()
214 self.assertEqual(haystack.count(needle), 1)
215
216 def test_count_with_dunder_int_calls_dunder_index(self):
217 class Desc:
218 def __get__(self, obj, type):
219 raise NotImplementedError("called descriptor")
220
221 class Idx:
222 def __index__(self):
223 return ord("a")
224
225 __int__ = Desc()
226
227 haystack = b"abc"
228 needle = Idx()
229 self.assertEqual(haystack.count(needle), 1)
230
231 def test_count_with_dunder_float_calls_dunder_index(self):
232 class Desc:
233 def __get__(self, obj, type):
234 raise NotImplementedError("called descriptor")
235
236 class Idx:
237 __float__ = Desc()
238
239 def __index__(self):
240 return ord("a")
241
242 haystack = b"abc"
243 needle = Idx()
244 self.assertEqual(haystack.count(needle), 1)
245
246 def test_count_with_index_overflow_raises_overflow_error(self):
247 class Idx:
248 def __float__(self):
249 return 0.0
250
251 def __index__(self):
252 raise OverflowError("not a byte!")
253
254 haystack = b"abc"
255 needle = Idx()
256 with self.assertRaises(OverflowError) as context:
257 haystack.count(needle)
258 self.assertEqual(str(context.exception), "not a byte!")
259
260 def test_count_with_index_error_raises_type_error(self):
261 class Idx:
262 def __float__(self):
263 return 0.0
264
265 def __index__(self):
266 raise TypeError("not a byte!")
267
268 haystack = b"abc"
269 needle = Idx()
270 with self.assertRaises(TypeError) as context:
271 haystack.count(needle)
272 self.assertEqual(str(context.exception), "not a byte!")
273
274 def test_count_with_empty_sub_returns_length_minus_adjusted_start_plus_one(self):
275 haystack = b"abcde"
276 needle = bytearray()
277 self.assertEqual(haystack.count(needle, -3), 4)
278
279 def test_count_with_missing_returns_zero(self):
280 haystack = b"abc"
281 needle = b"d"
282 self.assertEqual(haystack.count(needle), 0)
283
284 def test_count_with_missing_stays_within_bounds(self):
285 haystack = b"abc"
286 needle = bytearray(b"c")
287 self.assertEqual(haystack.count(needle, None, 2), 0)
288
289 def test_count_with_large_start_returns_zero(self):
290 haystack = b"abc"
291 needle = bytearray(b"")
292 self.assertEqual(haystack.count(needle, 10), 0)
293
294 def test_count_with_negative_bounds_returns_count(self):
295 haystack = b"foobar"
296 needle = bytearray(b"o")
297 self.assertEqual(haystack.count(needle, -6, -1), 2)
298
299 def test_count_returns_non_overlapping_count(self):
300 haystack = b"abababab"
301 needle = bytearray(b"aba")
302 self.assertEqual(haystack.count(needle), 2)
303
304 def test_endswith_with_bytearray_self_raises_type_error(self):
305 self.assertRaisesRegex(
306 TypeError,
307 "'endswith' .* 'bytes' object.* a 'bytearray'",
308 bytes.endswith,
309 bytearray(),
310 b"",
311 )
312
313 def test_endswith_with_list_other_raises_type_error(self):
314 with self.assertRaises(TypeError) as context:
315 b"".endswith([])
316 self.assertEqual(
317 str(context.exception),
318 "endswith first arg must be bytes or a tuple of bytes, not list",
319 )
320
321 def test_endswith_with_tuple_other_checks_each(self):
322 haystack = b"123"
323 needle1 = (b"12", b"13", b"23", b"d")
324 needle2 = (b"2", b"asd", b"122222")
325 self.assertTrue(haystack.endswith(needle1))
326 self.assertFalse(haystack.endswith(needle2))
327
328 def test_endswith_with_end_searches_from_end(self):
329 haystack = b"12345"
330 needle1 = bytearray(b"1")
331 needle4 = b"34"
332 self.assertFalse(haystack.endswith(needle1, 0))
333 self.assertFalse(haystack.endswith(needle4, 1))
334 self.assertTrue(haystack.endswith(needle1, 0, 1))
335 self.assertTrue(haystack.endswith(needle4, 1, 4))
336
337 def test_endswith_with_empty_returns_true_for_valid_bounds(self):
338 haystack = b"12345"
339 self.assertTrue(haystack.endswith(bytearray()))
340 self.assertTrue(haystack.endswith(b"", 5))
341 self.assertTrue(haystack.endswith(bytearray(), -9, 1))
342
343 def test_endswith_with_empty_returns_false_for_invalid_bounds(self):
344 haystack = b"12345"
345 self.assertFalse(haystack.endswith(b"", 3, 2))
346 self.assertFalse(haystack.endswith(bytearray(), 6))
347
348 def test_find_with_bytearray_self_raises_type_error(self):
349 with self.assertRaises(TypeError):
350 bytes.find(bytearray(), b"")
351
352 def test_find_with_empty_sub_returns_start(self):
353 haystack = b"abc"
354 needle = bytearray()
355 self.assertEqual(haystack.find(needle, 1), 1)
356
357 def test_find_with_missing_returns_negative(self):
358 haystack = b"abc"
359 needle = b"d"
360 self.assertEqual(haystack.find(needle), -1)
361
362 def test_find_with_missing_stays_within_bounds(self):
363 haystack = b"abc"
364 needle = bytearray(b"c")
365 self.assertEqual(haystack.find(needle, None, 2), -1)
366
367 def test_find_with_large_start_returns_negative(self):
368 haystack = b"abc"
369 needle = bytearray(b"c")
370 self.assertEqual(haystack.find(needle, 10), -1)
371
372 def test_find_with_negative_bounds_returns_index(self):
373 haystack = b"foobar"
374 needle = bytearray(b"o")
375 self.assertEqual(haystack.find(needle, -6, -1), 1)
376
377 def test_find_with_multiple_matches_returns_first_index_in_range(self):
378 haystack = b"abbabbabba"
379 needle = bytearray(b"abb")
380 self.assertEqual(haystack.find(needle, 1), 3)
381
382 def test_find_with_nonbyte_int_raises_value_error(self):
383 haystack = b""
384 needle = 266
385 with self.assertRaises(ValueError):
386 haystack.find(needle)
387
388 def test_find_with_int_returns_index(self):
389 haystack = b"123"
390 self.assertEqual(haystack.find(ord("1")), 0)
391 self.assertEqual(haystack.find(ord("2")), 1)
392 self.assertEqual(haystack.find(ord("3")), 2)
393
394 def test_find_with_string_raises_type_error(self):
395 haystack = b""
396 needle = "133"
397 with self.assertRaises(TypeError):
398 haystack.find(needle)
399
400 def test_find_with_non_number_index(self):
401 class Idx:
402 def __index__(self):
403 return ord("a")
404
405 haystack = b"abc"
406 needle = Idx()
407 self.assertEqual(haystack.find(needle), 0)
408
409 def test_find_with_dunder_int_calls_dunder_index(self):
410 class Desc:
411 def __get__(self, obj, type):
412 raise NotImplementedError("called descriptor")
413
414 class Idx:
415 def __index__(self):
416 return ord("a")
417
418 __int__ = Desc()
419
420 haystack = b"abc"
421 needle = Idx()
422 self.assertEqual(haystack.find(needle), 0)
423
424 def test_find_with_dunder_float_calls_dunder_index(self):
425 class Desc:
426 def __get__(self, obj, type):
427 raise NotImplementedError("called descriptor")
428
429 class Idx:
430 __float__ = Desc()
431
432 def __index__(self):
433 return ord("a")
434
435 haystack = b"abc"
436 needle = Idx()
437 self.assertEqual(haystack.find(needle), 0)
438
439 def test_find_with_index_overflow_raises_overflow_error(self):
440 class Idx:
441 def __float__(self):
442 return 0.0
443
444 def __index__(self):
445 raise OverflowError("not a byte!")
446
447 haystack = b"abc"
448 needle = Idx()
449 with self.assertRaises(OverflowError) as context:
450 haystack.find(needle)
451 self.assertEqual(str(context.exception), "not a byte!")
452
453 def test_find_with_index_error_raises_type_error(self):
454 class Idx:
455 def __float__(self):
456 return 0.0
457
458 def __index__(self):
459 raise TypeError("not a byte!")
460
461 haystack = b"abc"
462 needle = Idx()
463 with self.assertRaises(TypeError) as context:
464 haystack.find(needle)
465 self.assertEqual(str(context.exception), "not a byte!")
466
467 def test_fromhex_returns_bytes_instance(self):
468 self.assertEqual(bytes.fromhex("1234 ab AB"), b"\x124\xab\xab")
469
470 def test_fromhex_ignores_spaces(self):
471 self.assertEqual(bytes.fromhex("ab cc deff"), b"\xab\xcc\xde\xff")
472
473 def test_fromhex_with_trailing_spaces_returns_bytes(self):
474 self.assertEqual(bytes.fromhex("ABCD "), b"\xab\xcd")
475
476 def test_fromhex_with_number_raises_type_error(self):
477 with self.assertRaises(TypeError):
478 bytes.fromhex(1234)
479
480 def test_fromhex_with_bad_byte_groupings_raises_value_error(self):
481 with self.assertRaises(ValueError) as context:
482 bytes.fromhex("abc d")
483 self.assertEqual(
484 str(context.exception),
485 "non-hexadecimal number found in fromhex() arg at position 3",
486 )
487
488 def test_fromhex_with_dangling_nibble_raises_value_error(self):
489 with self.assertRaises(ValueError) as context:
490 bytes.fromhex("AB AB C")
491 self.assertEqual(
492 str(context.exception),
493 "non-hexadecimal number found in fromhex() arg at position 7",
494 )
495
496 def test_fromhex_with_non_ascii_raises_value_error(self):
497 with self.assertRaises(ValueError) as context:
498 bytes.fromhex("édcb")
499 self.assertEqual(
500 str(context.exception),
501 "non-hexadecimal number found in fromhex() arg at position 0",
502 )
503
504 def test_fromhex_with_non_hex_raises_value_error(self):
505 with self.assertRaises(ValueError) as context:
506 bytes.fromhex("0123abcdefgh")
507 self.assertEqual(
508 str(context.exception),
509 "non-hexadecimal number found in fromhex() arg at position 10",
510 )
511
512 def test_fromhex_with_bytes_subclass_returns_subclass_instance(self):
513 class C(bytes):
514 __init__ = Mock(name="__init__", return_value=None)
515
516 c = C.fromhex("1111")
517 self.assertIs(c.__class__, C)
518 c.__init__.assert_called_once()
519 self.assertEqual(c, b"\x11\x11")
520
521 def test_hex_with_non_bytes_raises_type_error(self):
522 self.assertRaisesRegex(
523 TypeError,
524 "'hex' .* 'bytes' object.* a 'str'",
525 bytes.hex,
526 "not a bytes",
527 )
528
529 def test_index_with_bytearray_self_raises_type_error(self):
530 with self.assertRaises(TypeError):
531 bytes.index(bytearray(), b"")
532
533 def test_index_with_subsequence_returns_first_in_range(self):
534 haystack = b"-a---a-aa"
535 needle = ord("a")
536 self.assertEqual(haystack.index(needle, 3), 5)
537
538 def test_index_with_missing_raises_value_error(self):
539 haystack = b"abc"
540 needle = b"d"
541 with self.assertRaises(ValueError) as context:
542 haystack.index(needle)
543 self.assertEqual(str(context.exception), "subsection not found")
544
545 def test_index_outside_of_bounds_raises_value_error(self):
546 haystack = b"abc"
547 needle = bytearray(b"c")
548 with self.assertRaises(ValueError) as context:
549 haystack.index(needle, 0, 2)
550 self.assertEqual(str(context.exception), "subsection not found")
551
552 def test_iteration_returns_ints(self):
553 expected = [97, 98, 99, 100]
554 index = 0
555 for val in b"abcd":
556 self.assertEqual(val, expected[index])
557 index += 1
558 self.assertEqual(index, len(expected))
559
560 def test_join_with_non_bytes_self_raises_type_error(self):
561 self.assertRaisesRegex(
562 TypeError,
563 "'join' .* 'bytes' object.* a 'int'",
564 bytes.join,
565 1,
566 [],
567 )
568
569 def test_join_with_bytes_returns_bytes(self):
570 result = b",".join((b"hello", b"world"))
571 self.assertIs(type(result), bytes)
572 self.assertEqual(result, b"hello,world")
573
574 def test_join_with_bytearray_returns_bytes(self):
575 result = b",".join((bytearray(b"hello"), bytearray(b"world")))
576 self.assertIs(type(result), bytes)
577 self.assertEqual(result, b"hello,world")
578
579 def test_join_with_memoryview_returns_bytes(self):
580 result = b",".join((memoryview(b"hello"), memoryview(b"world")))
581 self.assertIs(type(result), bytes)
582 self.assertEqual(result, b"hello,world")
583
584 def test_lower_with_non_bytes_raises_type_error(self):
585 with self.assertRaises(TypeError):
586 bytes.lower("not a bytes")
587
588 def test_lower_empty_self_returns_self(self):
589 src = b""
590 dst = src.lower()
591 self.assertIs(src, dst)
592
593 def test_lower_all_lower_returns_new_bytes(self):
594 src = b"abcdefghijklmnopqrstuvwxyz"
595 dst = src.lower()
596 self.assertIsNot(src, dst)
597 self.assertIsInstance(dst, bytes)
598 self.assertEqual(src, dst)
599
600 def test_lower_all_lower_and_non_alphanumeric_returns_self(self):
601 src = b"abcdefghijklmnopqrstuvwxyz1234567890"
602 dst = src.lower()
603 self.assertIsNot(src, dst)
604 self.assertIsInstance(dst, bytes)
605 self.assertEqual(src, dst)
606
607 def test_lower_all_uppercase_returns_all_lowercase(self):
608 src = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
609 dst = src.lower()
610 self.assertIsInstance(dst, bytes)
611 self.assertEqual(dst, b"abcdefghijklmnopqrstuvwxyz")
612
613 def test_lower_mixed_case_returns_all_lowercase(self):
614 src = b"aBcDeFgHiJkLmNoPqRsTuVwXyZ"
615 dst = src.lower()
616 self.assertIsInstance(dst, bytes)
617 self.assertEqual(dst, b"abcdefghijklmnopqrstuvwxyz")
618
619 def test_lower_mixed_case_returns_all_lowercase(self):
620 src = b"a1!B2@c3#D4$e5%F6^g7&H8*i9(J0)"
621 dst = src.lower()
622 self.assertIsInstance(dst, bytes)
623 self.assertEqual(dst, b"a1!b2@c3#d4$e5%f6^g7&h8*i9(j0)")
624
625 def test_ljust_without_growth_returns_original_bytes(self):
626 foo = b"foo"
627 self.assertIs(foo.ljust(-1), foo)
628 self.assertIs(foo.ljust(0), foo)
629 self.assertIs(foo.ljust(1), foo)
630 self.assertIs(foo.ljust(2), foo)
631 self.assertIs(foo.ljust(3), foo)
632
633 def test_ljust_pads_end_of_bytes(self):
634 self.assertEqual(b"abc".ljust(4), b"abc ")
635 self.assertEqual(b"abc".ljust(7), b"abc ")
636
637 def test_ljust_with_custom_fillchar_returns_bytes(self):
638 self.assertEqual(b"ba".ljust(7, b"@"), b"ba@@@@@")
639
640 def test_ljust_with_non_bytes_fillchar_raises_type_error(self):
641 with self.assertRaises(TypeError) as context:
642 b"".ljust(2, ord(" "))
643 self.assertEqual(
644 str(context.exception),
645 "ljust() argument 2 must be a byte string of length 1, not int",
646 )
647
648 def test_ljust_with_wrong_length_fillchar_raises_type_error(self):
649 with self.assertRaises(TypeError) as context:
650 b"".ljust(2, b",,")
651 self.assertEqual(
652 str(context.exception),
653 "ljust() argument 2 must be a byte string of length 1, not bytes",
654 )
655
656 def test_ljust_with_swapped_width_fillchar_raises_type_error(self):
657 with self.assertRaises(TypeError) as context:
658 b"".ljust(b",", 2)
659 self.assertEqual(
660 str(context.exception), "'bytes' object cannot be interpreted as an integer"
661 )
662
663 def test_lstrip_with_non_byteslike_raises_type_error(self):
664 with self.assertRaises(TypeError) as context:
665 b"".lstrip("")
666 self.assertEqual(
667 str(context.exception), "a bytes-like object is required, not 'str'"
668 )
669
670 def test_lstrip_with_none_or_default_strips_ascii_space(self):
671 self.assertEqual(b"".lstrip(None), b"")
672 self.assertEqual(b" ".lstrip(None), b"")
673 self.assertEqual(b" hi ".lstrip(), b"hi ")
674
675 def test_lstrip_with_byteslike_strips_bytes(self):
676 self.assertEqual(b"".lstrip(b"123"), b"")
677 self.assertEqual(b"1aaa1".lstrip(bytearray()), b"1aaa1")
678 self.assertEqual(b"1 aaa1".lstrip(bytearray(b" 1")), b"aaa1")
679 self.assertEqual(b"hello".lstrip(b"eho"), b"llo")
680
681 def test_replace(self):
682 test = b"mississippi"
683 self.assertEqual(test.replace(b"i", b"a"), b"massassappa")
684 self.assertEqual(test.replace(b"i", b"vv"), b"mvvssvvssvvppvv")
685 self.assertEqual(test.replace(b"ss", b"x"), b"mixixippi")
686 self.assertEqual(test.replace(bytearray(b"ss"), bytearray(b"x")), b"mixixippi")
687 self.assertEqual(test.replace(b"i", bytearray()), b"msssspp")
688 self.assertEqual(test.replace(bytearray(b"i"), b""), b"msssspp")
689
690 def test_replace_with_count(self):
691 test = b"mississippi"
692 self.assertEqual(test.replace(b"i", b"a", 0), b"mississippi")
693 self.assertEqual(test.replace(b"i", b"a", 2), b"massassippi")
694
695 def test_replace_int_error(self):
696 with self.assertRaises(TypeError) as context:
697 b"a b".replace(b"r", 4)
698 self.assertEqual(
699 str(context.exception), "a bytes-like object is required, not 'int'"
700 )
701
702 def test_replace_str_error(self):
703 with self.assertRaises(TypeError) as context:
704 b"a b".replace(b"r", "s")
705 self.assertEqual(
706 str(context.exception), "a bytes-like object is required, not 'str'"
707 )
708
709 def test_replace_float_count_error(self):
710 with self.assertRaises(TypeError) as context:
711 b"a b".replace(b"r", b"b", 4.2)
712 self.assertEqual(str(context.exception), "integer argument expected, got float")
713
714 def test_replace_str_count_error(self):
715 test = b"a b"
716 self.assertRaises(TypeError, test.replace, "r", b"", "hello")
717
718 def test_rfind_with_bytearray_self_raises_type_error(self):
719 self.assertRaisesRegex(
720 TypeError,
721 "'rfind' .* 'bytes' object.* a 'bytearray'",
722 bytes.rfind,
723 bytearray(),
724 b"",
725 )
726
727 def test_rfind_with_empty_sub_returns_end(self):
728 haystack = b"abc"
729 needle = bytearray()
730 self.assertEqual(haystack.rfind(needle), 3)
731
732 def test_rfind_with_missing_returns_negative(self):
733 haystack = b"abc"
734 needle = b"d"
735 self.assertEqual(haystack.rfind(needle), -1)
736
737 def test_rfind_with_missing_stays_within_bounds(self):
738 haystack = b"abc"
739 needle = bytearray(b"c")
740 self.assertEqual(haystack.rfind(needle, None, 2), -1)
741
742 def test_rfind_with_large_start_returns_negative(self):
743 haystack = b"abc"
744 needle = bytearray(b"c")
745 self.assertEqual(haystack.rfind(needle, 10), -1)
746
747 def test_rfind_with_negative_bounds_returns_index(self):
748 haystack = b"foobar"
749 needle = bytearray(b"o")
750 self.assertEqual(haystack.rfind(needle, -6, -1), 2)
751
752 def test_rfind_with_multiple_matches_returns_last_index_in_range(self):
753 haystack = b"abbabbabba"
754 needle = bytearray(b"abb")
755 self.assertEqual(haystack.rfind(needle), 6)
756
757 def test_rfind_with_nonbyte_int_raises_value_error(self):
758 haystack = b""
759 needle = 266
760 with self.assertRaises(ValueError) as context:
761 haystack.rfind(needle)
762 self.assertEqual(str(context.exception), "byte must be in range(0, 256)")
763
764 def test_rfind_with_string_raises_type_error(self):
765 haystack = b""
766 needle = "133"
767 with self.assertRaises(TypeError) as context:
768 haystack.rfind(needle)
769 self.assertEqual(
770 str(context.exception),
771 "argument should be integer or bytes-like object, not 'str'",
772 )
773
774 def test_rfind_with_non_number_index_calls_dunder_index(self):
775 class Idx:
776 def __index__(self):
777 return ord("a")
778
779 haystack = b"abc"
780 needle = Idx()
781 self.assertEqual(haystack.rfind(needle), 0)
782
783 def test_rfind_with_dunder_int_calls_dunder_index(self):
784 class Idx:
785 def __int__(self):
786 raise NotImplementedError("called __int__")
787
788 def __index__(self):
789 return ord("a")
790
791 haystack = b"abc"
792 needle = Idx()
793 self.assertEqual(haystack.rfind(needle), 0)
794
795 def test_rfind_with_dunder_float_calls_dunder_index(self):
796 class Idx:
797 def __float__(self):
798 raise NotImplementedError("called __float__")
799
800 def __index__(self):
801 return ord("a")
802
803 haystack = b"abc"
804 needle = Idx()
805 self.assertEqual(haystack.rfind(needle), 0)
806
807 def test_rindex_with_bytearray_self_raises_type_error(self):
808 with self.assertRaises(TypeError):
809 bytes.rindex(bytearray(), b"")
810
811 def test_rindex_with_subsequence_returns_last_in_range(self):
812 haystack = b"-a-aa----a--"
813 needle = ord("a")
814 self.assertEqual(haystack.rindex(needle, 2, 8), 4)
815
816 def test_rindex_with_missing_raises_value_error(self):
817 haystack = b"abc"
818 needle = b"d"
819 with self.assertRaises(ValueError) as context:
820 haystack.rindex(needle)
821 self.assertEqual(str(context.exception), "subsection not found")
822
823 def test_rindex_outside_of_bounds_raises_value_error(self):
824 haystack = b"abc"
825 needle = bytearray(b"c")
826 with self.assertRaises(ValueError) as context:
827 haystack.rindex(needle, 0, 2)
828 self.assertEqual(str(context.exception), "subsection not found")
829
830 def test_rjust_without_growth_returns_original_bytes(self):
831 foo = b"foo"
832 self.assertIs(foo.rjust(-1), foo)
833 self.assertIs(foo.rjust(0), foo)
834 self.assertIs(foo.rjust(1), foo)
835 self.assertIs(foo.rjust(2), foo)
836 self.assertIs(foo.rjust(3), foo)
837
838 def test_rjust_pads_beginning_of_bytes(self):
839 self.assertEqual(b"abc".rjust(4), b" abc")
840 self.assertEqual(b"abc".rjust(7), b" abc")
841
842 def test_rjust_with_custom_fillchar_returns_bytes(self):
843 self.assertEqual(b"ba".rjust(7, b"@"), b"@@@@@ba")
844
845 def test_rjust_with_non_bytes_fillchar_raises_type_error(self):
846 with self.assertRaises(TypeError) as context:
847 b"".rjust(2, ord(" "))
848 self.assertEqual(
849 str(context.exception),
850 "rjust() argument 2 must be a byte string of length 1, not int",
851 )
852
853 def test_rjust_with_wrong_length_fillchar_raises_type_error(self):
854 with self.assertRaises(TypeError) as context:
855 b"".rjust(2, b",,")
856 self.assertEqual(
857 str(context.exception),
858 "rjust() argument 2 must be a byte string of length 1, not bytes",
859 )
860
861 def test_rstrip_with_non_byteslike_raises_type_error(self):
862 with self.assertRaises(TypeError) as context:
863 b"".rstrip("")
864 self.assertEqual(
865 str(context.exception), "a bytes-like object is required, not 'str'"
866 )
867
868 def test_rstrip_with_none_or_default_strips_ascii_space(self):
869 self.assertEqual(b"".rstrip(None), b"")
870 self.assertEqual(b" ".rstrip(None), b"")
871 self.assertEqual(b" hi ".rstrip(), b" hi")
872
873 def test_rstrip_with_byteslike_strips_bytes(self):
874 self.assertEqual(b"".rstrip(b"123"), b"")
875 self.assertEqual(b"1aaa1".rstrip(bytearray()), b"1aaa1")
876 self.assertEqual(b"1aa a1".rstrip(bytearray(b" 1")), b"1aa a")
877 self.assertEqual(b"hello".rstrip(b"lo"), b"he")
878
879 def test_split_with_non_bytes_self_raises_type_error(self):
880 self.assertRaisesRegex(
881 TypeError,
882 "'split' .* 'bytes' object.* a 'str'",
883 bytes.split,
884 "foo bar",
885 )
886
887 def test_split_with_non_byteslike_sep_raises_type_error(self):
888 b = b"foo bar"
889 sep = ""
890 with self.assertRaises(TypeError) as context:
891 b.split(sep)
892 self.assertEqual(
893 str(context.exception), "a bytes-like object is required, not 'str'"
894 )
895
896 def test_split_with_non_index_maxsplit_raises_type_error(self):
897 b = b"foo bar"
898 with self.assertRaises(TypeError) as context:
899 b.split(maxsplit=None)
900 self.assertEqual(
901 str(context.exception),
902 "'NoneType' object cannot be interpreted as an integer",
903 )
904
905 def test_split_with_large_int_raises_overflow_error(self):
906 b = b"foo bar"
907 with self.assertRaises(OverflowError) as context:
908 b.split(maxsplit=2 ** 64)
909 self.assertEqual(
910 str(context.exception), "Python int too large to convert to C ssize_t"
911 )
912
913 def test_split_with_empty_sep_raises_value_error(self):
914 b = b"foo bar"
915 with self.assertRaises(ValueError) as context:
916 b.split(bytearray())
917 self.assertEqual(str(context.exception), "empty separator")
918
919 def test_split_empty_bytes_without_sep_returns_empty_list(self):
920 b = b""
921 self.assertEqual(b.split(), [])
922
923 def test_split_empty_bytes_with_sep_returns_list_of_empty_bytes(self):
924 b = b""
925 self.assertEqual(b.split(b"a"), [b""])
926
927 def test_split_without_sep_splits_whitespace(self):
928 b = b"foo bar"
929 self.assertEqual(b.split(), [b"foo", b"bar"])
930 b = b" foo bar \t \nbaz\r\n "
931 self.assertEqual(b.split(), [b"foo", b"bar", b"baz"])
932
933 def test_split_with_none_sep_splits_whitespace_maxsplit_times(self):
934 b = b" foo bar \t \nbaz\r\n "
935 self.assertEqual(b.split(None, 2), [b"foo", b"bar", b"baz\r\n "])
936
937 def test_split_by_byteslike_returns_list(self):
938 b = b"foo bar baz"
939 self.assertEqual(b.split(b" "), [b"foo", b"bar", b"baz"])
940 self.assertEqual(b.split(bytearray(b"o")), [b"f", b"", b" bar baz"])
941 self.assertEqual(b.split(b"ba"), [b"foo ", b"r ", b"z"])
942 self.assertEqual(b.split(b"not found"), [b])
943
944 def test_splitlines_with_non_bytes_raises_type_error(self):
945 with self.assertRaises(TypeError):
946 bytes.splitlines(None)
947
948 def test_splitlines_with_float_keepends_raises_type_error(self):
949 with self.assertRaises(TypeError):
950 bytes.splitlines(b"hello", 0.4)
951
952 def test_splitlines_with_string_keepends_raises_type_error(self):
953 with self.assertRaises(TypeError):
954 bytes.splitlines(b"hello", "1")
955
956 def test_splitlines_returns_list(self):
957 self.assertEqual(bytes.splitlines(b"", False), [])
958 self.assertEqual(bytes.splitlines(b"a", 0), [b"a"])
959 self.assertEqual(bytes.splitlines(b"a\nb\rc"), [b"a", b"b", b"c"])
960 self.assertEqual(bytes.splitlines(b"a\r\nb\r\n"), [b"a", b"b"])
961 self.assertEqual(bytes.splitlines(b"\n\r\n\r"), [b"", b"", b""])
962 self.assertEqual(bytes.splitlines(b"a\x0Bb"), [b"a\x0Bb"])
963
964 def test_splitlines_with_keepend_returns_list(self):
965 self.assertEqual(bytes.splitlines(b"", True), [])
966 self.assertEqual(bytes.splitlines(b"a", 1), [b"a"])
967 self.assertEqual(bytes.splitlines(b"a\nb\rc", 1), [b"a\n", b"b\r", b"c"])
968 self.assertEqual(bytes.splitlines(b"a\r\nb\r\n", 1), [b"a\r\n", b"b\r\n"])
969 self.assertEqual(bytes.splitlines(b"\n\r\n\r", 1), [b"\n", b"\r\n", b"\r"])
970
971 def test_startswith_with_bytearray_self_raises_type_error(self):
972 self.assertRaisesRegex(
973 TypeError,
974 "'startswith' .* 'bytes' object.* a 'bytearray'",
975 bytes.startswith,
976 bytearray(),
977 b"",
978 )
979
980 def test_startswith_with_list_other_raises_type_error(self):
981 with self.assertRaises(TypeError) as context:
982 b"".startswith([])
983 self.assertEqual(
984 str(context.exception),
985 "startswith first arg must be bytes or a tuple of bytes, not list",
986 )
987
988 def test_startswith_with_tuple_other_checks_each(self):
989 haystack = b"123"
990 needle1 = (b"13", b"23", b"12", b"d")
991 needle2 = (b"2", b"asd", b"122222")
992 self.assertTrue(haystack.startswith(needle1))
993 self.assertFalse(haystack.startswith(needle2))
994
995 def test_startswith_with_start_searches_from_start(self):
996 haystack = b"12345"
997 needle1 = bytearray(b"1")
998 needle4 = b"34"
999 self.assertFalse(haystack.startswith(needle1, 1))
1000 self.assertFalse(haystack.startswith(needle4, 0))
1001 self.assertTrue(haystack.startswith(needle1, 0))
1002 self.assertTrue(haystack.startswith(needle4, 2))
1003
1004 def test_startswith_with_empty_returns_true_for_valid_bounds(self):
1005 haystack = b"12345"
1006 self.assertTrue(haystack.startswith(bytearray()))
1007 self.assertTrue(haystack.startswith(b"", 5))
1008 self.assertTrue(haystack.startswith(bytearray(), -9, 1))
1009
1010 def test_startswith_with_empty_returns_false_for_invalid_bounds(self):
1011 haystack = b"12345"
1012 self.assertFalse(haystack.startswith(b"", 3, 2))
1013 self.assertFalse(haystack.startswith(bytearray(), 6))
1014
1015 def test_strip_with_non_byteslike_raises_type_error(self):
1016 with self.assertRaises(TypeError) as context:
1017 b"".strip("")
1018 self.assertEqual(
1019 str(context.exception), "a bytes-like object is required, not 'str'"
1020 )
1021
1022 def test_strip_with_none_or_default_strips_ascii_space(self):
1023 self.assertEqual(b"".strip(None), b"")
1024 self.assertEqual(b" ".strip(None), b"")
1025 self.assertEqual(b" hi ".strip(), b"hi")
1026
1027 def test_strip_with_byteslike_strips_bytes(self):
1028 self.assertEqual(b"".strip(b"123"), b"")
1029 self.assertEqual(b"1aaa1".strip(bytearray()), b"1aaa1")
1030 self.assertEqual(b"1 aaa1".strip(bytearray(b" 1")), b"aaa")
1031 self.assertEqual(b"hello".strip(b"ho"), b"ell")
1032
1033 def test_translate_with_non_bytes_raises_type_error(self):
1034 self.assertRaisesRegex(
1035 TypeError,
1036 "'translate' .* 'bytes' object.* a 'str'",
1037 bytes.translate,
1038 "not a bytes",
1039 bytes(256),
1040 )
1041
1042 def test_upper_with_non_bytes_raises_type_error(self):
1043 with self.assertRaises(TypeError):
1044 bytes.upper("not a bytes")
1045
1046 def test_upper_empty_self_returns_self(self):
1047 src = b""
1048 dst = src.upper()
1049 self.assertIs(src, dst)
1050
1051 def test_upper_all_upper_returns_new_bytes(self):
1052 src = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1053 dst = src.upper()
1054 self.assertIsInstance(dst, bytes)
1055 self.assertIsNot(src, dst)
1056 self.assertEqual(src, dst)
1057
1058 def test_upper_all_upper_and_non_alphanumeric_returns_new_bytes(self):
1059 src = b"ABCDEFGHIJ1234567890!@#$%^&*()"
1060 dst = src.upper()
1061 self.assertIsInstance(dst, bytes)
1062 self.assertIsNot(src, dst)
1063 self.assertEqual(src, dst)
1064
1065 def test_upper_all_lower_returns_all_uppercase(self):
1066 src = b"abcdefghijklmnopqrstuvwxyz"
1067 dst = src.upper()
1068 self.assertIsInstance(dst, bytes)
1069 self.assertEqual(dst, b"ABCDEFGHIJKLMNOPQRSTUVWXYZ")
1070
1071 def test_upper_mixed_case_returns_all_uppercase(self):
1072 src = b"aBcDeFgHiJkLmNoPqRsTuVwXyZ"
1073 dst = src.upper()
1074 self.assertIsInstance(dst, bytes)
1075 self.assertEqual(dst, b"ABCDEFGHIJKLMNOPQRSTUVWXYZ")
1076
1077 def test_upper_mixed_case_returns_all_uppercase(self):
1078 src = b"a1!B2@c3#D4$e5%F6^g7&H8*i9(J0)"
1079 dst = src.upper()
1080 self.assertIsInstance(dst, bytes)
1081 self.assertEqual(dst, b"A1!B2@C3#D4$E5%F6^G7&H8*I9(J0)")
1082
1083
1084class BytesModTests(unittest.TestCase):
1085 def test_empty_format_returns_empty_bytes(self):
1086 self.assertEqual(bytes.__mod__(b"", ()), b"")
1087
1088 def test_simple_string_returns_bytes(self):
1089 self.assertEqual(bytes.__mod__(b"foo bar (}", ()), b"foo bar (}")
1090
1091 def test_with_non_tuple_args_returns_bytes(self):
1092 self.assertEqual(bytes.__mod__(b"%s", b"foo"), b"foo")
1093 self.assertEqual(bytes.__mod__(b"%d", 42), b"42")
1094
1095 def test_with_named_args_returns_bytes(self):
1096 self.assertEqual(
1097 bytes.__mod__(b"%(foo)s %(bar)d", {b"foo": b"ho", b"bar": 42}), b"ho 42"
1098 )
1099 self.assertEqual(bytes.__mod__(b"%()x", {b"": 123}), b"7b")
1100 self.assertEqual(bytes.__mod__(b")%(((()) ()))d(", {b"((()) ())": 99}), b")99(")
1101 self.assertEqual(bytes.__mod__(b"%(%s)d", {b"%s": -5}), b"-5")
1102
1103 def test_with_custom_mapping_returns_bytes(self):
1104 class C:
1105 def __getitem__(self, key):
1106 return b"getitem called with " + key
1107
1108 self.assertEqual(bytes.__mod__(b"%(foo)s", C()), b"getitem called with foo")
1109
1110 def test_without_mapping_raises_type_error(self):
1111 with self.assertRaises(TypeError) as context:
1112 bytes.__mod__(b"%(foo)s", None)
1113 self.assertEqual(str(context.exception), "format requires a mapping")
1114 with self.assertRaises(TypeError) as context:
1115 bytes.__mod__(b"%(foo)s", "foobar")
1116 self.assertEqual(str(context.exception), "format requires a mapping")
1117 with self.assertRaises(TypeError) as context:
1118 bytes.__mod__(b"%(foo)s", ("foobar",))
1119 self.assertEqual(str(context.exception), "format requires a mapping")
1120
1121 def test_with_mapping_does_not_raise_type_error(self):
1122 # The following must not raise
1123 # "not all arguments converted during string formatting".
1124 self.assertEqual(bytes.__mod__(b"foo", {"bar": 42}), b"foo")
1125
1126 def test_positional_after_named_arg_raises_type_error(self):
1127 with self.assertRaises(TypeError) as context:
1128 bytes.__mod__(b"%(foo)s %s", {b"foo": b"bar"})
1129 self.assertEqual(
1130 str(context.exception), "not enough arguments for format string"
1131 )
1132
1133 def test_c_format_raises_type_error(self):
1134 with self.assertRaises(TypeError) as context:
1135 bytes.__mod__(b"%c", ("x",))
1136 self.assertEqual(
1137 str(context.exception),
1138 "%c requires an integer in range(256) or a single byte",
1139 )
1140 self.assertEqual(bytes.__mod__(b"%c", ("\U0001f44d",)), b"\U0001f44d")
1141 self.assertEqual(bytes.__mod__(b"%c", (76,)), b"L")
1142 self.assertEqual(bytes.__mod__(b"%c", (0x1F40D,)), b"\U0001f40d")
1143
1144 def test_c_format_with_non_int_returns_bytes(self):
1145 class C:
1146 def __index__(self):
1147 return 42
1148
1149 self.assertEqual(bytes.__mod__(b"%c", (C(),)), b"*")
1150
1151 def test_c_format_raises_overflow_error(self):
1152 import sys
1153
1154 with self.assertRaises(OverflowError) as context:
1155 bytes.__mod__(b"%c", (sys.maxunicode + 1,))
1156
1157 self.assertEqual(str(context.exception), "%c arg not in range(256)")
1158 with self.assertRaises(OverflowError) as context:
1159 bytes.__mod__(b"%c", (-1,))
1160 self.assertEqual(str(context.exception), "%c arg not in range(256)")
1161
1162 def test_c_format_raises_type_error(self):
1163 with self.assertRaises(TypeError) as context:
1164 bytes.__mod__(b"%c", (None,))
1165 self.assertEqual(
1166 str(context.exception),
1167 "%c requires an integer in range(256) or a single byte",
1168 )
1169 with self.assertRaises(TypeError) as context:
1170 bytes.__mod__(b"%c", ("ab",))
1171 self.assertEqual(
1172 str(context.exception),
1173 "%c requires an integer in range(256) or a single byte",
1174 )
1175 with self.assertRaises(OverflowError) as context:
1176 bytes.__mod__(b"%c", (123456789012345678901234567890,))
1177 self.assertEqual(str(context.exception), "%c arg not in range(256)")
1178
1179 def test_s_format_returns_bytes(self):
1180 self.assertEqual(bytes.__mod__(b"%s", (b"foo",)), b"foo")
1181
1182 class C:
1183 def __bytes__(self):
1184 return b"bytes called"
1185
1186 r = bytes.__mod__(b"%s", (C(),))
1187 self.assertEqual(r, b"bytes called")
1188
1189 def test_s_format_propagates_errors(self):
1190 class C:
1191 def __bytes__(self):
1192 raise UserWarning()
1193
1194 with self.assertRaises(UserWarning):
1195 bytes.__mod__(b"%s", (C(),))
1196
1197 def test_r_format_returns_bytes(self):
1198 self.assertEqual(bytes.__mod__(b"%r", (42,)), b"42")
1199 self.assertEqual(bytes.__mod__(b"%r", ("foo",)), b"'foo'")
1200 self.assertEqual(
1201 bytes.__mod__(b"%r", ({"foo": "\U0001d4eb\U0001d4ea\U0001d4fb"},)),
1202 b"{'foo': '\U0001d4eb\U0001d4ea\U0001d4fb'}",
1203 )
1204
1205 class C:
1206 def __repr__(self):
1207 return "repr called"
1208
1209 __str__ = None
1210
1211 self.assertEqual(bytes.__mod__(b"%r", (C(),)), b"repr called")
1212
1213 def test_r_format_propagates_errors(self):
1214 class C:
1215 def __repr__(self):
1216 raise UserWarning()
1217
1218 with self.assertRaises(UserWarning):
1219 bytes.__mod__(b"%r", (C(),))
1220
1221 def test_a_format_returns_bytes(self):
1222 self.assertEqual(bytes.__mod__(b"%a", (42,)), b"42")
1223 self.assertEqual(bytes.__mod__(b"%a", ("foo",)), b"'foo'")
1224
1225 class C:
1226 def __repr__(self):
1227 return "repr \t\xc4~\ucafe\U0001f00d called"
1228
1229 __str__ = None
1230
1231 self.assertEqual(
1232 bytes.__mod__(b"%a", (C(),)), b"repr \t\\xc4~\\ucafe\\U0001f00d called"
1233 )
1234
1235 def test_a_format_propagates_errors(self):
1236 class C:
1237 def __repr__(self):
1238 raise UserWarning()
1239
1240 with self.assertRaises(UserWarning):
1241 bytes.__mod__(b"%a", (C(),))
1242
1243 def test_diu_format_returns_bytes(self):
1244 self.assertEqual(bytes.__mod__(b"%d", (0,)), b"0")
1245 self.assertEqual(bytes.__mod__(b"%d", (-1,)), b"-1")
1246 self.assertEqual(bytes.__mod__(b"%d", (42,)), b"42")
1247 self.assertEqual(bytes.__mod__(b"%i", (0,)), b"0")
1248 self.assertEqual(bytes.__mod__(b"%i", (-1,)), b"-1")
1249 self.assertEqual(bytes.__mod__(b"%i", (42,)), b"42")
1250 self.assertEqual(bytes.__mod__(b"%u", (0,)), b"0")
1251 self.assertEqual(bytes.__mod__(b"%u", (-1,)), b"-1")
1252 self.assertEqual(bytes.__mod__(b"%u", (42,)), b"42")
1253
1254 def test_diu_format_with_largeint_returns_bytes(self):
1255 self.assertEqual(
1256 bytes.__mod__(b"%d", (-123456789012345678901234567890,)),
1257 b"-123456789012345678901234567890",
1258 )
1259 self.assertEqual(
1260 bytes.__mod__(b"%i", (-123456789012345678901234567890,)),
1261 b"-123456789012345678901234567890",
1262 )
1263 self.assertEqual(
1264 bytes.__mod__(b"%u", (-123456789012345678901234567890,)),
1265 b"-123456789012345678901234567890",
1266 )
1267
1268 def test_diu_format_with_non_int_returns_bytes(self):
1269 class C:
1270 def __int__(self):
1271 return 42
1272
1273 def __index__(self):
1274 raise UserWarning()
1275
1276 self.assertEqual(bytes.__mod__(b"%d", (C(),)), b"42")
1277 self.assertEqual(bytes.__mod__(b"%i", (C(),)), b"42")
1278 self.assertEqual(bytes.__mod__(b"%u", (C(),)), b"42")
1279
1280 def test_diu_format_raises_typeerrors(self):
1281 with self.assertRaises(TypeError) as context:
1282 bytes.__mod__(b"%d", (None,))
1283 self.assertEqual(
1284 str(context.exception), "%d format: a number is required, not NoneType"
1285 )
1286 with self.assertRaises(TypeError) as context:
1287 bytes.__mod__(b"%i", (None,))
1288 self.assertEqual(
1289 str(context.exception), "%d format: a number is required, not NoneType"
1290 )
1291 with self.assertRaises(TypeError) as context:
1292 bytes.__mod__(b"%u", (None,))
1293 self.assertEqual(
1294 str(context.exception), "%u format: a number is required, not NoneType"
1295 )
1296
1297 def test_diu_format_propagates_errors(self):
1298 class C:
1299 def __int__(self):
1300 raise UserWarning()
1301
1302 with self.assertRaises(UserWarning):
1303 bytes.__mod__(b"%d", (C(),))
1304 with self.assertRaises(UserWarning):
1305 bytes.__mod__(b"%i", (C(),))
1306 with self.assertRaises(UserWarning):
1307 bytes.__mod__(b"%u", (C(),))
1308
1309 def test_diu_format_reraises_typerrors(self):
1310 class C:
1311 def __int__(self):
1312 raise TypeError("foobar")
1313
1314 with self.assertRaises(TypeError) as context:
1315 bytes.__mod__(b"%d", (C(),))
1316 self.assertEqual(
1317 str(context.exception), "%d format: a number is required, not C"
1318 )
1319 with self.assertRaises(TypeError) as context:
1320 bytes.__mod__(b"%i", (C(),))
1321 self.assertEqual(
1322 str(context.exception), "%d format: a number is required, not C"
1323 )
1324 with self.assertRaises(TypeError) as context:
1325 bytes.__mod__(b"%u", (C(),))
1326 self.assertEqual(
1327 str(context.exception), "%u format: a number is required, not C"
1328 )
1329
1330 def test_xX_format_returns_bytes(self):
1331 self.assertEqual(bytes.__mod__(b"%x", (0,)), b"0")
1332 self.assertEqual(bytes.__mod__(b"%x", (-123,)), b"-7b")
1333 self.assertEqual(bytes.__mod__(b"%x", (42,)), b"2a")
1334 self.assertEqual(bytes.__mod__(b"%X", (0,)), b"0")
1335 self.assertEqual(bytes.__mod__(b"%X", (-123,)), b"-7B")
1336 self.assertEqual(bytes.__mod__(b"%X", (42,)), b"2A")
1337
1338 def test_xX_format_with_largeint_returns_bytes(self):
1339 self.assertEqual(
1340 bytes.__mod__(b"%x", (-123456789012345678901234567890,)),
1341 b"-18ee90ff6c373e0ee4e3f0ad2",
1342 )
1343 self.assertEqual(
1344 bytes.__mod__(b"%X", (-123456789012345678901234567890,)),
1345 b"-18EE90FF6C373E0EE4E3F0AD2",
1346 )
1347
1348 def test_xX_format_with_non_int_returns_bytes(self):
1349 class C:
1350 def __float__(self):
1351 return 3.3
1352
1353 def __index__(self):
1354 return 77
1355
1356 self.assertEqual(bytes.__mod__(b"%x", (C(),)), b"4d")
1357 self.assertEqual(bytes.__mod__(b"%X", (C(),)), b"4D")
1358
1359 def test_xX_format_raises_typeerrors(self):
1360 with self.assertRaises(TypeError) as context:
1361 bytes.__mod__(b"%x", (None,))
1362 self.assertEqual(
1363 str(context.exception), "%x format: an integer is required, not NoneType"
1364 )
1365 with self.assertRaises(TypeError) as context:
1366 bytes.__mod__(b"%X", (None,))
1367 self.assertEqual(
1368 str(context.exception), "%X format: an integer is required, not NoneType"
1369 )
1370
1371 def test_xX_format_propagates_errors(self):
1372 class C:
1373 def __int__(self):
1374 return 42
1375
1376 def __index__(self):
1377 raise UserWarning()
1378
1379 with self.assertRaises(UserWarning):
1380 bytes.__mod__(b"%x", (C(),))
1381 with self.assertRaises(UserWarning):
1382 bytes.__mod__(b"%X", (C(),))
1383
1384 def test_xX_format_reraises_typerrors(self):
1385 class C:
1386 def __int__(self):
1387 return 42
1388
1389 def __index__(self):
1390 raise TypeError("foobar")
1391
1392 with self.assertRaises(TypeError) as context:
1393 bytes.__mod__(b"%x", (C(),))
1394 self.assertEqual(
1395 str(context.exception), "%x format: an integer is required, not C"
1396 )
1397 with self.assertRaises(TypeError) as context:
1398 bytes.__mod__(b"%X", (C(),))
1399 self.assertEqual(
1400 str(context.exception), "%X format: an integer is required, not C"
1401 )
1402
1403 def test_o_format_returns_bytes(self):
1404 self.assertEqual(bytes.__mod__(b"%o", (0,)), b"0")
1405 self.assertEqual(bytes.__mod__(b"%o", (-123,)), b"-173")
1406 self.assertEqual(bytes.__mod__(b"%o", (42,)), b"52")
1407
1408 def test_o_format_with_largeint_returns_bytes(self):
1409 self.assertEqual(
1410 bytes.__mod__(b"%o", (-123456789012345678901234567890)),
1411 b"-143564417755415637016711617605322",
1412 )
1413
1414 def test_o_format_with_non_int_returns_bytes(self):
1415 class C:
1416 def __float__(self):
1417 return 3.3
1418
1419 def __index__(self):
1420 return 77
1421
1422 self.assertEqual(bytes.__mod__(b"%o", (C(),)), b"115")
1423
1424 def test_o_format_raises_typeerrors(self):
1425 with self.assertRaises(TypeError) as context:
1426 bytes.__mod__(b"%o", (None,))
1427 self.assertEqual(
1428 str(context.exception), "%o format: an integer is required, not NoneType"
1429 )
1430
1431 def test_o_format_propagates_errors(self):
1432 class C:
1433 def __int__(self):
1434 return 42
1435
1436 def __index__(self):
1437 raise UserWarning()
1438
1439 with self.assertRaises(UserWarning):
1440 bytes.__mod__(b"%o", (C(),))
1441
1442 def test_o_format_reraises_typerrors(self):
1443 class C:
1444 def __int__(self):
1445 return 42
1446
1447 def __index__(self):
1448 raise TypeError("foobar")
1449
1450 with self.assertRaises(TypeError) as context:
1451 bytes.__mod__(b"%o", (C(),))
1452 self.assertEqual(
1453 str(context.exception), "%o format: an integer is required, not C"
1454 )
1455
1456 def test_f_format_returns_bytes(self):
1457 self.assertEqual(bytes.__mod__(b"%f", (0.0,)), b"0.000000")
1458 self.assertEqual(bytes.__mod__(b"%f", (-0.0,)), b"-0.000000")
1459 self.assertEqual(bytes.__mod__(b"%f", (1.0,)), b"1.000000")
1460 self.assertEqual(bytes.__mod__(b"%f", (-1.0,)), b"-1.000000")
1461 self.assertEqual(bytes.__mod__(b"%f", (42.125,)), b"42.125000")
1462
1463 self.assertEqual(bytes.__mod__(b"%f", (1e3,)), b"1000.000000")
1464 self.assertEqual(bytes.__mod__(b"%f", (1e6,)), b"1000000.000000")
1465 self.assertEqual(
1466 bytes.__mod__(b"%f", (1e40,)),
1467 b"10000000000000000303786028427003666890752.000000",
1468 )
1469
1470 def test_F_format_returns_bytes(self):
1471 self.assertEqual(bytes.__mod__(b"%F", (42.125,)), b"42.125000")
1472
1473 def test_e_format_returns_bytes(self):
1474 self.assertEqual(bytes.__mod__(b"%e", (0.0,)), b"0.000000e+00")
1475 self.assertEqual(bytes.__mod__(b"%e", (-0.0,)), b"-0.000000e+00")
1476 self.assertEqual(bytes.__mod__(b"%e", (1.0,)), b"1.000000e+00")
1477 self.assertEqual(bytes.__mod__(b"%e", (-1.0,)), b"-1.000000e+00")
1478 self.assertEqual(bytes.__mod__(b"%e", (42.125,)), b"4.212500e+01")
1479
1480 self.assertEqual(bytes.__mod__(b"%e", (1e3,)), b"1.000000e+03")
1481 self.assertEqual(bytes.__mod__(b"%e", (1e6,)), b"1.000000e+06")
1482 self.assertEqual(bytes.__mod__(b"%e", (1e40,)), b"1.000000e+40")
1483
1484 def test_E_format_returns_bytes(self):
1485 self.assertEqual(bytes.__mod__(b"%E", (1.0,)), b"1.000000E+00")
1486
1487 def test_g_format_returns_bytes(self):
1488 self.assertEqual(bytes.__mod__(b"%g", (0.0,)), b"0")
1489 self.assertEqual(bytes.__mod__(b"%g", (-1.0,)), b"-1")
1490 self.assertEqual(bytes.__mod__(b"%g", (0.125,)), b"0.125")
1491 self.assertEqual(bytes.__mod__(b"%g", (3.5,)), b"3.5")
1492
1493 def test_eEfFgG_format_with_inf_returns_bytes(self):
1494 self.assertEqual(bytes.__mod__(b"%e", (float("inf"),)), b"inf")
1495 self.assertEqual(bytes.__mod__(b"%E", (float("inf"),)), b"INF")
1496 self.assertEqual(bytes.__mod__(b"%f", (float("inf"),)), b"inf")
1497 self.assertEqual(bytes.__mod__(b"%F", (float("inf"),)), b"INF")
1498 self.assertEqual(bytes.__mod__(b"%g", (float("inf"),)), b"inf")
1499 self.assertEqual(bytes.__mod__(b"%G", (float("inf"),)), b"INF")
1500
1501 self.assertEqual(bytes.__mod__(b"%e", (-float("inf"),)), b"-inf")
1502 self.assertEqual(bytes.__mod__(b"%E", (-float("inf"),)), b"-INF")
1503 self.assertEqual(bytes.__mod__(b"%f", (-float("inf"),)), b"-inf")
1504 self.assertEqual(bytes.__mod__(b"%F", (-float("inf"),)), b"-INF")
1505 self.assertEqual(bytes.__mod__(b"%g", (-float("inf"),)), b"-inf")
1506 self.assertEqual(bytes.__mod__(b"%G", (-float("inf"),)), b"-INF")
1507
1508 def test_eEfFgG_format_with_nan_returns_bytes(self):
1509 self.assertEqual(bytes.__mod__(b"%e", (float("nan"),)), b"nan")
1510 self.assertEqual(bytes.__mod__(b"%E", (float("nan"),)), b"NAN")
1511 self.assertEqual(bytes.__mod__(b"%f", (float("nan"),)), b"nan")
1512 self.assertEqual(bytes.__mod__(b"%F", (float("nan"),)), b"NAN")
1513 self.assertEqual(bytes.__mod__(b"%g", (float("nan"),)), b"nan")
1514 self.assertEqual(bytes.__mod__(b"%G", (float("nan"),)), b"NAN")
1515
1516 self.assertEqual(bytes.__mod__(b"%e", (float("-nan"),)), b"nan")
1517 self.assertEqual(bytes.__mod__(b"%E", (float("-nan"),)), b"NAN")
1518 self.assertEqual(bytes.__mod__(b"%f", (float("-nan"),)), b"nan")
1519 self.assertEqual(bytes.__mod__(b"%F", (float("-nan"),)), b"NAN")
1520 self.assertEqual(bytes.__mod__(b"%g", (float("-nan"),)), b"nan")
1521 self.assertEqual(bytes.__mod__(b"%G", (float("-nan"),)), b"NAN")
1522
1523 def test_f_format_with_precision_returns_bytes(self):
1524 number = 1.23456789123456789
1525 self.assertEqual(bytes.__mod__(b"%.0f", number), b"1")
1526 self.assertEqual(bytes.__mod__(b"%.1f", number), b"1.2")
1527 self.assertEqual(bytes.__mod__(b"%.2f", number), b"1.23")
1528 self.assertEqual(bytes.__mod__(b"%.3f", number), b"1.235")
1529 self.assertEqual(bytes.__mod__(b"%.4f", number), b"1.2346")
1530 self.assertEqual(bytes.__mod__(b"%.5f", number), b"1.23457")
1531 self.assertEqual(bytes.__mod__(b"%.6f", number), b"1.234568")
1532 self.assertEqual(bytes.__mod__(b"%f", number), b"1.234568")
1533
1534 self.assertEqual(bytes.__mod__(b"%.17f", number), b"1.23456789123456789")
1535 self.assertEqual(
1536 bytes.__mod__(b"%.25f", number), b"1.2345678912345678934769921"
1537 )
1538 self.assertEqual(
1539 bytes.__mod__(b"%.60f", number),
1540 b"1.234567891234567893476992139767389744520187377929687500000000",
1541 )
1542
1543 def test_eEfFgG_format_with_precision_returns_bytes(self):
1544 number = 1.23456789123456789
1545 self.assertEqual(bytes.__mod__(b"%.0e", number), b"1e+00")
1546 self.assertEqual(bytes.__mod__(b"%.0E", number), b"1E+00")
1547 self.assertEqual(bytes.__mod__(b"%.0f", number), b"1")
1548 self.assertEqual(bytes.__mod__(b"%.0F", number), b"1")
1549 self.assertEqual(bytes.__mod__(b"%.0g", number), b"1")
1550 self.assertEqual(bytes.__mod__(b"%.0G", number), b"1")
1551 self.assertEqual(bytes.__mod__(b"%.4e", number), b"1.2346e+00")
1552 self.assertEqual(bytes.__mod__(b"%.4E", number), b"1.2346E+00")
1553 self.assertEqual(bytes.__mod__(b"%.4f", number), b"1.2346")
1554 self.assertEqual(bytes.__mod__(b"%.4F", number), b"1.2346")
1555 self.assertEqual(bytes.__mod__(b"%.4g", number), b"1.235")
1556 self.assertEqual(bytes.__mod__(b"%.4G", number), b"1.235")
1557 self.assertEqual(bytes.__mod__(b"%e", number), b"1.234568e+00")
1558 self.assertEqual(bytes.__mod__(b"%E", number), b"1.234568E+00")
1559 self.assertEqual(bytes.__mod__(b"%f", number), b"1.234568")
1560 self.assertEqual(bytes.__mod__(b"%F", number), b"1.234568")
1561 self.assertEqual(bytes.__mod__(b"%g", number), b"1.23457")
1562 self.assertEqual(bytes.__mod__(b"%G", number), b"1.23457")
1563
1564 def test_g_format_with_flags_and_width_returns_bytes(self):
1565 self.assertEqual(bytes.__mod__(b"%5g", 7.0), b" 7")
1566 self.assertEqual(bytes.__mod__(b"%5g", 7.2), b" 7.2")
1567 self.assertEqual(bytes.__mod__(b"% 5g", 7.2), b" 7.2")
1568 self.assertEqual(bytes.__mod__(b"%+5g", 7.2), b" +7.2")
1569 self.assertEqual(bytes.__mod__(b"%5g", -7.2), b" -7.2")
1570 self.assertEqual(bytes.__mod__(b"% 5g", -7.2), b" -7.2")
1571 self.assertEqual(bytes.__mod__(b"%+5g", -7.2), b" -7.2")
1572
1573 self.assertEqual(bytes.__mod__(b"%-5g", 7.0), b"7 ")
1574 self.assertEqual(bytes.__mod__(b"%-5g", 7.2), b"7.2 ")
1575 self.assertEqual(bytes.__mod__(b"%- 5g", 7.2), b" 7.2 ")
1576 self.assertEqual(bytes.__mod__(b"%-+5g", 7.2), b"+7.2 ")
1577 self.assertEqual(bytes.__mod__(b"%-5g", -7.2), b"-7.2 ")
1578 self.assertEqual(bytes.__mod__(b"%- 5g", -7.2), b"-7.2 ")
1579 self.assertEqual(bytes.__mod__(b"%-+5g", -7.2), b"-7.2 ")
1580
1581 self.assertEqual(bytes.__mod__(b"%#g", 7.0), b"7.00000")
1582
1583 self.assertEqual(bytes.__mod__(b"%#- 7.2g", float("-nan")), b" nan ")
1584 self.assertEqual(bytes.__mod__(b"%#- 7.2g", float("inf")), b" inf ")
1585 self.assertEqual(bytes.__mod__(b"%#- 7.2g", float("-inf")), b"-inf ")
1586
1587 def test_eEfFgG_format_with_flags_and_width_returns_bytes(self):
1588 number = 1.23456789123456789
1589 self.assertEqual(bytes.__mod__(b"% -#12.3e", number), b" 1.235e+00 ")
1590 self.assertEqual(bytes.__mod__(b"% -#12.3E", number), b" 1.235E+00 ")
1591 self.assertEqual(bytes.__mod__(b"% -#12.3f", number), b" 1.235 ")
1592 self.assertEqual(bytes.__mod__(b"% -#12.3F", number), b" 1.235 ")
1593 self.assertEqual(bytes.__mod__(b"% -#12.3g", number), b" 1.23 ")
1594 self.assertEqual(bytes.__mod__(b"% -#12.3G", number), b" 1.23 ")
1595
1596 def test_ef_format_with_non_float_raises_type_error(self):
1597 with self.assertRaises(TypeError) as context:
1598 bytes.__mod__(b"%e", (None,))
1599 self.assertEqual(
1600 str(context.exception), "float argument required, not NoneType"
1601 )
1602
1603 class C:
1604 def __float__(self):
1605 return "not a float"
1606
1607 with self.assertRaises(TypeError) as context:
1608 bytes.__mod__(b"%f", (C(),))
1609 self.assertEqual(str(context.exception), "float argument required, not C")
1610
1611 def test_efg_format_with_non_float_returns_bytes(self):
1612 class A(float):
1613 pass
1614
1615 self.assertEqual(
1616 bytes.__mod__(b"%e", (A(9.625),)), bytes.__mod__(b"%e", (9.625,))
1617 )
1618
1619 class C:
1620 def __float__(self):
1621 return 3.5
1622
1623 self.assertEqual(bytes.__mod__(b"%f", (C(),)), bytes.__mod__(b"%f", (3.5,)))
1624
1625 class D:
1626 def __float__(self):
1627 return A(-12.75)
1628
1629 warnings.filterwarnings(
1630 action="ignore",
1631 category=DeprecationWarning,
1632 message=".*__float__ returned non-float.*",
1633 module=__name__,
1634 )
1635 self.assertEqual(bytes.__mod__(b"%g", (D(),)), bytes.__mod__(b"%g", (-12.75,)))
1636
1637 def test_percent_format_returns_percent(self):
1638 self.assertEqual(bytes.__mod__(b"%%", ()), b"%")
1639
1640 def test_escaped_percent_with_characters_between_raises_type_error(self):
1641 with self.assertRaises(TypeError) as context:
1642 bytes.__mod__(b"%0.0%", ())
1643 self.assertEqual(
1644 str(context.exception), "not enough arguments for format string"
1645 )
1646 with self.assertRaises(TypeError) as context:
1647 bytes.__mod__(b"%*.%", (42,))
1648 self.assertEqual(
1649 str(context.exception), "not enough arguments for format string"
1650 )
1651 with self.assertRaises(TypeError) as context:
1652 bytes.__mod__(b"%d %*.%", (42,))
1653 self.assertEqual(
1654 str(context.exception), "not enough arguments for format string"
1655 )
1656 with self.assertRaises(TypeError) as context:
1657 bytes.__mod__(b"%.*%", (88,))
1658 self.assertEqual(
1659 str(context.exception), "not enough arguments for format string"
1660 )
1661 with self.assertRaises(TypeError) as context:
1662 bytes.__mod__(b"%0#*.42%", (1234,))
1663 self.assertEqual(
1664 str(context.exception), "not enough arguments for format string"
1665 )
1666
1667 def test_escaped_percent_with_characters_between_raises_value_error(self):
1668 with self.assertRaises(ValueError) as context:
1669 bytes.__mod__(b"%*.%", (42, 1))
1670 self.assertEqual(
1671 str(context.exception), "unsupported format character '%' (0x25) at index 3"
1672 )
1673
1674 def test_flags_get_accepted(self):
1675 self.assertEqual(bytes.__mod__(b"%-s", b""), b"")
1676 self.assertEqual(bytes.__mod__(b"%+s", b""), b"")
1677 self.assertEqual(bytes.__mod__(b"% s", b""), b"")
1678 self.assertEqual(bytes.__mod__(b"%#s", b""), b"")
1679 self.assertEqual(bytes.__mod__(b"%0s", b""), b"")
1680 self.assertEqual(bytes.__mod__(b"%#-#0+ -s", b""), b"")
1681
1682 def test_string_format_with_width_returns_bytes(self):
1683 self.assertEqual(bytes.__mod__(b"%5s", b"oh"), b" oh")
1684 self.assertEqual(bytes.__mod__(b"%-5s", b"ah"), b"ah ")
1685 self.assertEqual(bytes.__mod__(b"%05s", b"uh"), b" uh")
1686 self.assertEqual(bytes.__mod__(b"%-# 5s", b"eh"), b"eh ")
1687
1688 self.assertEqual(bytes.__mod__(b"%0s", b"foo"), b"foo")
1689 self.assertEqual(bytes.__mod__(b"%-0s", b"foo"), b"foo")
1690 self.assertEqual(bytes.__mod__(b"%10s", b"hello world"), b"hello world")
1691 self.assertEqual(bytes.__mod__(b"%-10s", b"hello world"), b"hello world")
1692
1693 def test_string_format_with_width_star_returns_bytes(self):
1694 self.assertEqual(bytes.__mod__(b"%*s", (7, b"foo")), b" foo")
1695 self.assertEqual(bytes.__mod__(b"%*s", (-7, b"bar")), b"bar ")
1696 self.assertEqual(bytes.__mod__(b"%-*s", (7, b"baz")), b"baz ")
1697 self.assertEqual(bytes.__mod__(b"%-*s", (-7, b"bam")), b"bam ")
1698
1699 def test_string_format_with_precision_returns_bytes(self):
1700 self.assertEqual(bytes.__mod__(b"%.3s", b"python"), b"pyt")
1701 self.assertEqual(bytes.__mod__(b"%.0s", b"python"), b"")
1702 self.assertEqual(bytes.__mod__(b"%.10s", b"python"), b"python")
1703
1704 def test_string_format_with_precision_star_returns_bytes(self):
1705 self.assertEqual(bytes.__mod__(b"%.*s", (3, b"monty")), b"mon")
1706 self.assertEqual(bytes.__mod__(b"%.*s", (0, b"monty")), b"")
1707 self.assertEqual(bytes.__mod__(b"%.*s", (-4, b"monty")), b"")
1708
1709 def test_string_format_with_width_and_precision_returns_bytes(self):
1710 self.assertEqual(bytes.__mod__(b"%8.3s", (b"foobar",)), b" foo")
1711 self.assertEqual(bytes.__mod__(b"%-8.3s", (b"foobar",)), b"foo ")
1712 self.assertEqual(bytes.__mod__(b"%*.3s", (8, b"foobar")), b" foo")
1713 self.assertEqual(bytes.__mod__(b"%*.3s", (-8, b"foobar")), b"foo ")
1714 self.assertEqual(bytes.__mod__(b"%8.*s", (3, b"foobar")), b" foo")
1715 self.assertEqual(bytes.__mod__(b"%-8.*s", (3, b"foobar")), b"foo ")
1716 self.assertEqual(bytes.__mod__(b"%*.*s", (8, 3, b"foobar")), b" foo")
1717 self.assertEqual(bytes.__mod__(b"%-*.*s", (8, 3, b"foobar")), b"foo ")
1718
1719 def test_s_r_a_c_formats_accept_flags_width_precision_return_strings(self):
1720 self.assertEqual(bytes.__mod__(b"%-*.3s", (8, b"foobar")), b"foo ")
1721 self.assertEqual(bytes.__mod__(b"%-*.3r", (8, b"foobar")), b"b'f ")
1722 self.assertEqual(bytes.__mod__(b"%-*.3a", (8, b"foobar")), b"b'f ")
1723 self.assertEqual(bytes.__mod__(b"%-*.3c", (8, 94)), b"^ ")
1724
1725 def test_number_format_with_sign_flag_returns_bytes(self):
1726 self.assertEqual(bytes.__mod__(b"%+d", (42,)), b"+42")
1727 self.assertEqual(bytes.__mod__(b"%+d", (-42,)), b"-42")
1728 self.assertEqual(bytes.__mod__(b"% d", (17,)), b" 17")
1729 self.assertEqual(bytes.__mod__(b"% d", (-17,)), b"-17")
1730 self.assertEqual(bytes.__mod__(b"%+ d", (42,)), b"+42")
1731 self.assertEqual(bytes.__mod__(b"%+ d", (-42,)), b"-42")
1732 self.assertEqual(bytes.__mod__(b"% +d", (17,)), b"+17")
1733 self.assertEqual(bytes.__mod__(b"% +d", (-17,)), b"-17")
1734
1735 def test_number_format_alt_flag_returns_bytes(self):
1736 self.assertEqual(bytes.__mod__(b"%#d", (23,)), b"23")
1737 self.assertEqual(bytes.__mod__(b"%#x", (23,)), b"0x17")
1738 self.assertEqual(bytes.__mod__(b"%#X", (23,)), b"0X17")
1739 self.assertEqual(bytes.__mod__(b"%#o", (23,)), b"0o27")
1740
1741 def test_number_format_with_width_returns_bytes(self):
1742 self.assertEqual(bytes.__mod__(b"%5d", (123,)), b" 123")
1743 self.assertEqual(bytes.__mod__(b"%5d", (-8,)), b" -8")
1744 self.assertEqual(bytes.__mod__(b"%-5d", (123,)), b"123 ")
1745 self.assertEqual(bytes.__mod__(b"%-5d", (-8,)), b"-8 ")
1746
1747 self.assertEqual(bytes.__mod__(b"%05d", (123,)), b"00123")
1748 self.assertEqual(bytes.__mod__(b"%05d", (-8,)), b"-0008")
1749 self.assertEqual(bytes.__mod__(b"%-05d", (123,)), b"123 ")
1750 self.assertEqual(bytes.__mod__(b"%0-5d", (-8,)), b"-8 ")
1751
1752 self.assertEqual(bytes.__mod__(b"%#7x", (42,)), b" 0x2a")
1753 self.assertEqual(bytes.__mod__(b"%#7x", (-42,)), b" -0x2a")
1754
1755 self.assertEqual(bytes.__mod__(b"%5d", (123456,)), b"123456")
1756 self.assertEqual(bytes.__mod__(b"%-5d", (-123456,)), b"-123456")
1757
1758 def test_number_format_with_precision_returns_bytes(self):
1759 self.assertEqual(bytes.__mod__(b"%.5d", (123,)), b"00123")
1760 self.assertEqual(bytes.__mod__(b"%.5d", (-123,)), b"-00123")
1761 self.assertEqual(bytes.__mod__(b"%.5d", (1234567,)), b"1234567")
1762 self.assertEqual(bytes.__mod__(b"%#.5x", (99,)), b"0x00063")
1763
1764 def test_number_format_with_width_precision_flags_returns_bytes(self):
1765 self.assertEqual(bytes.__mod__(b"%8.3d", (12,)), b" 012")
1766 self.assertEqual(bytes.__mod__(b"%8.3d", (-7,)), b" -007")
1767 self.assertEqual(bytes.__mod__(b"%05.3d", (12,)), b"00012")
1768 self.assertEqual(bytes.__mod__(b"%+05.3d", (12,)), b"+0012")
1769 self.assertEqual(bytes.__mod__(b"% 05.3d", (12,)), b" 0012")
1770 self.assertEqual(bytes.__mod__(b"% 05.3x", (19,)), b" 0013")
1771
1772 self.assertEqual(bytes.__mod__(b"%-8.3d", (12,)), b"012 ")
1773 self.assertEqual(bytes.__mod__(b"%-8.3d", (-7,)), b"-007 ")
1774 self.assertEqual(bytes.__mod__(b"%- 8.3d", (66,)), b" 066 ")
1775
1776 def test_width_and_precision_star_raises_type_error(self):
1777 with self.assertRaises(TypeError) as context:
1778 bytes.__mod__(b"%*d", (42,))
1779 self.assertEqual(
1780 str(context.exception), "not enough arguments for format string"
1781 )
1782 with self.assertRaises(TypeError) as context:
1783 bytes.__mod__(b"%.*d", (42,))
1784 self.assertEqual(
1785 str(context.exception), "not enough arguments for format string"
1786 )
1787 with self.assertRaises(TypeError) as context:
1788 bytes.__mod__(b"%*.*d", (42,))
1789 self.assertEqual(
1790 str(context.exception), "not enough arguments for format string"
1791 )
1792 with self.assertRaises(TypeError) as context:
1793 bytes.__mod__(b"%*.*d", (1, 2))
1794 self.assertEqual(
1795 str(context.exception), "not enough arguments for format string"
1796 )
1797
1798 def test_negative_precision_raises_value_error(self):
1799 with self.assertRaises(ValueError) as context:
1800 bytes.__mod__(b"%.-2s", "foo")
1801 self.assertEqual(
1802 str(context.exception), "unsupported format character '-' (0x2d) at index 2"
1803 )
1804
1805 def test_two_specifiers_returns_bytes(self):
1806 self.assertEqual(bytes.__mod__(b"%s%s", (b"foo", b"bar")), b"foobar")
1807 self.assertEqual(bytes.__mod__(b",%s%s", (b"foo", b"bar")), b",foobar")
1808 self.assertEqual(bytes.__mod__(b"%s,%s", (b"foo", b"bar")), b"foo,bar")
1809 self.assertEqual(bytes.__mod__(b"%s%s,", (b"foo", b"bar")), b"foobar,")
1810 self.assertEqual(
1811 bytes.__mod__(b",%s..%s---", (b"foo", b"bar")), b",foo..bar---"
1812 )
1813 self.assertEqual(
1814 bytes.__mod__(b",%s...%s--", (b"foo", b"bar")), b",foo...bar--"
1815 )
1816 self.assertEqual(
1817 bytes.__mod__(b",,%s.%s---", (b"foo", b"bar")), b",,foo.bar---"
1818 )
1819 self.assertEqual(
1820 bytes.__mod__(b",,%s...%s-", (b"foo", b"bar")), b",,foo...bar-"
1821 )
1822 self.assertEqual(
1823 bytes.__mod__(b",,,%s..%s-", (b"foo", b"bar")), b",,,foo..bar-"
1824 )
1825 self.assertEqual(
1826 bytes.__mod__(b",,,%s.%s--", (b"foo", b"bar")), b",,,foo.bar--"
1827 )
1828
1829 def test_mixed_specifiers_with_percents_returns_bytes(self):
1830 self.assertEqual(bytes.__mod__(b"%%%s%%%s%%", (b"foo", b"bar")), b"%foo%bar%")
1831
1832 def test_mixed_specifiers_returns_bytes(self):
1833 self.assertEqual(
1834 bytes.__mod__(b"a %d %g %s", (123, 3.14, b"baz")), b"a 123 3.14 baz"
1835 )
1836
1837 def test_specifier_missing_format_raises_value_error(self):
1838 with self.assertRaises(ValueError) as context:
1839 bytes.__mod__(b"%", ())
1840 self.assertEqual(str(context.exception), "incomplete format")
1841 with self.assertRaises(ValueError) as context:
1842 bytes.__mod__(b"%(foo)", {b"foo": None})
1843 self.assertEqual(str(context.exception), "incomplete format")
1844
1845 def test_unknown_specifier_raises_value_error(self):
1846 with self.assertRaises(ValueError) as context:
1847 bytes.__mod__(b"try %Y", (42,))
1848 self.assertEqual(
1849 str(context.exception), "unsupported format character 'Y' (0x59) at index 5"
1850 )
1851
1852 def test_too_few_args_raises_type_error(self):
1853 with self.assertRaises(TypeError) as context:
1854 bytes.__mod__(b"%s%s", (b"foo",))
1855 self.assertEqual(
1856 str(context.exception), "not enough arguments for format string"
1857 )
1858
1859 def test_too_many_args_raises_type_error(self):
1860 with self.assertRaises(TypeError) as context:
1861 bytes.__mod__(b"hello", 42)
1862 self.assertEqual(
1863 str(context.exception),
1864 "not all arguments converted during bytes formatting",
1865 )
1866 with self.assertRaises(TypeError) as context:
1867 bytes.__mod__(b"%d%s", (1, b"foo", 3))
1868 self.assertEqual(
1869 str(context.exception),
1870 "not all arguments converted during bytes formatting",
1871 )
1872
1873
1874if __name__ == "__main__":
1875 unittest.main()