|
1 | 1 | from contextlib import contextmanager
|
2 | 2 | import linecache
|
3 | 3 | import os
|
| 4 | +import importlib |
4 | 5 | from io import StringIO
|
5 | 6 | import re
|
6 | 7 | import sys
|
@@ -858,37 +859,46 @@ def test_issue31285(self):
|
858 | 859 | # warn_explicit() should neither raise a SystemError nor cause an
|
859 | 860 | # assertion failure, in case the return value of get_source() has a
|
860 | 861 | # bad splitlines() method.
|
861 |
| - def get_bad_loader(splitlines_ret_val): |
| 862 | + get_source_called = [] |
| 863 | + def get_module_globals(*, splitlines_ret_val): |
| 864 | + class BadSource(str): |
| 865 | + def splitlines(self): |
| 866 | + return splitlines_ret_val |
| 867 | + |
862 | 868 | class BadLoader:
|
863 | 869 | def get_source(self, fullname):
|
864 |
| - class BadSource(str): |
865 |
| - def splitlines(self): |
866 |
| - return splitlines_ret_val |
| 870 | + get_source_called.append(splitlines_ret_val) |
867 | 871 | return BadSource('spam')
|
868 |
| - return BadLoader() |
| 872 | + |
| 873 | + loader = BadLoader() |
| 874 | + spec = importlib.machinery.ModuleSpec('foobar', loader) |
| 875 | + return {'__loader__': loader, |
| 876 | + '__spec__': spec, |
| 877 | + '__name__': 'foobar'} |
| 878 | + |
869 | 879 |
|
870 | 880 | wmod = self.module
|
871 | 881 | with original_warnings.catch_warnings(module=wmod):
|
872 | 882 | wmod.filterwarnings('default', category=UserWarning)
|
873 | 883 |
|
| 884 | + linecache.clearcache() |
874 | 885 | with support.captured_stderr() as stderr:
|
875 | 886 | wmod.warn_explicit(
|
876 | 887 | 'foo', UserWarning, 'bar', 1,
|
877 |
| - module_globals={'__loader__': get_bad_loader(42), |
878 |
| - '__name__': 'foobar'}) |
| 888 | + module_globals=get_module_globals(splitlines_ret_val=42)) |
879 | 889 | self.assertIn('UserWarning: foo', stderr.getvalue())
|
| 890 | + self.assertEqual(get_source_called, [42]) |
880 | 891 |
|
881 |
| - show = wmod._showwarnmsg |
882 |
| - try: |
| 892 | + linecache.clearcache() |
| 893 | + with support.swap_attr(wmod, '_showwarnmsg', None): |
883 | 894 | del wmod._showwarnmsg
|
884 | 895 | with support.captured_stderr() as stderr:
|
885 | 896 | wmod.warn_explicit(
|
886 | 897 | 'eggs', UserWarning, 'bar', 1,
|
887 |
| - module_globals={'__loader__': get_bad_loader([42]), |
888 |
| - '__name__': 'foobar'}) |
| 898 | + module_globals=get_module_globals(splitlines_ret_val=[42])) |
889 | 899 | self.assertIn('UserWarning: eggs', stderr.getvalue())
|
890 |
| - finally: |
891 |
| - wmod._showwarnmsg = show |
| 900 | + self.assertEqual(get_source_called, [42, [42]]) |
| 901 | + linecache.clearcache() |
892 | 902 |
|
893 | 903 | @support.cpython_only
|
894 | 904 | def test_issue31411(self):
|
|
0 commit comments