|
1 | 1 | from contextlib import contextmanager |
2 | 2 | import linecache |
| 3 | +import logging |
3 | 4 | import os |
4 | 5 | import importlib |
5 | 6 | import inspect |
@@ -509,6 +510,47 @@ def test_catchwarnings_with_simplefilter_error(self): |
509 | 510 | stderr = stderr.getvalue() |
510 | 511 | self.assertIn(error_msg, stderr) |
511 | 512 |
|
| 513 | + def test_catchwarnings_with_showwarning(self): |
| 514 | + # gh-146358: catch_warnings must override warnings.showwarning() |
| 515 | + # if it's not the default implementation. |
| 516 | + |
| 517 | + warns = [] |
| 518 | + def custom_showwarning(message, category, filename, lineno, |
| 519 | + file=None, line=None): |
| 520 | + warns.append(message) |
| 521 | + |
| 522 | + with self.module.catch_warnings(): |
| 523 | + self.module.resetwarnings() |
| 524 | + |
| 525 | + with support.swap_attr(self.module, 'showwarning', |
| 526 | + custom_showwarning): |
| 527 | + with self.module.catch_warnings(record=True) as recorded: |
| 528 | + self.module.warn("recorded") |
| 529 | + self.assertEqual(len(recorded), 1) |
| 530 | + self.assertEqual(str(recorded[0].message), 'recorded') |
| 531 | + self.assertIs(self.module.showwarning, custom_showwarning) |
| 532 | + |
| 533 | + self.module.warn("custom") |
| 534 | + |
| 535 | + self.assertEqual(len(warns), 1) |
| 536 | + self.assertEqual(str(warns[0]), "custom") |
| 537 | + |
| 538 | + def test_catchwarnings_logging(self): |
| 539 | + # gh-146358: catch_warnings(record=True) must replace the |
| 540 | + # showwarning() function set by logging.captureWarnings(True). |
| 541 | + |
| 542 | + with self.module.catch_warnings(): |
| 543 | + self.module.resetwarnings() |
| 544 | + logging.captureWarnings(True) |
| 545 | + |
| 546 | + with self.module.catch_warnings(record=True) as recorded: |
| 547 | + self.module.warn("recorded") |
| 548 | + self.assertEqual(len(recorded), 1) |
| 549 | + self.assertEqual(str(recorded[0].message), 'recorded') |
| 550 | + |
| 551 | + logging.captureWarnings(False) |
| 552 | + |
| 553 | + |
512 | 554 | class CFilterTests(FilterTests, unittest.TestCase): |
513 | 555 | module = c_warnings |
514 | 556 |
|
|
0 commit comments