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
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
use std::fmt::Debug;

pub struct Assert<T> {
    actual: T,
}

/// Entry point for the [Assert] DSL.
///
/// [Assert] provides a fluent API for assertions. An [Assert] holds
/// the `actual` value that can be used in assertion statements.
///
/// ```
/// # use assert4rs::{Assert, AssertEquals};
/// Assert::that(3).is(3);
/// ```
impl<T> Assert<T> {
    /// Create an [Assert] instance for the `actual` value.
    ///
    /// All assertions start with `Assert::that(actual)`.
    pub fn that(actual: T) -> Self {
        Assert { actual }
    }

    /// Maps the `actual` value using lambda `f`.
    ///
    /// This method is intended to map the actual value in order to
    /// apply further assertions.
    ///
    /// ```
    /// # use assert4rs::{Assert, AssertEquals};
    /// Assert::that("3")
    ///     .map(|v| v.parse::<i32>().unwrap())
    ///     .is(3);
    /// ```
    pub fn map<R>(self, f: impl Fn(T) -> R) -> Assert<R> {
        Assert::that(f(self.actual))
    }
}

/// Used to assert equality or inequality of some value with `self`.
///
/// It takes ownership of self and returns ownership back so that
/// assertions can be chained in fluent manner.
///
/// Like in the following example:
///
/// ```
/// # use assert4rs::{Assert, AssertEquals};
/// Assert::that("foo")
///     .is("foo")
///     .is_not("bar");
/// ```
///
/// When implementing this trait, panic when the assertion fails.
///
/// For example the following code should panic:
///
/// ```should_panic
/// # use assert4rs::{Assert, AssertEquals};
/// Assert::that("foo").is("bar");
/// ```
pub trait AssertEquals<R> {
    /// Assert that `self` is equal to the `expected` value.
    fn is(self, expected: R) -> Self;
    /// Assert that `self` is not equal to the `other` value.
    fn is_not(self, other: R) -> Self;
}

/// Default implementation of [AssertEquals].
impl<T, R> AssertEquals<R> for Assert<T>
where
    T: PartialEq<R> + Debug,
    R: Debug,
{
    fn is(self, expected: R) -> Self {
        assert!(
            self.actual == expected,
            "Assertion failed: `(actual == expected)`
  Actual:   `{:?}`
  Expected: `{:?}`",
            self.actual,
            expected,
        );
        self
    }

    fn is_not(self, other: R) -> Self {
        assert!(
            self.actual != other,
            "Assertion failed: `(actual != other)`
  Actual:   `{:?}`
  Other:    `{:?}`",
            self.actual,
            other,
        );
        self
    }
}

/// DSL for [Option] assertions.
impl<T> Assert<Option<T>>
where
    T: PartialEq + Debug,
{
    /// Assert that `actual` is equal to [Some] `expected' value.
    pub fn is_some(self, expected: T) -> Self {
        self.is(Some(expected))
    }

    /// Assert that `actual` is equal to [None].
    pub fn is_none(self) -> Self {
        self.is(None)
    }

    /// Unwrap the [Option] value, panic for [None].
    pub fn unwrap(self) -> Assert<T> {
        match self.actual {
            Some(value) => Assert::that(value),
            None => panic!(
                "Assertion failed: `(actual == Some(expected)`
  Actual:   `None`"
            ),
        }
    }
}

/// [Assert] DSL for [Vec].
impl<T> Assert<Vec<T>>
where
    T: PartialEq + Debug,
{
    /// Assert that the actual vector contains a specific `expected`
    /// value.
    ///
    /// ```
    /// # use assert4rs::Assert;
    /// Assert::that(vec![1, 2, 3]).contains(2);
    /// ```
    pub fn contains(self, expected: T) -> Self {
        assert!(
            self.actual.contains(&expected),
            "Assertion failed: `(actual.contains(expected))`
  Actual:   `{:?}`
  Expected: `{:?}`",
            self.actual,
            expected
        );
        self
    }

    /// Returns an [Assert] for a value from the [Vec].
    ///
    /// ```
    /// # use assert4rs::Assert;
    /// Assert::that(vec!['a', 'b', 'c']).get(1).is_some('b');
    /// Assert::that(vec!['a', 'b', 'c']).get(5).is_none();
    /// ```
    pub fn get(&mut self, index: usize) -> Assert<Option<T>> {
        match self.actual.get(index) {
            None => Assert::that(None),
            Some(_) => Assert::that(Some(self.actual.swap_remove(index))),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_succeeds_for_equal_values() {
        Assert::that(2).is(2);
    }

    #[test]
    fn is_succeeds_for_equal_string_values() {
        Assert::that(String::from("2")).is(String::from("2"));
    }

    #[test]
    fn is_succeeds_for_equal_string_and_string_slice() {
        Assert::that(String::from("2")).is("2");
    }

    #[test]
    #[should_panic(expected = "Assertion failed: `(actual == expected)`
  Actual:   `2`
  Expected: `3`")]
    fn is_panics_for_different_values() {
        Assert::that(2).is(3);
    }

    #[test]
    #[should_panic(expected = "Assertion failed: `(actual != other)`
  Actual:   `2`
  Other:    `2`")]
    fn is_not_panics_for_equal_values() {
        Assert::that(2).is_not(2);
    }

    #[test]
    fn is_not_succeeds_for_different_values() {
        Assert::that(2).is_not(3);
    }

    #[test]
    fn map_converts_assertion_pass() {
        Assert::that(2).map(|v| v + 2).is(4);
    }

    #[test]
    #[should_panic(expected = "Assertion failed: `(actual == expected)`
  Actual:   `4`
  Expected: `3`")]
    fn map_converts_assertion_fail() {
        Assert::that(2).map(|v| v + 2).is(3);
    }

    #[test]
    fn option_is_some_succeeds_for_equal_values() {
        Assert::that(Some(2)).is_some(2);
    }

    #[test]
    fn option_unwrap_successfully_unwraps_some_value() {
        Assert::that(Some(2)).unwrap().is(2);
    }

    #[test]
    #[should_panic(expected = "Assertion failed: `(actual == Some(expected)`
  Actual:   `None`")]
    fn option_unwrap_panics_for_none() {
        let i: Option<i32> = None;
        Assert::that(i).unwrap();
    }

    #[test]
    #[should_panic(expected = "Assertion failed: `(actual == expected)`
  Actual:   `None`
  Expected: `Some(2)`")]
    fn option_is_some_panics_for_none() {
        Assert::that(None).is_some(2);
    }

    #[test]
    fn option_is_none_succeeds_for_none() {
        let i: Option<i32> = None;
        Assert::that(i).is_none();
    }

    #[test]
    #[should_panic(expected = "Assertion failed: `(actual == expected)`
  Actual:   `Some(2)`
  Expected: `None`")]
    fn option_is_none_panics_for_some() {
        Assert::that(Some(2)).is_none();
    }
}