3b94f4b70c
* Add 'anyhow' feature which provides simple From<anyhow::Error> for PyErr impl This makes it possible to use anyhow::Result<T> as the return type for methods and functions exposed to Python. The current implementation just stringifies the anyhow::Error before shoving it into a PyRuntimeError. Conversion back to the anyhow::Error is not possible, but it is better than nothing. Signed-off-by: Chris Laplante <chris.laplante@agilent.com> * Document `anyhow` feature in the guide Signed-off-by: Chris Laplante <chris.laplante@agilent.com> * update changelog to document anyhow feature * WIP adding tests * Finish up anyhow feature * Fix formatting * Fix tests * Fix tests * Apply review suggestions Co-authored-by: Bruno Kolenbrander <59372212+mejrs@users.noreply.github.com> Co-authored-by: mejrs <brunokolenbrander@hotmail.com>
49 lines
1 KiB
Rust
49 lines
1 KiB
Rust
#![cfg(feature = "anyhow")]
|
|
|
|
#[test]
|
|
fn test_anyhow_py_function_ok_result() {
|
|
use pyo3::{py_run, pyfunction, wrap_pyfunction, Python};
|
|
|
|
#[pyfunction]
|
|
fn produce_ok_result() -> anyhow::Result<String> {
|
|
Ok(String::from("OK buddy"))
|
|
}
|
|
|
|
Python::with_gil(|py| {
|
|
let func = wrap_pyfunction!(produce_ok_result)(py).unwrap();
|
|
|
|
py_run!(
|
|
py,
|
|
func,
|
|
r#"
|
|
func()
|
|
"#
|
|
);
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn test_anyhow_py_function_err_result() {
|
|
use pyo3::{pyfunction, types::PyDict, wrap_pyfunction, Python};
|
|
|
|
#[pyfunction]
|
|
fn produce_err_result() -> anyhow::Result<String> {
|
|
anyhow::bail!("error time")
|
|
}
|
|
|
|
Python::with_gil(|py| {
|
|
let func = wrap_pyfunction!(produce_err_result)(py).unwrap();
|
|
let locals = PyDict::new(py);
|
|
locals.set_item("func", func).unwrap();
|
|
|
|
py.run(
|
|
r#"
|
|
func()
|
|
"#,
|
|
None,
|
|
Some(locals),
|
|
)
|
|
.unwrap_err();
|
|
});
|
|
}
|