|
7 | 7 | import itertools |
8 | 8 | import sys |
9 | 9 | import unittest |
| 10 | +import warnings |
10 | 11 |
|
11 | 12 | from iptest import IronPythonTestCase, is_cli, is_cpython, long, run_test, skipUnlessIronPython |
12 | 13 |
|
@@ -299,6 +300,40 @@ def __index__(self): |
299 | 300 | self.assertRaises(TypeError, int.from_bytes, IndexableInt(2), 'big') |
300 | 301 | self.assertRaises(TypeError, int.from_bytes, 2, 'big') |
301 | 302 |
|
| 303 | + @unittest.skipUnless(sys.flags.bytes_warning, "Run Python with the '-b' flag on command line for this test") |
| 304 | + def test_byteswarning(self): |
| 305 | + with warnings.catch_warnings(record=True) as ws: |
| 306 | + warnings.simplefilter("always") |
| 307 | + |
| 308 | + with self.assertWarnsRegex(BytesWarning, r"^str\(\) on a bytes instance$"): |
| 309 | + self.assertEqual(str(b'abc'), "b'abc'") |
| 310 | + self.assertEqual(str(b'abc', 'ascii'), 'abc') |
| 311 | + |
| 312 | + with self.assertWarnsRegex(BytesWarning, r"^str\(\) on a bytearray instance$"): |
| 313 | + self.assertEqual(str(bytearray(b'abc')), "bytearray(b'abc')") |
| 314 | + self.assertEqual(str(bytearray(b'abc'), 'ascii'), 'abc') |
| 315 | + |
| 316 | + class B(bytes): |
| 317 | + def __str__(self): |
| 318 | + return "This is B" |
| 319 | + |
| 320 | + self.assertEqual(str(B(b'abc')), "This is B") # no warning |
| 321 | + |
| 322 | + class B2(bytes): pass |
| 323 | + with self.assertWarnsRegex(BytesWarning, r"^str\(\) on a bytes instance$"): |
| 324 | + self.assertEqual(str(B2(b'abc')), "b'abc'") |
| 325 | + |
| 326 | + self.assertEqual(len(ws), 0) # no unchecked warnings |
| 327 | + |
| 328 | + def test_byteswarning_user(self): |
| 329 | + with warnings.catch_warnings(record=True) as ws: |
| 330 | + warnings.simplefilter("always") |
| 331 | + |
| 332 | + with self.assertWarnsRegex(BytesWarning, r"^test warning$"): |
| 333 | + warnings.warn("test warning", BytesWarning) |
| 334 | + |
| 335 | + self.assertEqual(len(ws), 0) # no unchecked warnings |
| 336 | + |
302 | 337 | def test_capitalize(self): |
303 | 338 | tests = [(b'foo', b'Foo'), |
304 | 339 | (b' foo', b' foo'), |
|
0 commit comments