|
1 | 1 | from contextlib import contextmanager |
2 | 2 | import linecache |
3 | 3 | import os |
| 4 | +import importlib |
4 | 5 | import inspect |
5 | 6 | from io import StringIO |
6 | 7 | import re |
@@ -885,37 +886,46 @@ def test_issue31285(self): |
885 | 886 | # warn_explicit() should neither raise a SystemError nor cause an |
886 | 887 | # assertion failure, in case the return value of get_source() has a |
887 | 888 | # bad splitlines() method. |
888 | | - def get_bad_loader(splitlines_ret_val): |
| 889 | + get_source_called = [] |
| 890 | + def get_module_globals(*, splitlines_ret_val): |
| 891 | + class BadSource(str): |
| 892 | + def splitlines(self): |
| 893 | + return splitlines_ret_val |
| 894 | + |
889 | 895 | class BadLoader: |
890 | 896 | def get_source(self, fullname): |
891 | | - class BadSource(str): |
892 | | - def splitlines(self): |
893 | | - return splitlines_ret_val |
| 897 | + get_source_called.append(splitlines_ret_val) |
894 | 898 | return BadSource('spam') |
895 | | - return BadLoader() |
| 899 | + |
| 900 | + loader = BadLoader() |
| 901 | + spec = importlib.machinery.ModuleSpec('foobar', loader) |
| 902 | + return {'__loader__': loader, |
| 903 | + '__spec__': spec, |
| 904 | + '__name__': 'foobar'} |
| 905 | + |
896 | 906 |
|
897 | 907 | wmod = self.module |
898 | 908 | with original_warnings.catch_warnings(module=wmod): |
899 | 909 | wmod.filterwarnings('default', category=UserWarning) |
900 | 910 |
|
| 911 | + linecache.clearcache() |
901 | 912 | with support.captured_stderr() as stderr: |
902 | 913 | wmod.warn_explicit( |
903 | 914 | 'foo', UserWarning, 'bar', 1, |
904 | | - module_globals={'__loader__': get_bad_loader(42), |
905 | | - '__name__': 'foobar'}) |
| 915 | + module_globals=get_module_globals(splitlines_ret_val=42)) |
906 | 916 | self.assertIn('UserWarning: foo', stderr.getvalue()) |
| 917 | + self.assertEqual(get_source_called, [42]) |
907 | 918 |
|
908 | | - show = wmod._showwarnmsg |
909 | | - try: |
| 919 | + linecache.clearcache() |
| 920 | + with support.swap_attr(wmod, '_showwarnmsg', None): |
910 | 921 | del wmod._showwarnmsg |
911 | 922 | with support.captured_stderr() as stderr: |
912 | 923 | wmod.warn_explicit( |
913 | 924 | 'eggs', UserWarning, 'bar', 1, |
914 | | - module_globals={'__loader__': get_bad_loader([42]), |
915 | | - '__name__': 'foobar'}) |
| 925 | + module_globals=get_module_globals(splitlines_ret_val=[42])) |
916 | 926 | self.assertIn('UserWarning: eggs', stderr.getvalue()) |
917 | | - finally: |
918 | | - wmod._showwarnmsg = show |
| 927 | + self.assertEqual(get_source_called, [42, [42]]) |
| 928 | + linecache.clearcache() |
919 | 929 |
|
920 | 930 | @support.cpython_only |
921 | 931 | def test_issue31411(self): |
|
0 commit comments