Skip to content

Commit 9d984fd

Browse files
orenmnserhiy-storchaka
authored andcommitted
bpo-31416: Fix assertion failures in case of a bad warnings.filters or warnings.defaultaction. (#3496)
Patch by Oren Milman.
1 parent 8239fd7 commit 9d984fd

File tree

3 files changed

+33
-3
lines changed

3 files changed

+33
-3
lines changed

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
@@ -110,7 +110,14 @@ get_default_action(void)
110110
}
111111
return _PyRuntime.warnings.default_action;
112112
}
113-
113+
if (!PyUnicode_Check(default_action)) {
114+
PyErr_Format(PyExc_TypeError,
115+
MODULE_NAME ".defaultaction must be a string, "
116+
"not '%.200s'",
117+
Py_TYPE(default_action)->tp_name);
118+
Py_DECREF(default_action);
119+
return NULL;
120+
}
114121
Py_DECREF(_PyRuntime.warnings.default_action);
115122
_PyRuntime.warnings.default_action = default_action;
116123
return default_action;
@@ -164,6 +171,14 @@ get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
164171
mod = PyTuple_GET_ITEM(tmp_item, 3);
165172
ln_obj = PyTuple_GET_ITEM(tmp_item, 4);
166173

174+
if (!PyUnicode_Check(action)) {
175+
PyErr_Format(PyExc_TypeError,
176+
"action must be a string, not '%.200s'",
177+
Py_TYPE(action)->tp_name);
178+
Py_DECREF(tmp_item);
179+
return NULL;
180+
}
181+
167182
good_msg = check_matched(msg, text);
168183
if (good_msg == -1) {
169184
Py_DECREF(tmp_item);
@@ -203,8 +218,6 @@ get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
203218
return action;
204219
}
205220

206-
PyErr_SetString(PyExc_ValueError,
207-
MODULE_NAME ".defaultaction not found");
208221
return NULL;
209222
}
210223

0 commit comments

Comments
 (0)