fluent_assertions/assertions/
string_assertion.rs1use crate::Assertion;
2
3impl<T: AsRef<str>> Assertion<T> {
5 pub fn be_empty(&self) -> &Self {
7 assert!(
8 self.value.as_ref().is_empty(),
9 "Expected string to be empty, but got '{}'",
10 self.value.as_ref()
11 );
12 self
13 }
14 pub fn not_be_empty(&self) -> &Self {
16 assert!(
17 !self.value.as_ref().is_empty(),
18 "Expected string to not be empty, but got empty string"
19 );
20 self
21 }
22 pub fn start_with(&self, prefix: &str) -> &Self {
24 assert!(
25 self.value.as_ref().starts_with(prefix),
26 "Expected string to start with '{}', but it started with '{}'",
27 prefix,
28 &self.value.as_ref()[0..prefix.len()]
29 );
30 self
31 }
32 pub fn end_with(&self, suffix: &str) -> &Self {
34 assert!(
35 self.value.as_ref().ends_with(suffix),
36 "Expected string to end with '{}', but it ended with '{}'",
37 suffix,
38 &self.value.as_ref()[self.value.as_ref().len() - suffix.len()..]
39 );
40 self
41 }
42
43 pub fn contain(&self, substring: &str) -> &Self {
45 assert!(
46 self.value.as_ref().contains(substring),
47 "Expected string to contain '{}', but it didn't",
48 substring
49 );
50 self
51 }
52
53 pub fn have_length(&self, length: usize) -> &Self {
55 assert!(
56 self.value.as_ref().len() == length,
57 "Expected string to have length {}, but it had length {}",
58 length,
59 self.value.as_ref().len()
60 );
61 self
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use crate::assertions::*;
68 use rstest::*;
69
70 #[test]
71 fn test_str_assertions() {
72 let actual = "ABCDEFGHI";
73 actual
74 .should()
75 .start_with("AB")
76 .end_with("HI")
77 .contain("EF")
78 .have_length(9);
79 }
80
81 #[test]
82 fn test_string_assertions() {
83 let actual_string = "ABCDEFGHI".to_string();
84 actual_string
85 .should()
86 .start_with("AB")
87 .end_with("HI")
88 .contain("EF")
89 .have_length(9);
90 }
91
92 #[rstest]
93 #[case(String::default())]
94 #[case(String::from(""))]
95 #[case("".to_string())]
96 fn should_be_empty(#[case] input: String) {
97 input.should().be_empty();
98 }
99
100 #[rstest]
101 #[case(String::from("hello"))]
102 #[case("42".to_string())]
103 fn should_not_be_empty(#[case] input: String) {
104 input.should().not_be_empty();
105 }
106
107 #[rstest]
108 #[case("hello")]
109 #[case("42")]
110 fn should_be(#[case] input: &str) {
111 input.should().be(input);
112 }
113}