0
0
mirror of https://github.com/google/googletest.git synced 2025-03-20 10:53:47 +00:00
Zhanyong Wan 0bdccf4aa2 Add a DistanceFrom() matcher for general distance comparison.
We have a bunch of matchers for asserting that a value is near the target value, e.g.
`DoubleNear()` and `FloatNear()`. These matchers only work for specific types (`double` and `float`). They are not flexible enough to support other types that have the notion of a "distance" (e.g. N-dimensional points and vectors, which are commonly used in ML).

In this diff, we generalize the idea to a `DistanceFrom(target, get_distance, m)` matcher that works on arbitrary types that have the "distance" concept (the `get_distance` argument is optional and can be omitted for types that support `-`, and `std::abs()`). What it does:

1. compute the distance between the value and the target using `get_distance(value, target)`; if `get_distance` is omitted, compute the distance as `std::abs(value - target)`.
2. match the distance against matcher `m`; if the match succeeds, the `DistanceFrom()` match succeeds.

Examples:

```
  // 0.5's distance from 0.6 should be <= 0.2.
  EXPECT_THAT(0.5, DistanceFrom(0.6, Le(0.2)));

  Vector2D v1(3.0, 4.0), v2(3.2, 6.0);
  // v1's distance from v2, as computed by EuclideanDistance(v1, v2),
  // should be >= 1.0.
  EXPECT_THAT(v1, DistanceFrom(v2, EuclideanDistance, Ge(1.0)));
```

PiperOrigin-RevId: 734593292
Change-Id: Id6bb7074dc4aa4d8abd78b57ad2426637e590de5
2025-03-07 09:54:00 -08:00
..
2023-04-20 14:29:09 -07:00
2024-07-23 03:57:23 -07:00
2025-02-12 09:44:07 -08:00
2025-02-10 10:22:27 -08:00
2024-08-29 08:17:22 -07:00
2025-02-12 09:44:07 -08:00