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
use crate::{CheckResult, Expectation, ExpectationBuilder};
use std::fmt::Debug;
/// Extension trait for equality expectations
pub trait EqualityExpectations<T, U> {
/// Expect the value to equal another value
/// ```
/// # use rxpect::expect;
/// # use rxpect::expectations::EqualityExpectations;
///
/// let a = "foo";
/// let b = "foo";
/// expect(a).to_equal(b);
/// ```
///
/// It works with differing types as well, as long as `T: Eq<U>` holds true
/// ```
/// # use rxpect::expect;
/// # use rxpect::expectations::EqualityExpectations;
///
/// let a = "foo".to_string();
/// let b = "foo";
/// expect(a).to_equal(b);
/// ```
/// asserts that `b.eq(a)` is true
fn to_equal(self, value: U) -> Self;
}
impl<'e, T, U, B> EqualityExpectations<T, U> for B
where
T: PartialEq<U> + Debug + 'e,
U: Debug + 'e,
B: ExpectationBuilder<'e, Value = T>,
{
fn to_equal(self, value: U) -> Self {
self.to_pass(ToEqualExpectation(value))
}
}
/// Expectation for to_equal
struct ToEqualExpectation<U>(U);
impl<T, U> Expectation<T> for ToEqualExpectation<U>
where
T: PartialEq<U> + Debug,
U: Debug,
{
fn check(&self, value: &T) -> CheckResult {
if value.eq(&self.0) {
CheckResult::Pass
} else {
CheckResult::Fail(format!(
"Expectation failed (expected == actual)\nexpected: `{:?}`\n actual: `{:?}`",
&self.0, value
))
}
}
}
#[cfg(test)]
mod tests {
use super::EqualityExpectations;
use crate::expect;
use rstest::rstest;
use std::fmt::Debug;
#[rstest]
#[case(1, 1)]
#[case("&str", "&str")]
#[case("String".to_string(), "String".to_string())]
#[case("String and &str".to_string(), "String and &str")]
pub fn that_to_equal_accepts_equal_values<T, U>(#[case] a: T, #[case] b: U)
where
T: PartialEq<U> + Debug,
U: Debug,
{
// Expect the two values to be equal
expect(a).to_equal(b);
}
#[test]
#[should_panic]
pub fn that_to_equal_does_not_accept_unequal_values() {
// Given a value that implements PartialEq
let value = 1;
// Expect the to_equal expectation to fail with an identical value
expect(value).to_equal(2);
}
}