-
Notifications
You must be signed in to change notification settings - Fork 0
/
result.rs
96 lines (81 loc) · 2.7 KB
/
result.rs
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use crate::core::{Expectation, ExpectationChain};
use std::fmt::Debug;
/// Expectation extension for working with [Result]s.
pub trait ResultExpectationsExt<'a, T, E> {
/// Asserts that the tested [Result] is `Ok(..)`.
fn to_be_ok(self) -> ExpectationChain<'a, Result<T, E>>;
/// Asserts that the tested [Result] is `Err(..)`.
fn to_be_err(self) -> ExpectationChain<'a, Result<T, E>>;
}
impl<'a, T, E> ResultExpectationsExt<'a, T, E> for ExpectationChain<'a, Result<T, E>> {
fn to_be_ok(self) -> ExpectationChain<'a, Result<T, E>> {
self.expecting(ExpectResultOk {})
}
fn to_be_err(self) -> ExpectationChain<'a, Result<T, E>> {
self.expecting(ExpectResultErr {})
}
}
struct ExpectResultOk {}
impl<T, E> Expectation<Result<T, E>> for ExpectResultOk {
fn test(&self, actual: &Result<T, E>) -> bool {
actual.is_ok()
}
fn message(&self, expression: &str, _actual: &Result<T, E>) -> String {
format!("Expected Result {}\n to be Ok(..).", expression)
}
}
struct ExpectResultErr {}
impl<T, E> Expectation<Result<T, E>> for ExpectResultErr {
fn test(&self, actual: &Result<T, E>) -> bool {
actual.is_err()
}
fn message(&self, expression: &str, _actual: &Result<T, E>) -> String {
format!("Expected Result {}\n to be Err(..).", expression)
}
}
/// Expectation extension to assert the contents of an [Result] if the
/// contained `Ok` type is [Debug] and [PartialEq].
pub trait ResultOkExpectationsExt<'a, T, E>
where
T: Debug + PartialEq,
{
fn to_be_ok_with(self, expected: &'a T) -> ExpectationChain<'a, Result<T, E>>;
}
impl<'a, T, E> ResultOkExpectationsExt<'a, T, E> for ExpectationChain<'a, Result<T, E>>
where
T: Debug + PartialEq,
{
fn to_be_ok_with(self, expected: &'a T) -> ExpectationChain<'a, Result<T, E>> {
self.expecting(ExpectResultOkWith { item: expected })
}
}
struct ExpectResultOkWith<'a, T>
where
T: Debug + PartialEq,
{
item: &'a T,
}
impl<'a, T, E> Expectation<Result<T, E>> for ExpectResultOkWith<'a, T>
where
T: Debug + PartialEq,
{
fn test(&self, actual: &Result<T, E>) -> bool {
actual
.as_ref()
.map_or(false, |contained| contained == self.item)
}
fn message(&self, expression: &str, actual: &Result<T, E>) -> String {
actual.as_ref().map_or(
format!(
"Expected Result {}\n to be Ok({:?})\n but was Err",
expression, self.item
),
|contained| {
format!(
"Expected Result {}\n to be Ok({:?})\n but was Ok({:?})",
expression, self.item, contained
)
},
)
}
}