Skip to content

Commit 0648d71

Browse files
Add test for 'PyErr::set_context'
1 parent af62ab0 commit 0648d71

2 files changed

Lines changed: 20 additions & 7 deletions

File tree

src/err/err_state.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use crate::{
1313
ffi,
1414
ffi_ptr_ext::FfiPtrExt,
1515
types::{PyAnyMethods, PyTraceback, PyType},
16-
Bound, BoundObject, Py, PyAny, PyErrArguments, PyTypeInfo, Python,
16+
Bound, Py, PyAny, PyErrArguments, PyTypeInfo, Python,
1717
};
1818

1919
pub(crate) struct PyErrState {
@@ -205,10 +205,8 @@ impl PyErrStateNormalized {
205205
}
206206

207207
#[cfg_attr(not(Py_3_12), allow(unused))]
208-
pub(crate) fn set_context(&self, py: Python<'_>, context: Option<Bound<'_, PyBaseException>>) {
209-
let context = context
210-
.map(Bound::into_ptr)
211-
.unwrap_or_else(|| crate::types::PyNone::get(py).into_ptr());
208+
pub(crate) fn set_context(&self, _py: Python<'_>, context: Option<Bound<'_, PyBaseException>>) {
209+
let context = context.map(Bound::into_ptr).unwrap_or(std::ptr::null_mut());
212210

213211
unsafe { ffi::PyException_SetContext(self.pvalue.as_ptr(), context) };
214212
}

src/err/mod.rs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -618,11 +618,11 @@ impl PyErr {
618618
/// Set the context associated with the exception, pass `None` to clear it.
619619
pub fn set_context(&self, py: Python<'_>, context: Option<PyErr>) {
620620
let value = self.value(py);
621-
let cause = context.map(|err| err.into_value(py));
621+
let context = context.map(|err| err.into_value(py));
622622
unsafe {
623623
ffi::PyException_SetContext(
624624
value.as_ptr(),
625-
cause.map_or(std::ptr::null_mut(), Py::into_ptr),
625+
context.map_or(std::ptr::null_mut(), Py::into_ptr),
626626
);
627627
}
628628
}
@@ -1050,4 +1050,19 @@ mod tests {
10501050
);
10511051
});
10521052
}
1053+
1054+
#[test]
1055+
fn test_set_context() {
1056+
Python::attach(|py| {
1057+
let err = PyErr::new::<PyValueError, _>("original error");
1058+
assert!(err.context(py).is_none());
1059+
1060+
let context = PyErr::new::<PyTypeError, _>("context error");
1061+
err.set_context(py, Some(context));
1062+
assert!(err.context(py).unwrap().is_instance_of::<PyTypeError>(py));
1063+
1064+
err.set_context(py, None);
1065+
assert!(err.context(py).is_none());
1066+
})
1067+
}
10531068
}

0 commit comments

Comments
 (0)