easy_assert/option_assertions.rs
1//! ## Usage
2//!
3//! ``` rust
4//!
5//!use easy_assert::{expected, expected_vec};
6//!use easy_assert::option_assertions::OptionAssert;
7//!
8//!#[test]
9//!pub fn none_is_none() {
10//! OptionAssert::<&str>::assert_that(None).is_none();
11//!}
12//!
13//!#[test]
14//!#[should_panic]
15//!pub fn some_is_not_none() {
16//! OptionAssert::assert_that(Some("a")).is_none();
17//!}
18//!
19//!#[test]
20//!#[should_panic]
21//!pub fn does_not_contains_value() {
22//! OptionAssert::assert_that(Some(1))
23//! .contains()
24//! .value()
25//! .matches_by(|a,b| a==b)
26//! .to(expected(2));
27//!}
28//!
29//!
30//!#[test]
31//!pub fn contains_vec() {
32//! OptionAssert::assert_that(Some(vec!['a','b','c']))
33//! .contains()
34//! .list()
35//! .with_element_matcher(|a,b| a==b)
36//! .is_equal_to(expected_vec(vec!['a','b','c']))
37//! .in_order();
38//!}
39//!
40//!#[test]
41//!#[should_panic]
42//!pub fn does_not_contains_vec() {
43//! OptionAssert::assert_that(Some(vec!['a','b','c']))
44//! .contains()
45//! .list()
46//! .with_element_matcher(|a,b| a==b)
47//! .is_equal_to(expected_vec(vec!['a','b','d']))
48//! .in_order();
49//!}
50//!
51//!#[test]
52//!#[should_panic]
53//!pub fn contains_for_none_will_raise_error() {
54//! OptionAssert::<i32>::assert_that(None)
55//! .contains()
56//! .value()
57//! .matches_by(|a,b| a==b)
58//! .to(expected(2));
59//!}
60//!
61//! ```
62
63use crate::assertions::OptionCheck;
64use crate::custom_assertions::CustomAssert;
65use crate::list_assertions::ListAssert;
66use crate::{actual, actual_vec, test_failed};
67use core::fmt::Display;
68
69pub struct OptionAssert<T> {
70 actual: Option<T>,
71}
72
73impl<T: 'static> OptionAssert<T> {
74 pub fn assert_that(actual: Option<T>) -> OptionAssert<T> {
75 OptionAssert { actual }
76 }
77
78 pub fn is_none(&self) {
79 OptionCheck::is_none(self)
80 }
81
82 pub fn is_some(&self) {
83 OptionCheck::is_some(self)
84 }
85
86 pub fn contains(self) -> ElementMatcher<T> {
87 ElementMatcher {
88 actual: self.actual.expect("\n Actual: is None, but should be Some"),
89 }
90 }
91}
92
93impl<T: 'static> OptionCheck for OptionAssert<T> {
94 fn is_none(&self) {
95 if self.actual.is_some() {
96 test_failed("Actual is Some, but should be None");
97 }
98 }
99
100 fn is_some(&self) {
101 if self.actual.is_none() {
102 test_failed("Actual: is None, but should be Some");
103 }
104 }
105}
106
107pub struct ElementMatcher<T> {
108 actual: T,
109}
110
111impl<T> ElementMatcher<Vec<T>>
112where
113 T: Display + 'static,
114{
115 pub fn list(self) -> ListAssert<T> {
116 ListAssert::assert_that(actual_vec(self.actual))
117 }
118}
119
120impl<T> ElementMatcher<T>
121where
122 T: Display + 'static,
123{
124 pub fn value(self) -> CustomAssert<T> {
125 CustomAssert::assert_that(actual(self.actual))
126 }
127}