Add test for exception with custom error
Also simplify the old test.
This commit is contained in:
parent
c6de61f7e1
commit
618b9090ed
|
@ -1,6 +1,7 @@
|
||||||
use pyo3::prelude::*;
|
use pyo3::prelude::*;
|
||||||
use pyo3::types::IntoPyDict;
|
use pyo3::{exceptions, py_run, wrap_pyfunction, PyErr, PyResult};
|
||||||
use pyo3::wrap_pyfunction;
|
use std::error::Error;
|
||||||
|
use std::fmt;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
|
|
||||||
mod common;
|
mod common;
|
||||||
|
@ -15,14 +16,61 @@ fn fail_to_open_file() -> PyResult<()> {
|
||||||
fn test_filenotfounderror() {
|
fn test_filenotfounderror() {
|
||||||
let gil = Python::acquire_gil();
|
let gil = Python::acquire_gil();
|
||||||
let py = gil.python();
|
let py = gil.python();
|
||||||
|
|
||||||
let fail_to_open_file = wrap_pyfunction!(fail_to_open_file)(py);
|
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)) {
|
py_run!(
|
||||||
Ok(()) => panic!("Call should raise a FileNotFoundError"),
|
py,
|
||||||
Err(e) => {
|
fail_to_open_file,
|
||||||
py_assert!(py, e, "isinstance(e, FileNotFoundError)");
|
r#"
|
||||||
py_assert!(py, e, "'No such file or directory (os error 2)' == str(e)");
|
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<CustomError> 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!"
|
||||||
|
"#
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue