Skip to content

Commit 4b50f88

Browse files
0z5asobolevn
andauthored
gh-161387: Check the type of the decimal context ContextVar (#161399)
Co-authored-by: sobolevn <mail@sobolevn.me>
1 parent 85a67ba commit 4b50f88

3 files changed

Lines changed: 30 additions & 0 deletions

File tree

‎Lib/test/test_decimal.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3780,6 +3780,27 @@ def test_crashing_signal_dict_flags(self):
37803780
@requires_cdecimal
37813781
class CContextAPItests(ContextAPItests, unittest.TestCase):
37823782
decimal = C
3783+
3784+
def test_current_context_var_wrong_type(self):
3785+
# gh-161387
3786+
if not self.decimal.HAVE_CONTEXTVAR:
3787+
self.skipTest("_decimal built without context variables")
3788+
value = object()
3789+
context_vars = [var for var in contextvars.copy_context()
3790+
if var.name == "decimal_context"]
3791+
self.assertTrue(context_vars)
3792+
tokens = [var.set(value) for var in context_vars]
3793+
3794+
def restore():
3795+
for var, token in zip(context_vars, tokens):
3796+
var.reset(token)
3797+
3798+
self.addCleanup(restore)
3799+
with self.assertRaisesRegex(TypeError, "got object"):
3800+
self.decimal.Decimal(1) + self.decimal.Decimal(2)
3801+
for var in context_vars:
3802+
self.assertIs(var.get(), value)
3803+
37833804
class PyContextAPItests(ContextAPItests, unittest.TestCase):
37843805
decimal = P
37853806

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a crash in :mod:`decimal` when the internal ``decimal_context``
2+
:class:`contextvars.ContextVar` holds a value that is not a context.

‎Modules/_decimal/_decimal.c‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2003,6 +2003,13 @@ current_context(decimal_state *state)
20032003
}
20042004

20052005
if (tl_context != NULL) {
2006+
if (!PyDecContext_Check(state, tl_context)) {
2007+
PyErr_Format(PyExc_TypeError,
2008+
"current decimal context must be a Context "
2009+
"instance, got %T", tl_context);
2010+
Py_DECREF(tl_context);
2011+
return NULL;
2012+
}
20062013
return tl_context;
20072014
}
20082015

0 commit comments

Comments
 (0)