Skip to content

Commit 9adc87b

Browse files
[3.6] bpo-31416: Fix assertion failures in case of a bad warnings.filters or warnings.defaultaction. (GH-3496) (#3509)
Patch by Oren Milman.. (cherry picked from commit 9d984fd)
1 parent cb356c2 commit 9adc87b

3 files changed

Lines changed: 33 additions & 3 deletions

File tree

Lib/test/test_warnings/__init__.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -805,6 +805,21 @@ def test_issue31411(self):
805805
with self.assertRaises(TypeError):
806806
wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None)
807807

808+
@support.cpython_only
809+
def test_issue31416(self):
810+
# warn_explicit() shouldn't cause an assertion failure in case of a
811+
# bad warnings.filters or warnings.defaultaction.
812+
wmod = self.module
813+
with original_warnings.catch_warnings(module=wmod):
814+
wmod.filters = [(None, None, Warning, None, 0)]
815+
with self.assertRaises(TypeError):
816+
wmod.warn_explicit('foo', Warning, 'bar', 1)
817+
818+
wmod.filters = []
819+
with support.swap_attr(wmod, 'defaultaction', None), \
820+
self.assertRaises(TypeError):
821+
wmod.warn_explicit('foo', Warning, 'bar', 1)
822+
808823

809824
class WarningsDisplayTests(BaseTest):
810825

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix assertion failures in case of a bad warnings.filters or
2+
warnings.defaultaction. Patch by Oren Milman.

Python/_warnings.c

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,14 @@ get_default_action(void)
118118
}
119119
return _default_action;
120120
}
121-
121+
if (!PyUnicode_Check(default_action)) {
122+
PyErr_Format(PyExc_TypeError,
123+
MODULE_NAME ".defaultaction must be a string, "
124+
"not '%.200s'",
125+
Py_TYPE(default_action)->tp_name);
126+
Py_DECREF(default_action);
127+
return NULL;
128+
}
122129
Py_DECREF(_default_action);
123130
_default_action = default_action;
124131
return default_action;
@@ -171,6 +178,14 @@ get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
171178
mod = PyTuple_GET_ITEM(tmp_item, 3);
172179
ln_obj = PyTuple_GET_ITEM(tmp_item, 4);
173180

181+
if (!PyUnicode_Check(action)) {
182+
PyErr_Format(PyExc_TypeError,
183+
"action must be a string, not '%.200s'",
184+
Py_TYPE(action)->tp_name);
185+
Py_DECREF(tmp_item);
186+
return NULL;
187+
}
188+
174189
good_msg = check_matched(msg, text);
175190
if (good_msg == -1) {
176191
Py_DECREF(tmp_item);
@@ -210,8 +225,6 @@ get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
210225
return action;
211226
}
212227

213-
PyErr_SetString(PyExc_ValueError,
214-
MODULE_NAME ".defaultaction not found");
215228
return NULL;
216229
}
217230

0 commit comments

Comments
 (0)