From 618b9090ed3ddcdbd66253839c6dfb442e5eb24b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20Niederb=C3=BChl?= Date: Sat, 3 Aug 2019 00:45:53 +0200 Subject: [PATCH] Add test for exception with custom error Also simplify the old test. --- tests/test_exceptions.rs | 70 +++++++++++++++++++++++++++++++++------- 1 file changed, 59 insertions(+), 11 deletions(-) diff --git a/tests/test_exceptions.rs b/tests/test_exceptions.rs index e5e36c37..b80d0372 100644 --- a/tests/test_exceptions.rs +++ b/tests/test_exceptions.rs @@ -1,6 +1,7 @@ use pyo3::prelude::*; -use pyo3::types::IntoPyDict; -use pyo3::wrap_pyfunction; +use pyo3::{exceptions, py_run, wrap_pyfunction, PyErr, PyResult}; +use std::error::Error; +use std::fmt; use std::fs::File; mod common; @@ -15,14 +16,61 @@ fn fail_to_open_file() -> PyResult<()> { fn test_filenotfounderror() { let gil = Python::acquire_gil(); let py = gil.python(); - let fail_to_open_file = wrap_pyfunction!(fail_to_open_file)(py); - let d = [("fail_to_open_file", fail_to_open_file)].into_py_dict(py); - match py.run("fail_to_open_file()", None, Some(d)) { - Ok(()) => panic!("Call should raise a FileNotFoundError"), - Err(e) => { - py_assert!(py, e, "isinstance(e, FileNotFoundError)"); - py_assert!(py, e, "'No such file or directory (os error 2)' == str(e)"); - } - }; + + py_run!( + py, + fail_to_open_file, + r#" + try: + fail_to_open_file() + except FileNotFoundError as e: + assert str(e) == "No such file or directory (os error 2)" + "# + ); +} + +#[derive(Debug)] +struct CustomError; + +impl Error for CustomError {} + +impl fmt::Display for CustomError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Oh no!") + } +} + +impl std::convert::From for PyErr { + fn from(err: CustomError) -> PyErr { + exceptions::OSError::py_err(err.to_string()) + } +} + +fn fail_with_custom_error() -> Result<(), CustomError> { + Err(CustomError) +} + +#[pyfunction] +fn call_fail_with_custom_error() -> PyResult<()> { + fail_with_custom_error()?; + Ok(()) +} + +#[test] +fn test_custom_error() { + let gil = Python::acquire_gil(); + let py = gil.python(); + let call_fail_with_custom_error = wrap_pyfunction!(call_fail_with_custom_error)(py); + + py_run!( + py, + call_fail_with_custom_error, + r#" + try: + call_fail_with_custom_error() + except OSError as e: + assert str(e) == "Oh no!" + "# + ); }