1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
use core::error::{Request, request_ref, request_value};
// Test the `Request` API.
#[derive(Debug)]
struct SomeConcreteType {
some_string: String,
}
impl std::fmt::Display for SomeConcreteType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "A")
}
}
impl std::error::Error for SomeConcreteType {
fn provide<'a>(&'a self, request: &mut Request<'a>) {
request
.provide_ref::<String>(&self.some_string)
.provide_ref::<str>(&self.some_string)
.provide_value_with::<String>(|| "bye".to_owned());
}
}
// Test the Error.provide and request mechanisms with a by-reference trait object.
#[test]
fn test_error_generic_member_access() {
let obj = &SomeConcreteType { some_string: "hello".to_owned() };
assert_eq!(request_ref::<String>(&*obj).unwrap(), "hello");
assert_eq!(request_value::<String>(&*obj).unwrap(), "bye");
assert_eq!(request_value::<u8>(&obj), None);
}
// Test the Error.provide and request mechanisms with a by-reference trait object.
#[test]
fn test_request_constructor() {
let obj: &dyn std::error::Error = &SomeConcreteType { some_string: "hello".to_owned() };
assert_eq!(request_ref::<String>(&*obj).unwrap(), "hello");
assert_eq!(request_value::<String>(&*obj).unwrap(), "bye");
assert_eq!(request_value::<u8>(&obj), None);
}
// Test the Error.provide and request mechanisms with a boxed trait object.
#[test]
fn test_error_generic_member_access_boxed() {
let obj: Box<dyn std::error::Error> =
Box::new(SomeConcreteType { some_string: "hello".to_owned() });
assert_eq!(request_ref::<String>(&*obj).unwrap(), "hello");
assert_eq!(request_value::<String>(&*obj).unwrap(), "bye");
// NOTE: Box<E> only implements Error when E: Error + Sized, which means we can't pass a
// Box<dyn Error> to request_value.
//assert_eq!(request_value::<String>(&obj).unwrap(), "bye");
}
// Test the Error.provide and request mechanisms with a concrete object.
#[test]
fn test_error_generic_member_access_concrete() {
let obj = SomeConcreteType { some_string: "hello".to_owned() };
assert_eq!(request_ref::<String>(&obj).unwrap(), "hello");
assert_eq!(request_value::<String>(&obj).unwrap(), "bye");
assert_eq!(request_value::<u8>(&obj), None);
}
|