Skip to content

Commit be5e229

Browse files
[3.12] gh-122191: Fix test_warnings failure if run with -Werror (GH-122222) (GH-122257)
__spec__.loader is now required in the module globals (see gh-86298). (cherry picked from commit 9b4fe9b)
1 parent dd4c8ac commit be5e229

File tree

1 file changed

+23
-13
lines changed

1 file changed

+23
-13
lines changed

Lib/test/test_warnings/__init__.py

+23-13
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from contextlib import contextmanager
22
import linecache
33
import os
4+
import importlib
45
from io import StringIO
56
import re
67
import sys
@@ -858,37 +859,46 @@ def test_issue31285(self):
858859
# warn_explicit() should neither raise a SystemError nor cause an
859860
# assertion failure, in case the return value of get_source() has a
860861
# 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+
862868
class BadLoader:
863869
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)
867871
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+
869879

870880
wmod = self.module
871881
with original_warnings.catch_warnings(module=wmod):
872882
wmod.filterwarnings('default', category=UserWarning)
873883

884+
linecache.clearcache()
874885
with support.captured_stderr() as stderr:
875886
wmod.warn_explicit(
876887
'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))
879889
self.assertIn('UserWarning: foo', stderr.getvalue())
890+
self.assertEqual(get_source_called, [42])
880891

881-
show = wmod._showwarnmsg
882-
try:
892+
linecache.clearcache()
893+
with support.swap_attr(wmod, '_showwarnmsg', None):
883894
del wmod._showwarnmsg
884895
with support.captured_stderr() as stderr:
885896
wmod.warn_explicit(
886897
'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]))
889899
self.assertIn('UserWarning: eggs', stderr.getvalue())
890-
finally:
891-
wmod._showwarnmsg = show
900+
self.assertEqual(get_source_called, [42, [42]])
901+
linecache.clearcache()
892902

893903
@support.cpython_only
894904
def test_issue31411(self):

0 commit comments

Comments
 (0)