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