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

3 files changed

lines changed

Original file line number Diff line number Diff line change
@@ -877,6 +877,25 @@ def test_showwarning(self):
877 877 file_object, expected_file_line)
878 878 self.assertEqual(expect, file_object.getvalue())
879 879
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 +
880 899
881 900 class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
882 901 module = c_warnings
Original file line number Diff line number Diff line change
@@ -124,7 +124,7 @@ def _formatwarnmsg(msg):
124 124 if fw is not _formatwarning_orig:
125 125 # warnings.formatwarning() was replaced
126 126 return fw(msg.message, msg.category,
127 -msg.filename, msg.lineno, line=msg.line)
127 +msg.filename, msg.lineno, msg.line)
128 128 return _formatwarnmsg_impl(msg)
129 129
130 130 def filterwarnings(action, message="", category=Warning, module="", lineno=0,
Original file line number Diff line number Diff 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.