bpo-35178: Fix warnings._formatwarnmsg() (GH-12033) · python/cpython@b94874f

3 files changed

lines changed

Original file line numberDiff line numberDiff line change

@@ -940,6 +940,25 @@ def test_showwarning(self):

940940

file_object, expected_file_line)

941941

self.assertEqual(expect, file_object.getvalue())

942942
943+

def test_formatwarning_override(self):

944+

# bpo-35178: Test that a custom formatwarning function gets the 'line'

945+

# argument as a positional argument, and not only as a keyword argument

946+

def myformatwarning(message, category, filename, lineno, text):

947+

return f'm={message}:c={category}:f={filename}:l={lineno}:t={text}'

948+
949+

file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'

950+

line_num = 3

951+

file_line = linecache.getline(file_name, line_num).strip()

952+

message = 'msg'

953+

category = Warning

954+

file_object = StringIO()

955+

expected = f'm={message}:c={category}:f={file_name}:l={line_num}' + \

956+

f':t={file_line}'

957+

with support.swap_attr(self.module, 'formatwarning', myformatwarning):

958+

self.module.showwarning(message, category, file_name, line_num,

959+

file_object, file_line)

960+

self.assertEqual(file_object.getvalue(), expected)

961+
943962
944963

class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):

945964

module = c_warnings

Original file line numberDiff line numberDiff line change

@@ -124,7 +124,7 @@ def _formatwarnmsg(msg):

124124

if fw is not _formatwarning_orig:

125125

# warnings.formatwarning() was replaced

126126

return fw(msg.message, msg.category,

127-

msg.filename, msg.lineno, line=msg.line)

127+

msg.filename, msg.lineno, msg.line)

128128

return _formatwarnmsg_impl(msg)

129129
130130

def filterwarnings(action, message="", category=Warning, module="", lineno=0,

Original file line numberDiff line numberDiff line change

@@ -0,0 +1,2 @@

1+

Ensure custom :func:`warnings.formatwarning` function can receive `line` as

2+

positional argument. Based on patch by Tashrif Billah.