Skip to content

Commit cbd6ed7

Browse files
hovinenbcopybara-github
authored andcommitted
Support the use of a lambda expression as argument to the pointwise! macro.
This allows a kind of "currying" where a multi-argument matcher can be constructed with additional data: ``` verify_that!(value, pointwise!(|v| near(v, 0.001), [1.0, 2.0, 3.0])) ``` PiperOrigin-RevId: 523967340
1 parent af51fbb commit cbd6ed7

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

googletest/src/matchers/pointwise_matcher.rs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@
2929
/// verify_that!(value, pointwise!(le, [1, 1, 3]))?; // Fails
3030
/// ```
3131
///
32+
/// One can also use a closure which returns a matcher:
33+
///
34+
/// ```
35+
/// let value = vec![1.00001, 2.000001, 3.00001];
36+
/// verify_that!(value, pointwise!(|v| near(v, 0.001), [1.0, 2.0, 3.0]))?;
37+
/// ```
38+
///
3239
/// The actual value must be a container implementing [`IntoIterator`]. This
3340
/// includes standard containers, slices (when dereferenced) and arrays.
3441
///
@@ -56,12 +63,12 @@
5663
#[macro_export]
5764
macro_rules! pointwise {
5865
($matcher:expr, $container:expr) => {{
59-
#[cfg(google3)]
60-
use $crate::internal::PointwiseMatcher;
61-
#[cfg(not(google3))]
62-
use $crate::matchers::pointwise_matcher::internal::PointwiseMatcher;
63-
PointwiseMatcher::new($container.into_iter().map(|t| $matcher(t)).collect())
64-
}};
66+
#[cfg(google3)]
67+
use $crate::internal::PointwiseMatcher;
68+
#[cfg(not(google3))]
69+
use $crate::matchers::pointwise_matcher::internal::PointwiseMatcher;
70+
PointwiseMatcher::new($container.into_iter().map($matcher).collect())
71+
}};
6572
}
6673

6774
/// Module for use only by the procedural macros in this module.

googletest/tests/pointwise_matcher_test.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use googletest::{google_test, verify_that, Result};
2020
use indoc::indoc;
2121
#[cfg(google3)]
2222
use matchers::pointwise;
23-
use matchers::{contains_substring, displays_as, eq, err, lt, not};
23+
use matchers::{contains_substring, displays_as, eq, err, lt, near, not};
2424

2525
#[google_test]
2626
fn pointwise_matches_single_element() -> Result<()> {
@@ -166,3 +166,9 @@ fn pointwise_returns_mismatch_when_actual_value_does_not_match_on_first_and_seco
166166
))))
167167
)
168168
}
169+
170+
#[google_test]
171+
fn pointwise_matches_single_element_with_lambda_expression_with_extra_value() -> Result<()> {
172+
let value = vec![1.00001f32];
173+
verify_that!(value, pointwise!(|v| near(v, 0.0001), vec![1.0]))
174+
}

0 commit comments

Comments
 (0)