Skip to content

Commit be7c460

Browse files
tirkarthitashrifbillah
authored andcommitted
bpo-35178: Fix warnings._formatwarnmsg() (GH-12033)
Ensure custom formatwarning function can receive line as positional argument. Co-Authored-By: Tashrif Billah <[email protected]>
1 parent 91b9ecf commit be7c460

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

Lib/test/test_warnings/__init__.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -877,6 +877,25 @@ def test_showwarning(self):
877877
file_object, expected_file_line)
878878
self.assertEqual(expect, file_object.getvalue())
879879

880+
def test_formatwarning_override(self):
881+
# bpo-35178: Test that a custom formatwarning function gets the 'line'
882+
# argument as a positional argument, and not only as a keyword argument
883+
def myformatwarning(message, category, filename, lineno, text):
884+
return f'm={message}:c={category}:f={filename}:l={lineno}:t={text}'
885+
886+
file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
887+
line_num = 3
888+
file_line = linecache.getline(file_name, line_num).strip()
889+
message = 'msg'
890+
category = Warning
891+
file_object = StringIO()
892+
expected = f'm={message}:c={category}:f={file_name}:l={line_num}' + \
893+
f':t={file_line}'
894+
with support.swap_attr(self.module, 'formatwarning', myformatwarning):
895+
self.module.showwarning(message, category, file_name, line_num,
896+
file_object, file_line)
897+
self.assertEqual(file_object.getvalue(), expected)
898+
880899

881900
class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
882901
module = c_warnings

Lib/warnings.py

Lines changed: 1 addition & 1 deletion
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,
Lines changed: 2 additions & 0 deletions
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.

0 commit comments

Comments
 (0)