asserting/order/
mod.rs

1//! Implementation of order assertions.
2
3use crate::assertions::AssertOrder;
4use crate::expectations::{IsAtLeast, IsAtMost, IsGreaterThan, IsLessThan};
5use crate::spec::{Expectation, Expression, FailingStrategy, Spec};
6use crate::std::fmt::Debug;
7#[cfg(not(feature = "std"))]
8use alloc::{format, string::String};
9
10impl<S, E, R> AssertOrder<E> for Spec<'_, S, R>
11where
12    S: PartialOrd<E> + Debug,
13    E: Debug,
14    R: FailingStrategy,
15{
16    fn is_less_than(self, expected: E) -> Self {
17        self.expecting(IsLessThan { expected })
18    }
19
20    fn is_greater_than(self, expected: E) -> Self {
21        self.expecting(IsGreaterThan { expected })
22    }
23
24    fn is_at_most(self, expected: E) -> Self {
25        self.expecting(IsAtMost { expected })
26    }
27
28    fn is_at_least(self, expected: E) -> Self {
29        self.expecting(IsAtLeast { expected })
30    }
31}
32
33impl<S, E> Expectation<S> for IsLessThan<E>
34where
35    S: PartialOrd<E> + Debug,
36    E: Debug,
37{
38    fn test(&mut self, subject: &S) -> bool {
39        subject < &self.expected
40    }
41
42    fn message(&self, expression: Expression<'_>, actual: &S) -> String {
43        format!(
44            "expected {expression} is less than {:?}\n   but was: {actual:?}\n  expected: < {:?}",
45            self.expected, self.expected,
46        )
47    }
48}
49
50impl<S, E> Expectation<S> for IsAtMost<E>
51where
52    S: PartialOrd<E> + Debug,
53    E: Debug,
54{
55    fn test(&mut self, subject: &S) -> bool {
56        subject <= &self.expected
57    }
58
59    fn message(&self, expression: Expression<'_>, actual: &S) -> String {
60        format!(
61            "expected {expression} is at most {:?}\n   but was: {actual:?}\n  expected: <= {:?}",
62            self.expected, self.expected,
63        )
64    }
65}
66
67impl<S, E> Expectation<S> for IsGreaterThan<E>
68where
69    S: PartialOrd<E> + Debug,
70    E: Debug,
71{
72    fn test(&mut self, subject: &S) -> bool {
73        subject > &self.expected
74    }
75
76    fn message(&self, expression: Expression<'_>, actual: &S) -> String {
77        format!(
78            "expected {expression} is greater than {:?}\n   but was: {actual:?}\n  expected: > {:?}",
79            self.expected, self.expected,
80        )
81    }
82}
83
84impl<S, E> Expectation<S> for IsAtLeast<E>
85where
86    S: PartialOrd<E> + Debug,
87    E: Debug,
88{
89    fn test(&mut self, subject: &S) -> bool {
90        subject >= &self.expected
91    }
92
93    fn message(&self, expression: Expression<'_>, actual: &S) -> String {
94        format!(
95            "expected {expression} is at least {:?}\n   but was: {actual:?}\n  expected: >= {:?}",
96            self.expected, self.expected,
97        )
98    }
99}
100
101#[cfg(test)]
102mod tests;