1use crate::assertions::{AssertHasValue, AssertOption, AssertOptionValue};
4use crate::expectations::{HasValue, IsNone, IsSome};
5use crate::spec::{Expectation, Expression, FailingStrategy, Spec, Unknown};
6use crate::std::fmt::Debug;
7#[cfg(not(feature = "std"))]
8use alloc::{format, string::String};
9
10impl<S, R> AssertOption for Spec<'_, Option<S>, R>
11where
12 S: Debug,
13 R: FailingStrategy,
14{
15 fn is_some(self) -> Self {
16 self.expecting(IsSome)
17 }
18
19 fn is_none(self) -> Self {
20 self.expecting(IsNone)
21 }
22}
23
24impl<'a, T, R> AssertOptionValue<'a, T, R> for Spec<'a, Option<T>, R>
25where
26 R: FailingStrategy,
27{
28 fn some(self) -> Spec<'a, T, R> {
29 self.mapping(|subject| match subject {
30 None => {
31 panic!("assertion failed: expected the subject to be `Some(_)`, but was `None`")
32 },
33 Some(value) => value,
34 })
35 }
36}
37
38impl<S, E, R> AssertHasValue<E> for Spec<'_, Option<S>, R>
39where
40 S: PartialEq<E> + Debug,
41 E: Debug,
42 R: FailingStrategy,
43{
44 fn has_value(self, expected: E) -> Self {
45 self.expecting(HasValue { expected })
46 }
47}
48
49impl<T> Expectation<Option<T>> for IsSome
50where
51 T: Debug,
52{
53 fn test(&mut self, subject: &Option<T>) -> bool {
54 subject.is_some()
55 }
56
57 fn message(&self, expression: Expression<'_>, actual: &Option<T>) -> String {
58 format!(
59 "expected {expression} is {:?}\n but was: {actual:?}\n expected: {:?}",
60 Some(Unknown),
61 Some(Unknown)
62 )
63 }
64}
65
66impl<T> Expectation<Option<T>> for IsNone
67where
68 T: Debug,
69{
70 fn test(&mut self, subject: &Option<T>) -> bool {
71 subject.is_none()
72 }
73
74 fn message(&self, expression: Expression<'_>, actual: &Option<T>) -> String {
75 format!(
76 "expected {expression} is {:?}\n but was: {actual:?}\n expected: {:?}",
77 None::<Unknown>, None::<Unknown>
78 )
79 }
80}
81
82impl<T, E> Expectation<Option<T>> for HasValue<E>
83where
84 T: PartialEq<E> + Debug,
85 E: Debug,
86{
87 fn test(&mut self, subject: &Option<T>) -> bool {
88 subject
89 .as_ref()
90 .is_some_and(|value| value == &self.expected)
91 }
92
93 fn message(&self, expression: Expression<'_>, actual: &Option<T>) -> String {
94 format!("expected {expression} is some containing {:?}\n but was: {actual:?}\n expected: {:?}",
95 &self.expected,
96 Some(&self.expected),
97 )
98 }
99}
100
101#[cfg(test)]
102mod tests;