Skip to content

Commit b2543ab

Browse files
bjacotgcopybara-github
authored andcommitted
Reimplement explain_match in SizeMatcher.
This allows to explicitly state the size of the container and call the inner matcher explain_match. PiperOrigin-RevId: 521432225
1 parent f43e4ba commit b2543ab

File tree

1 file changed

+53
-2
lines changed

1 file changed

+53
-2
lines changed

googletest/src/matchers/size_matcher.rs

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use crate as googletest;
1818
use crate::matchers::count_elements::count_elements;
1919
#[cfg(google3)]
2020
use count_elements::count_elements;
21-
use googletest::matcher::{Matcher, MatcherResult};
21+
use googletest::matcher::{MatchExplanation, Matcher, MatcherResult};
2222
use std::fmt::Debug;
2323

2424
/// Matches a container whose size matches `expected`.
@@ -70,6 +70,15 @@ where
7070
}
7171
}
7272
}
73+
74+
fn explain_match(&self, actual: &T) -> MatchExplanation {
75+
let actual_size = count_elements(actual);
76+
MatchExplanation::create(format!(
77+
"which has size {}, {}",
78+
actual_size,
79+
self.expected.explain_match(&actual_size)
80+
))
81+
}
7382
}
7483

7584
#[cfg(test)]
@@ -80,7 +89,8 @@ mod tests {
8089
#[cfg(not(google3))]
8190
use googletest::matchers;
8291
use googletest::{google_test, verify_that, Result};
83-
use matchers::eq;
92+
use indoc::indoc;
93+
use matchers::{contains_substring, displays_as, eq, err};
8494
use std::collections::{
8595
BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque,
8696
};
@@ -157,4 +167,45 @@ mod tests {
157167
let value = VecDeque::from([1, 2, 3]);
158168
verify_that!(value, size(eq(3)))
159169
}
170+
171+
#[google_test]
172+
fn size_matcher_explain_match() -> Result<()> {
173+
struct TestMatcher;
174+
impl<T: Debug> Matcher<T> for TestMatcher {
175+
fn matches(&self, _: &T) -> MatcherResult {
176+
false.into()
177+
}
178+
179+
fn describe(&self, _: MatcherResult) -> String {
180+
"called described".into()
181+
}
182+
183+
fn explain_match(&self, _: &T) -> MatchExplanation {
184+
MatchExplanation::create("called explain_match".into())
185+
}
186+
}
187+
verify_that!(
188+
size(TestMatcher {}).explain_match(&[1, 2, 3]),
189+
displays_as(eq("which has size 3, called explain_match"))
190+
)
191+
}
192+
193+
#[google_test]
194+
fn size_matcher_error_message() -> Result<()> {
195+
let result = verify_that!(vec![1, 2, 3, 4], size(eq(3)));
196+
verify_that!(
197+
result,
198+
err(displays_as(contains_substring(indoc!(
199+
"
200+
Value of: vec![1, 2, 3, 4]
201+
Expected: has size, which is equal to 3
202+
Actual: [
203+
1,
204+
2,
205+
3,
206+
4,
207+
], which has size 4, which isn't equal to 3"
208+
))))
209+
)
210+
}
160211
}

0 commit comments

Comments
 (0)