| 1 | // Copyright 2007, Google Inc. |
| 2 | // All rights reserved. |
| 3 | // |
| 4 | // Redistribution and use in source and binary forms, with or without |
| 5 | // modification, are permitted provided that the following conditions are |
| 6 | // met: |
| 7 | // |
| 8 | // * Redistributions of source code must retain the above copyright |
| 9 | // notice, this list of conditions and the following disclaimer. |
| 10 | // * Redistributions in binary form must reproduce the above |
| 11 | // copyright notice, this list of conditions and the following disclaimer |
| 12 | // in the documentation and/or other materials provided with the |
| 13 | // distribution. |
| 14 | // * Neither the name of Google Inc. nor the names of its |
| 15 | // contributors may be used to endorse or promote products derived from |
| 16 | // this software without specific prior written permission. |
| 17 | // |
| 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | |
| 30 | // Google Mock - a framework for writing C++ mock classes. |
| 31 | // |
| 32 | // The MATCHER* family of macros can be used in a namespace scope to |
| 33 | // define custom matchers easily. |
| 34 | // |
| 35 | // Basic Usage |
| 36 | // =========== |
| 37 | // |
| 38 | // The syntax |
| 39 | // |
| 40 | // MATCHER(name, description_string) { statements; } |
| 41 | // |
| 42 | // defines a matcher with the given name that executes the statements, |
| 43 | // which must return a bool to indicate if the match succeeds. Inside |
| 44 | // the statements, you can refer to the value being matched by 'arg', |
| 45 | // and refer to its type by 'arg_type'. |
| 46 | // |
| 47 | // The description string documents what the matcher does, and is used |
| 48 | // to generate the failure message when the match fails. Since a |
| 49 | // MATCHER() is usually defined in a header file shared by multiple |
| 50 | // C++ source files, we require the description to be a C-string |
| 51 | // literal to avoid possible side effects. It can be empty, in which |
| 52 | // case we'll use the sequence of words in the matcher name as the |
| 53 | // description. |
| 54 | // |
| 55 | // For example: |
| 56 | // |
| 57 | // MATCHER(IsEven, "") { return (arg % 2) == 0; } |
| 58 | // |
| 59 | // allows you to write |
| 60 | // |
| 61 | // // Expects mock_foo.Bar(n) to be called where n is even. |
| 62 | // EXPECT_CALL(mock_foo, Bar(IsEven())); |
| 63 | // |
| 64 | // or, |
| 65 | // |
| 66 | // // Verifies that the value of some_expression is even. |
| 67 | // EXPECT_THAT(some_expression, IsEven()); |
| 68 | // |
| 69 | // If the above assertion fails, it will print something like: |
| 70 | // |
| 71 | // Value of: some_expression |
| 72 | // Expected: is even |
| 73 | // Actual: 7 |
| 74 | // |
| 75 | // where the description "is even" is automatically calculated from the |
| 76 | // matcher name IsEven. |
| 77 | // |
| 78 | // Argument Type |
| 79 | // ============= |
| 80 | // |
| 81 | // Note that the type of the value being matched (arg_type) is |
| 82 | // determined by the context in which you use the matcher and is |
| 83 | // supplied to you by the compiler, so you don't need to worry about |
| 84 | // declaring it (nor can you). This allows the matcher to be |
| 85 | // polymorphic. For example, IsEven() can be used to match any type |
| 86 | // where the value of "(arg % 2) == 0" can be implicitly converted to |
| 87 | // a bool. In the "Bar(IsEven())" example above, if method Bar() |
| 88 | // takes an int, 'arg_type' will be int; if it takes an unsigned long, |
| 89 | // 'arg_type' will be unsigned long; and so on. |
| 90 | // |
| 91 | // Parameterizing Matchers |
| 92 | // ======================= |
| 93 | // |
| 94 | // Sometimes you'll want to parameterize the matcher. For that you |
| 95 | // can use another macro: |
| 96 | // |
| 97 | // MATCHER_P(name, param_name, description_string) { statements; } |
| 98 | // |
| 99 | // For example: |
| 100 | // |
| 101 | // MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } |
| 102 | // |
| 103 | // will allow you to write: |
| 104 | // |
| 105 | // EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); |
| 106 | // |
| 107 | // which may lead to this message (assuming n is 10): |
| 108 | // |
| 109 | // Value of: Blah("a") |
| 110 | // Expected: has absolute value 10 |
| 111 | // Actual: -9 |
| 112 | // |
| 113 | // Note that both the matcher description and its parameter are |
| 114 | // printed, making the message human-friendly. |
| 115 | // |
| 116 | // In the matcher definition body, you can write 'foo_type' to |
| 117 | // reference the type of a parameter named 'foo'. For example, in the |
| 118 | // body of MATCHER_P(HasAbsoluteValue, value) above, you can write |
| 119 | // 'value_type' to refer to the type of 'value'. |
| 120 | // |
| 121 | // We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to |
| 122 | // support multi-parameter matchers. |
| 123 | // |
| 124 | // Describing Parameterized Matchers |
| 125 | // ================================= |
| 126 | // |
| 127 | // The last argument to MATCHER*() is a string-typed expression. The |
| 128 | // expression can reference all of the matcher's parameters and a |
| 129 | // special bool-typed variable named 'negation'. When 'negation' is |
| 130 | // false, the expression should evaluate to the matcher's description; |
| 131 | // otherwise it should evaluate to the description of the negation of |
| 132 | // the matcher. For example, |
| 133 | // |
| 134 | // using testing::PrintToString; |
| 135 | // |
| 136 | // MATCHER_P2(InClosedRange, low, hi, |
| 137 | // std::string(negation ? "is not" : "is") + " in range [" + |
| 138 | // PrintToString(low) + ", " + PrintToString(hi) + "]") { |
| 139 | // return low <= arg && arg <= hi; |
| 140 | // } |
| 141 | // ... |
| 142 | // EXPECT_THAT(3, InClosedRange(4, 6)); |
| 143 | // EXPECT_THAT(3, Not(InClosedRange(2, 4))); |
| 144 | // |
| 145 | // would generate two failures that contain the text: |
| 146 | // |
| 147 | // Expected: is in range [4, 6] |
| 148 | // ... |
| 149 | // Expected: is not in range [2, 4] |
| 150 | // |
| 151 | // If you specify "" as the description, the failure message will |
| 152 | // contain the sequence of words in the matcher name followed by the |
| 153 | // parameter values printed as a tuple. For example, |
| 154 | // |
| 155 | // MATCHER_P2(InClosedRange, low, hi, "") { ... } |
| 156 | // ... |
| 157 | // EXPECT_THAT(3, InClosedRange(4, 6)); |
| 158 | // EXPECT_THAT(3, Not(InClosedRange(2, 4))); |
| 159 | // |
| 160 | // would generate two failures that contain the text: |
| 161 | // |
| 162 | // Expected: in closed range (4, 6) |
| 163 | // ... |
| 164 | // Expected: not (in closed range (2, 4)) |
| 165 | // |
| 166 | // Types of Matcher Parameters |
| 167 | // =========================== |
| 168 | // |
| 169 | // For the purpose of typing, you can view |
| 170 | // |
| 171 | // MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } |
| 172 | // |
| 173 | // as shorthand for |
| 174 | // |
| 175 | // template <typename p1_type, ..., typename pk_type> |
| 176 | // FooMatcherPk<p1_type, ..., pk_type> |
| 177 | // Foo(p1_type p1, ..., pk_type pk) { ... } |
| 178 | // |
| 179 | // When you write Foo(v1, ..., vk), the compiler infers the types of |
| 180 | // the parameters v1, ..., and vk for you. If you are not happy with |
| 181 | // the result of the type inference, you can specify the types by |
| 182 | // explicitly instantiating the template, as in Foo<long, bool>(5, |
| 183 | // false). As said earlier, you don't get to (or need to) specify |
| 184 | // 'arg_type' as that's determined by the context in which the matcher |
| 185 | // is used. You can assign the result of expression Foo(p1, ..., pk) |
| 186 | // to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This |
| 187 | // can be useful when composing matchers. |
| 188 | // |
| 189 | // While you can instantiate a matcher template with reference types, |
| 190 | // passing the parameters by pointer usually makes your code more |
| 191 | // readable. If, however, you still want to pass a parameter by |
| 192 | // reference, be aware that in the failure message generated by the |
| 193 | // matcher you will see the value of the referenced object but not its |
| 194 | // address. |
| 195 | // |
| 196 | // Explaining Match Results |
| 197 | // ======================== |
| 198 | // |
| 199 | // Sometimes the matcher description alone isn't enough to explain why |
| 200 | // the match has failed or succeeded. For example, when expecting a |
| 201 | // long string, it can be very helpful to also print the diff between |
| 202 | // the expected string and the actual one. To achieve that, you can |
| 203 | // optionally stream additional information to a special variable |
| 204 | // named result_listener, whose type is a pointer to class |
| 205 | // MatchResultListener: |
| 206 | // |
| 207 | // MATCHER_P(EqualsLongString, str, "") { |
| 208 | // if (arg == str) return true; |
| 209 | // |
| 210 | // *result_listener << "the difference: " |
| 211 | /// << DiffStrings(str, arg); |
| 212 | // return false; |
| 213 | // } |
| 214 | // |
| 215 | // Overloading Matchers |
| 216 | // ==================== |
| 217 | // |
| 218 | // You can overload matchers with different numbers of parameters: |
| 219 | // |
| 220 | // MATCHER_P(Blah, a, description_string1) { ... } |
| 221 | // MATCHER_P2(Blah, a, b, description_string2) { ... } |
| 222 | // |
| 223 | // Caveats |
| 224 | // ======= |
| 225 | // |
| 226 | // When defining a new matcher, you should also consider implementing |
| 227 | // MatcherInterface or using MakePolymorphicMatcher(). These |
| 228 | // approaches require more work than the MATCHER* macros, but also |
| 229 | // give you more control on the types of the value being matched and |
| 230 | // the matcher parameters, which may leads to better compiler error |
| 231 | // messages when the matcher is used wrong. They also allow |
| 232 | // overloading matchers based on parameter types (as opposed to just |
| 233 | // based on the number of parameters). |
| 234 | // |
| 235 | // MATCHER*() can only be used in a namespace scope as templates cannot be |
| 236 | // declared inside of a local class. |
| 237 | // |
| 238 | // More Information |
| 239 | // ================ |
| 240 | // |
| 241 | // To learn more about using these macros, please search for 'MATCHER' |
| 242 | // on |
| 243 | // https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md |
| 244 | // |
| 245 | // This file also implements some commonly used argument matchers. More |
| 246 | // matchers can be defined by the user implementing the |
| 247 | // MatcherInterface<T> interface if necessary. |
| 248 | // |
| 249 | // See googletest/include/gtest/gtest-matchers.h for the definition of class |
| 250 | // Matcher, class MatcherInterface, and others. |
| 251 | |
| 252 | // IWYU pragma: private, include "gmock/gmock.h" |
| 253 | // IWYU pragma: friend gmock/.* |
| 254 | |
| 255 | #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ |
| 256 | #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ |
| 257 | |
| 258 | #include <algorithm> |
| 259 | #include <cmath> |
| 260 | #include <cstddef> |
| 261 | #include <exception> |
| 262 | #include <functional> |
| 263 | #include <initializer_list> |
| 264 | #include <ios> |
| 265 | #include <iterator> |
| 266 | #include <limits> |
| 267 | #include <memory> |
| 268 | #include <ostream> // NOLINT |
| 269 | #include <sstream> |
| 270 | #include <string> |
| 271 | #include <type_traits> |
| 272 | #include <utility> |
| 273 | #include <vector> |
| 274 | |
| 275 | #include "gmock/internal/gmock-internal-utils.h" |
| 276 | #include "gmock/internal/gmock-port.h" |
| 277 | #include "gmock/internal/gmock-pp.h" |
| 278 | #include "gtest/gtest.h" |
| 279 | |
| 280 | // MSVC warning C5046 is new as of VS2017 version 15.8. |
| 281 | #if defined(_MSC_VER) && _MSC_VER >= 1915 |
| 282 | #define GMOCK_MAYBE_5046_ 5046 |
| 283 | #else |
| 284 | #define GMOCK_MAYBE_5046_ |
| 285 | #endif |
| 286 | |
| 287 | GTEST_DISABLE_MSC_WARNINGS_PUSH_( |
| 288 | 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by |
| 289 | clients of class B */ |
| 290 | /* Symbol involving type with internal linkage not defined */) |
| 291 | |
| 292 | namespace testing { |
| 293 | |
| 294 | // To implement a matcher Foo for type T, define: |
| 295 | // 1. a class FooMatcherImpl that implements the |
| 296 | // MatcherInterface<T> interface, and |
| 297 | // 2. a factory function that creates a Matcher<T> object from a |
| 298 | // FooMatcherImpl*. |
| 299 | // |
| 300 | // The two-level delegation design makes it possible to allow a user |
| 301 | // to write "v" instead of "Eq(v)" where a Matcher is expected, which |
| 302 | // is impossible if we pass matchers by pointers. It also eases |
| 303 | // ownership management as Matcher objects can now be copied like |
| 304 | // plain values. |
| 305 | |
| 306 | // A match result listener that stores the explanation in a string. |
| 307 | class StringMatchResultListener : public MatchResultListener { |
| 308 | public: |
| 309 | StringMatchResultListener() : MatchResultListener(&ss_) {} |
| 310 | |
| 311 | // Returns the explanation accumulated so far. |
| 312 | std::string str() const { return ss_.str(); } |
| 313 | |
| 314 | // Clears the explanation accumulated so far. |
| 315 | void Clear() { ss_.str(s: "" ); } |
| 316 | |
| 317 | private: |
| 318 | ::std::stringstream ss_; |
| 319 | |
| 320 | StringMatchResultListener(const StringMatchResultListener&) = delete; |
| 321 | StringMatchResultListener& operator=(const StringMatchResultListener&) = |
| 322 | delete; |
| 323 | }; |
| 324 | |
| 325 | // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION |
| 326 | // and MUST NOT BE USED IN USER CODE!!! |
| 327 | namespace internal { |
| 328 | |
| 329 | // The MatcherCastImpl class template is a helper for implementing |
| 330 | // MatcherCast(). We need this helper in order to partially |
| 331 | // specialize the implementation of MatcherCast() (C++ allows |
| 332 | // class/struct templates to be partially specialized, but not |
| 333 | // function templates.). |
| 334 | |
| 335 | // This general version is used when MatcherCast()'s argument is a |
| 336 | // polymorphic matcher (i.e. something that can be converted to a |
| 337 | // Matcher but is not one yet; for example, Eq(value)) or a value (for |
| 338 | // example, "hello"). |
| 339 | template <typename T, typename M> |
| 340 | class MatcherCastImpl { |
| 341 | public: |
| 342 | static Matcher<T> Cast(const M& polymorphic_matcher_or_value) { |
| 343 | // M can be a polymorphic matcher, in which case we want to use |
| 344 | // its conversion operator to create Matcher<T>. Or it can be a value |
| 345 | // that should be passed to the Matcher<T>'s constructor. |
| 346 | // |
| 347 | // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a |
| 348 | // polymorphic matcher because it'll be ambiguous if T has an implicit |
| 349 | // constructor from M (this usually happens when T has an implicit |
| 350 | // constructor from any type). |
| 351 | // |
| 352 | // It won't work to unconditionally implicit_cast |
| 353 | // polymorphic_matcher_or_value to Matcher<T> because it won't trigger |
| 354 | // a user-defined conversion from M to T if one exists (assuming M is |
| 355 | // a value). |
| 356 | return CastImpl(polymorphic_matcher_or_value, |
| 357 | std::is_convertible<M, Matcher<T>>{}, |
| 358 | std::is_convertible<M, T>{}); |
| 359 | } |
| 360 | |
| 361 | private: |
| 362 | template <bool Ignore> |
| 363 | static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value, |
| 364 | std::true_type /* convertible_to_matcher */, |
| 365 | std::integral_constant<bool, Ignore>) { |
| 366 | // M is implicitly convertible to Matcher<T>, which means that either |
| 367 | // M is a polymorphic matcher or Matcher<T> has an implicit constructor |
| 368 | // from M. In both cases using the implicit conversion will produce a |
| 369 | // matcher. |
| 370 | // |
| 371 | // Even if T has an implicit constructor from M, it won't be called because |
| 372 | // creating Matcher<T> would require a chain of two user-defined conversions |
| 373 | // (first to create T from M and then to create Matcher<T> from T). |
| 374 | return polymorphic_matcher_or_value; |
| 375 | } |
| 376 | |
| 377 | // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic |
| 378 | // matcher. It's a value of a type implicitly convertible to T. Use direct |
| 379 | // initialization to create a matcher. |
| 380 | static Matcher<T> CastImpl(const M& value, |
| 381 | std::false_type /* convertible_to_matcher */, |
| 382 | std::true_type /* convertible_to_T */) { |
| 383 | return Matcher<T>(ImplicitCast_<T>(value)); |
| 384 | } |
| 385 | |
| 386 | // M can't be implicitly converted to either Matcher<T> or T. Attempt to use |
| 387 | // polymorphic matcher Eq(value) in this case. |
| 388 | // |
| 389 | // Note that we first attempt to perform an implicit cast on the value and |
| 390 | // only fall back to the polymorphic Eq() matcher afterwards because the |
| 391 | // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end |
| 392 | // which might be undefined even when Rhs is implicitly convertible to Lhs |
| 393 | // (e.g. std::pair<const int, int> vs. std::pair<int, int>). |
| 394 | // |
| 395 | // We don't define this method inline as we need the declaration of Eq(). |
| 396 | static Matcher<T> CastImpl(const M& value, |
| 397 | std::false_type /* convertible_to_matcher */, |
| 398 | std::false_type /* convertible_to_T */); |
| 399 | }; |
| 400 | |
| 401 | // This more specialized version is used when MatcherCast()'s argument |
| 402 | // is already a Matcher. This only compiles when type T can be |
| 403 | // statically converted to type U. |
| 404 | template <typename T, typename U> |
| 405 | class MatcherCastImpl<T, Matcher<U>> { |
| 406 | public: |
| 407 | static Matcher<T> Cast(const Matcher<U>& source_matcher) { |
| 408 | return Matcher<T>(new Impl(source_matcher)); |
| 409 | } |
| 410 | |
| 411 | private: |
| 412 | // If it's possible to implicitly convert a `const T&` to U, then `Impl` can |
| 413 | // take that as input to avoid a copy. Otherwise, such as when `T` is a |
| 414 | // non-const reference type or a type explicitly constructible only from a |
| 415 | // non-const reference, then `Impl` must use `T` as-is (potentially copying). |
| 416 | using ImplArgT = |
| 417 | typename std::conditional<std::is_convertible<const T&, const U&>::value, |
| 418 | const T&, T>::type; |
| 419 | |
| 420 | class Impl : public MatcherInterface<ImplArgT> { |
| 421 | public: |
| 422 | explicit Impl(const Matcher<U>& source_matcher) |
| 423 | : source_matcher_(source_matcher) {} |
| 424 | |
| 425 | // We delegate the matching logic to the source matcher. |
| 426 | bool MatchAndExplain(ImplArgT x, |
| 427 | MatchResultListener* listener) const override { |
| 428 | using FromType = typename std::remove_cv<typename std::remove_pointer< |
| 429 | typename std::remove_reference<T>::type>::type>::type; |
| 430 | using ToType = typename std::remove_cv<typename std::remove_pointer< |
| 431 | typename std::remove_reference<U>::type>::type>::type; |
| 432 | // Do not allow implicitly converting base*/& to derived*/&. |
| 433 | static_assert( |
| 434 | // Do not trigger if only one of them is a pointer. That implies a |
| 435 | // regular conversion and not a down_cast. |
| 436 | (std::is_pointer<typename std::remove_reference<T>::type>::value != |
| 437 | std::is_pointer<typename std::remove_reference<U>::type>::value) || |
| 438 | std::is_same<FromType, ToType>::value || |
| 439 | !std::is_base_of<FromType, ToType>::value, |
| 440 | "Can't implicitly convert from <base> to <derived>" ); |
| 441 | |
| 442 | // Do the cast to `U` explicitly if necessary. |
| 443 | // Otherwise, let implicit conversions do the trick. |
| 444 | using CastType = typename std::conditional< |
| 445 | std::is_convertible<ImplArgT&, const U&>::value, ImplArgT&, U>::type; |
| 446 | |
| 447 | return source_matcher_.MatchAndExplain(static_cast<CastType>(x), |
| 448 | listener); |
| 449 | } |
| 450 | |
| 451 | void DescribeTo(::std::ostream* os) const override { |
| 452 | source_matcher_.DescribeTo(os); |
| 453 | } |
| 454 | |
| 455 | void DescribeNegationTo(::std::ostream* os) const override { |
| 456 | source_matcher_.DescribeNegationTo(os); |
| 457 | } |
| 458 | |
| 459 | private: |
| 460 | const Matcher<U> source_matcher_; |
| 461 | }; |
| 462 | }; |
| 463 | |
| 464 | // This even more specialized version is used for efficiently casting |
| 465 | // a matcher to its own type. |
| 466 | template <typename T> |
| 467 | class MatcherCastImpl<T, Matcher<T>> { |
| 468 | public: |
| 469 | static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; } |
| 470 | }; |
| 471 | |
| 472 | // Template specialization for parameterless Matcher. |
| 473 | template <typename Derived> |
| 474 | class MatcherBaseImpl { |
| 475 | public: |
| 476 | MatcherBaseImpl() = default; |
| 477 | |
| 478 | template <typename T> |
| 479 | operator ::testing::Matcher<T>() const { // NOLINT(runtime/explicit) |
| 480 | return ::testing::Matcher<T>(new |
| 481 | typename Derived::template gmock_Impl<T>()); |
| 482 | } |
| 483 | }; |
| 484 | |
| 485 | // Template specialization for Matcher with parameters. |
| 486 | template <template <typename...> class Derived, typename... Ts> |
| 487 | class MatcherBaseImpl<Derived<Ts...>> { |
| 488 | public: |
| 489 | // Mark the constructor explicit for single argument T to avoid implicit |
| 490 | // conversions. |
| 491 | template <typename E = std::enable_if<sizeof...(Ts) == 1>, |
| 492 | typename E::type* = nullptr> |
| 493 | explicit MatcherBaseImpl(Ts... params) |
| 494 | : params_(std::forward<Ts>(params)...) {} |
| 495 | template <typename E = std::enable_if<sizeof...(Ts) != 1>, |
| 496 | typename = typename E::type> |
| 497 | MatcherBaseImpl(Ts... params) // NOLINT |
| 498 | : params_(std::forward<Ts>(params)...) {} |
| 499 | |
| 500 | template <typename F> |
| 501 | operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit) |
| 502 | return Apply<F>(std::make_index_sequence<sizeof...(Ts)>{}); |
| 503 | } |
| 504 | |
| 505 | private: |
| 506 | template <typename F, std::size_t... tuple_ids> |
| 507 | ::testing::Matcher<F> Apply(std::index_sequence<tuple_ids...>) const { |
| 508 | return ::testing::Matcher<F>( |
| 509 | new typename Derived<Ts...>::template gmock_Impl<F>( |
| 510 | std::get<tuple_ids>(params_)...)); |
| 511 | } |
| 512 | |
| 513 | const std::tuple<Ts...> params_; |
| 514 | }; |
| 515 | |
| 516 | } // namespace internal |
| 517 | |
| 518 | // In order to be safe and clear, casting between different matcher |
| 519 | // types is done explicitly via MatcherCast<T>(m), which takes a |
| 520 | // matcher m and returns a Matcher<T>. It compiles only when T can be |
| 521 | // statically converted to the argument type of m. |
| 522 | template <typename T, typename M> |
| 523 | inline Matcher<T> MatcherCast(const M& matcher) { |
| 524 | return internal::MatcherCastImpl<T, M>::Cast(matcher); |
| 525 | } |
| 526 | |
| 527 | // This overload handles polymorphic matchers and values only since |
| 528 | // monomorphic matchers are handled by the next one. |
| 529 | template <typename T, typename M> |
| 530 | inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) { |
| 531 | return MatcherCast<T>(polymorphic_matcher_or_value); |
| 532 | } |
| 533 | |
| 534 | // This overload handles monomorphic matchers. |
| 535 | // |
| 536 | // In general, if type T can be implicitly converted to type U, we can |
| 537 | // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is |
| 538 | // contravariant): just keep a copy of the original Matcher<U>, convert the |
| 539 | // argument from type T to U, and then pass it to the underlying Matcher<U>. |
| 540 | // The only exception is when U is a non-const reference and T is not, as the |
| 541 | // underlying Matcher<U> may be interested in the argument's address, which |
| 542 | // cannot be preserved in the conversion from T to U (since a copy of the input |
| 543 | // T argument would be required to provide a non-const reference U). |
| 544 | template <typename T, typename U> |
| 545 | inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) { |
| 546 | // Enforce that T can be implicitly converted to U. |
| 547 | static_assert(std::is_convertible<const T&, const U&>::value, |
| 548 | "T must be implicitly convertible to U (and T must be a " |
| 549 | "non-const reference if U is a non-const reference)" ); |
| 550 | // In case both T and U are arithmetic types, enforce that the |
| 551 | // conversion is not lossy. |
| 552 | typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; |
| 553 | typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU; |
| 554 | constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther; |
| 555 | constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther; |
| 556 | static_assert( |
| 557 | kTIsOther || kUIsOther || |
| 558 | (internal::LosslessArithmeticConvertible<RawT, RawU>::value), |
| 559 | "conversion of arithmetic types must be lossless" ); |
| 560 | return MatcherCast<T>(matcher); |
| 561 | } |
| 562 | |
| 563 | // A<T>() returns a matcher that matches any value of type T. |
| 564 | template <typename T> |
| 565 | Matcher<T> A(); |
| 566 | |
| 567 | // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION |
| 568 | // and MUST NOT BE USED IN USER CODE!!! |
| 569 | namespace internal { |
| 570 | |
| 571 | // Used per go/ranked-overloads for dispatching. |
| 572 | struct Rank0 {}; |
| 573 | struct Rank1 : Rank0 {}; |
| 574 | using HighestRank = Rank1; |
| 575 | |
| 576 | // If the explanation is not empty, prints it to the ostream. |
| 577 | inline void PrintIfNotEmpty(const std::string& explanation, |
| 578 | ::std::ostream* os) { |
| 579 | if (!explanation.empty() && os != nullptr) { |
| 580 | *os << ", " << explanation; |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | // Returns true if the given type name is easy to read by a human. |
| 585 | // This is used to decide whether printing the type of a value might |
| 586 | // be helpful. |
| 587 | inline bool IsReadableTypeName(const std::string& type_name) { |
| 588 | // We consider a type name readable if it's short or doesn't contain |
| 589 | // a template or function type. |
| 590 | return (type_name.length() <= 20 || |
| 591 | type_name.find_first_of(s: "<(" ) == std::string::npos); |
| 592 | } |
| 593 | |
| 594 | // Matches the value against the given matcher, prints the value and explains |
| 595 | // the match result to the listener. Returns the match result. |
| 596 | // 'listener' must not be NULL. |
| 597 | // Value cannot be passed by const reference, because some matchers take a |
| 598 | // non-const argument. |
| 599 | template <typename Value, typename T> |
| 600 | bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher, |
| 601 | MatchResultListener* listener) { |
| 602 | if (!listener->IsInterested()) { |
| 603 | // If the listener is not interested, we do not need to construct the |
| 604 | // inner explanation. |
| 605 | return matcher.Matches(value); |
| 606 | } |
| 607 | |
| 608 | StringMatchResultListener inner_listener; |
| 609 | const bool match = matcher.MatchAndExplain(value, &inner_listener); |
| 610 | |
| 611 | UniversalPrint(value, listener->stream()); |
| 612 | #if GTEST_HAS_RTTI |
| 613 | const std::string& type_name = GetTypeName<Value>(); |
| 614 | if (IsReadableTypeName(type_name)) |
| 615 | *listener->stream() << " (of type " << type_name << ")" ; |
| 616 | #endif |
| 617 | PrintIfNotEmpty(explanation: inner_listener.str(), os: listener->stream()); |
| 618 | |
| 619 | return match; |
| 620 | } |
| 621 | |
| 622 | // An internal helper class for doing compile-time loop on a tuple's |
| 623 | // fields. |
| 624 | template <size_t N> |
| 625 | class TuplePrefix { |
| 626 | public: |
| 627 | // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true |
| 628 | // if and only if the first N fields of matcher_tuple matches |
| 629 | // the first N fields of value_tuple, respectively. |
| 630 | template <typename MatcherTuple, typename ValueTuple> |
| 631 | static bool Matches(const MatcherTuple& matcher_tuple, |
| 632 | const ValueTuple& value_tuple) { |
| 633 | return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) && |
| 634 | std::get<N - 1>(matcher_tuple).Matches(std::get<N - 1>(value_tuple)); |
| 635 | } |
| 636 | |
| 637 | // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os) |
| 638 | // describes failures in matching the first N fields of matchers |
| 639 | // against the first N fields of values. If there is no failure, |
| 640 | // nothing will be streamed to os. |
| 641 | template <typename MatcherTuple, typename ValueTuple> |
| 642 | static void ExplainMatchFailuresTo(const MatcherTuple& matchers, |
| 643 | const ValueTuple& values, |
| 644 | ::std::ostream* os) { |
| 645 | // First, describes failures in the first N - 1 fields. |
| 646 | TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os); |
| 647 | |
| 648 | // Then describes the failure (if any) in the (N - 1)-th (0-based) |
| 649 | // field. |
| 650 | typename std::tuple_element<N - 1, MatcherTuple>::type matcher = |
| 651 | std::get<N - 1>(matchers); |
| 652 | typedef typename std::tuple_element<N - 1, ValueTuple>::type Value; |
| 653 | const Value& value = std::get<N - 1>(values); |
| 654 | StringMatchResultListener listener; |
| 655 | if (!matcher.MatchAndExplain(value, &listener)) { |
| 656 | *os << " Expected arg #" << N - 1 << ": " ; |
| 657 | std::get<N - 1>(matchers).DescribeTo(os); |
| 658 | *os << "\n Actual: " ; |
| 659 | // We remove the reference in type Value to prevent the |
| 660 | // universal printer from printing the address of value, which |
| 661 | // isn't interesting to the user most of the time. The |
| 662 | // matcher's MatchAndExplain() method handles the case when |
| 663 | // the address is interesting. |
| 664 | internal::UniversalPrint(value, os); |
| 665 | PrintIfNotEmpty(explanation: listener.str(), os); |
| 666 | *os << "\n" ; |
| 667 | } |
| 668 | } |
| 669 | }; |
| 670 | |
| 671 | // The base case. |
| 672 | template <> |
| 673 | class TuplePrefix<0> { |
| 674 | public: |
| 675 | template <typename MatcherTuple, typename ValueTuple> |
| 676 | static bool Matches(const MatcherTuple& /* matcher_tuple */, |
| 677 | const ValueTuple& /* value_tuple */) { |
| 678 | return true; |
| 679 | } |
| 680 | |
| 681 | template <typename MatcherTuple, typename ValueTuple> |
| 682 | static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */, |
| 683 | const ValueTuple& /* values */, |
| 684 | ::std::ostream* /* os */) {} |
| 685 | }; |
| 686 | |
| 687 | // TupleMatches(matcher_tuple, value_tuple) returns true if and only if |
| 688 | // all matchers in matcher_tuple match the corresponding fields in |
| 689 | // value_tuple. It is a compiler error if matcher_tuple and |
| 690 | // value_tuple have different number of fields or incompatible field |
| 691 | // types. |
| 692 | template <typename MatcherTuple, typename ValueTuple> |
| 693 | bool TupleMatches(const MatcherTuple& matcher_tuple, |
| 694 | const ValueTuple& value_tuple) { |
| 695 | // Makes sure that matcher_tuple and value_tuple have the same |
| 696 | // number of fields. |
| 697 | static_assert(std::tuple_size<MatcherTuple>::value == |
| 698 | std::tuple_size<ValueTuple>::value, |
| 699 | "matcher and value have different numbers of fields" ); |
| 700 | return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple, |
| 701 | value_tuple); |
| 702 | } |
| 703 | |
| 704 | // Describes failures in matching matchers against values. If there |
| 705 | // is no failure, nothing will be streamed to os. |
| 706 | template <typename MatcherTuple, typename ValueTuple> |
| 707 | void ExplainMatchFailureTupleTo(const MatcherTuple& matchers, |
| 708 | const ValueTuple& values, ::std::ostream* os) { |
| 709 | TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo( |
| 710 | matchers, values, os); |
| 711 | } |
| 712 | |
| 713 | // TransformTupleValues and its helper. |
| 714 | // |
| 715 | // TransformTupleValuesHelper hides the internal machinery that |
| 716 | // TransformTupleValues uses to implement a tuple traversal. |
| 717 | template <typename Tuple, typename Func, typename OutIter> |
| 718 | class TransformTupleValuesHelper { |
| 719 | private: |
| 720 | typedef ::std::tuple_size<Tuple> TupleSize; |
| 721 | |
| 722 | public: |
| 723 | // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'. |
| 724 | // Returns the final value of 'out' in case the caller needs it. |
| 725 | static OutIter Run(Func f, const Tuple& t, OutIter out) { |
| 726 | return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out); |
| 727 | } |
| 728 | |
| 729 | private: |
| 730 | template <typename Tup, size_t kRemainingSize> |
| 731 | struct IterateOverTuple { |
| 732 | OutIter operator()(Func f, const Tup& t, OutIter out) const { |
| 733 | *out++ = f(::std::get<TupleSize::value - kRemainingSize>(t)); |
| 734 | return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out); |
| 735 | } |
| 736 | }; |
| 737 | template <typename Tup> |
| 738 | struct IterateOverTuple<Tup, 0> { |
| 739 | OutIter operator()(Func /* f */, const Tup& /* t */, OutIter out) const { |
| 740 | return out; |
| 741 | } |
| 742 | }; |
| 743 | }; |
| 744 | |
| 745 | // Successively invokes 'f(element)' on each element of the tuple 't', |
| 746 | // appending each result to the 'out' iterator. Returns the final value |
| 747 | // of 'out'. |
| 748 | template <typename Tuple, typename Func, typename OutIter> |
| 749 | OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) { |
| 750 | return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out); |
| 751 | } |
| 752 | |
| 753 | // Implements _, a matcher that matches any value of any |
| 754 | // type. This is a polymorphic matcher, so we need a template type |
| 755 | // conversion operator to make it appearing as a Matcher<T> for any |
| 756 | // type T. |
| 757 | class AnythingMatcher { |
| 758 | public: |
| 759 | using is_gtest_matcher = void; |
| 760 | |
| 761 | template <typename T> |
| 762 | bool MatchAndExplain(const T& /* x */, std::ostream* /* listener */) const { |
| 763 | return true; |
| 764 | } |
| 765 | void DescribeTo(std::ostream* os) const { *os << "is anything" ; } |
| 766 | void DescribeNegationTo(::std::ostream* os) const { |
| 767 | // This is mostly for completeness' sake, as it's not very useful |
| 768 | // to write Not(A<bool>()). However we cannot completely rule out |
| 769 | // such a possibility, and it doesn't hurt to be prepared. |
| 770 | *os << "never matches" ; |
| 771 | } |
| 772 | }; |
| 773 | |
| 774 | // Implements the polymorphic IsNull() matcher, which matches any raw or smart |
| 775 | // pointer that is NULL. |
| 776 | class IsNullMatcher { |
| 777 | public: |
| 778 | template <typename Pointer> |
| 779 | bool MatchAndExplain(const Pointer& p, |
| 780 | MatchResultListener* /* listener */) const { |
| 781 | return p == nullptr; |
| 782 | } |
| 783 | |
| 784 | void DescribeTo(::std::ostream* os) const { *os << "is NULL" ; } |
| 785 | void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NULL" ; } |
| 786 | }; |
| 787 | |
| 788 | // Implements the polymorphic NotNull() matcher, which matches any raw or smart |
| 789 | // pointer that is not NULL. |
| 790 | class NotNullMatcher { |
| 791 | public: |
| 792 | template <typename Pointer> |
| 793 | bool MatchAndExplain(const Pointer& p, |
| 794 | MatchResultListener* /* listener */) const { |
| 795 | return p != nullptr; |
| 796 | } |
| 797 | |
| 798 | void DescribeTo(::std::ostream* os) const { *os << "isn't NULL" ; } |
| 799 | void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL" ; } |
| 800 | }; |
| 801 | |
| 802 | // Ref(variable) matches any argument that is a reference to |
| 803 | // 'variable'. This matcher is polymorphic as it can match any |
| 804 | // super type of the type of 'variable'. |
| 805 | // |
| 806 | // The RefMatcher template class implements Ref(variable). It can |
| 807 | // only be instantiated with a reference type. This prevents a user |
| 808 | // from mistakenly using Ref(x) to match a non-reference function |
| 809 | // argument. For example, the following will righteously cause a |
| 810 | // compiler error: |
| 811 | // |
| 812 | // int n; |
| 813 | // Matcher<int> m1 = Ref(n); // This won't compile. |
| 814 | // Matcher<int&> m2 = Ref(n); // This will compile. |
| 815 | template <typename T> |
| 816 | class RefMatcher; |
| 817 | |
| 818 | template <typename T> |
| 819 | class RefMatcher<T&> { |
| 820 | // Google Mock is a generic framework and thus needs to support |
| 821 | // mocking any function types, including those that take non-const |
| 822 | // reference arguments. Therefore the template parameter T (and |
| 823 | // Super below) can be instantiated to either a const type or a |
| 824 | // non-const type. |
| 825 | public: |
| 826 | // RefMatcher() takes a T& instead of const T&, as we want the |
| 827 | // compiler to catch using Ref(const_value) as a matcher for a |
| 828 | // non-const reference. |
| 829 | explicit RefMatcher(T& x) : object_(x) {} // NOLINT |
| 830 | |
| 831 | template <typename Super> |
| 832 | operator Matcher<Super&>() const { |
| 833 | // By passing object_ (type T&) to Impl(), which expects a Super&, |
| 834 | // we make sure that Super is a super type of T. In particular, |
| 835 | // this catches using Ref(const_value) as a matcher for a |
| 836 | // non-const reference, as you cannot implicitly convert a const |
| 837 | // reference to a non-const reference. |
| 838 | return MakeMatcher(new Impl<Super>(object_)); |
| 839 | } |
| 840 | |
| 841 | private: |
| 842 | template <typename Super> |
| 843 | class Impl : public MatcherInterface<Super&> { |
| 844 | public: |
| 845 | explicit Impl(Super& x) : object_(x) {} // NOLINT |
| 846 | |
| 847 | // MatchAndExplain() takes a Super& (as opposed to const Super&) |
| 848 | // in order to match the interface MatcherInterface<Super&>. |
| 849 | bool MatchAndExplain(Super& x, |
| 850 | MatchResultListener* listener) const override { |
| 851 | *listener << "which is located @" << static_cast<const void*>(&x); |
| 852 | return &x == &object_; |
| 853 | } |
| 854 | |
| 855 | void DescribeTo(::std::ostream* os) const override { |
| 856 | *os << "references the variable " ; |
| 857 | UniversalPrinter<Super&>::Print(object_, os); |
| 858 | } |
| 859 | |
| 860 | void DescribeNegationTo(::std::ostream* os) const override { |
| 861 | *os << "does not reference the variable " ; |
| 862 | UniversalPrinter<Super&>::Print(object_, os); |
| 863 | } |
| 864 | |
| 865 | private: |
| 866 | const Super& object_; |
| 867 | }; |
| 868 | |
| 869 | T& object_; |
| 870 | }; |
| 871 | |
| 872 | // Polymorphic helper functions for narrow and wide string matchers. |
| 873 | inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { |
| 874 | return String::CaseInsensitiveCStringEquals(lhs, rhs); |
| 875 | } |
| 876 | |
| 877 | inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs, |
| 878 | const wchar_t* rhs) { |
| 879 | return String::CaseInsensitiveWideCStringEquals(lhs, rhs); |
| 880 | } |
| 881 | |
| 882 | // String comparison for narrow or wide strings that can have embedded NUL |
| 883 | // characters. |
| 884 | template <typename StringType> |
| 885 | bool CaseInsensitiveStringEquals(const StringType& s1, const StringType& s2) { |
| 886 | // Are the heads equal? |
| 887 | if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) { |
| 888 | return false; |
| 889 | } |
| 890 | |
| 891 | // Skip the equal heads. |
| 892 | const typename StringType::value_type nul = 0; |
| 893 | const size_t i1 = s1.find(nul), i2 = s2.find(nul); |
| 894 | |
| 895 | // Are we at the end of either s1 or s2? |
| 896 | if (i1 == StringType::npos || i2 == StringType::npos) { |
| 897 | return i1 == i2; |
| 898 | } |
| 899 | |
| 900 | // Are the tails equal? |
| 901 | return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1)); |
| 902 | } |
| 903 | |
| 904 | // String matchers. |
| 905 | |
| 906 | // Implements equality-based string matchers like StrEq, StrCaseNe, and etc. |
| 907 | template <typename StringType> |
| 908 | class StrEqualityMatcher { |
| 909 | public: |
| 910 | StrEqualityMatcher(StringType str, bool expect_eq, bool case_sensitive) |
| 911 | : string_(std::move(str)), |
| 912 | expect_eq_(expect_eq), |
| 913 | case_sensitive_(case_sensitive) {} |
| 914 | |
| 915 | #if GTEST_INTERNAL_HAS_STRING_VIEW |
| 916 | bool MatchAndExplain(const internal::StringView& s, |
| 917 | MatchResultListener* listener) const { |
| 918 | // This should fail to compile if StringView is used with wide |
| 919 | // strings. |
| 920 | const StringType& str = std::string(s); |
| 921 | return MatchAndExplain(str, listener); |
| 922 | } |
| 923 | #endif // GTEST_INTERNAL_HAS_STRING_VIEW |
| 924 | |
| 925 | // Accepts pointer types, particularly: |
| 926 | // const char* |
| 927 | // char* |
| 928 | // const wchar_t* |
| 929 | // wchar_t* |
| 930 | template <typename CharType> |
| 931 | bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { |
| 932 | if (s == nullptr) { |
| 933 | return !expect_eq_; |
| 934 | } |
| 935 | return MatchAndExplain(StringType(s), listener); |
| 936 | } |
| 937 | |
| 938 | // Matches anything that can convert to StringType. |
| 939 | // |
| 940 | // This is a template, not just a plain function with const StringType&, |
| 941 | // because StringView has some interfering non-explicit constructors. |
| 942 | template <typename MatcheeStringType> |
| 943 | bool MatchAndExplain(const MatcheeStringType& s, |
| 944 | MatchResultListener* /* listener */) const { |
| 945 | const StringType s2(s); |
| 946 | const bool eq = case_sensitive_ ? s2 == string_ |
| 947 | : CaseInsensitiveStringEquals(s2, string_); |
| 948 | return expect_eq_ == eq; |
| 949 | } |
| 950 | |
| 951 | void DescribeTo(::std::ostream* os) const { |
| 952 | DescribeToHelper(expect_eq: expect_eq_, os); |
| 953 | } |
| 954 | |
| 955 | void DescribeNegationTo(::std::ostream* os) const { |
| 956 | DescribeToHelper(expect_eq: !expect_eq_, os); |
| 957 | } |
| 958 | |
| 959 | private: |
| 960 | void DescribeToHelper(bool expect_eq, ::std::ostream* os) const { |
| 961 | *os << (expect_eq ? "is " : "isn't " ); |
| 962 | *os << "equal to " ; |
| 963 | if (!case_sensitive_) { |
| 964 | *os << "(ignoring case) " ; |
| 965 | } |
| 966 | UniversalPrint(string_, os); |
| 967 | } |
| 968 | |
| 969 | const StringType string_; |
| 970 | const bool expect_eq_; |
| 971 | const bool case_sensitive_; |
| 972 | }; |
| 973 | |
| 974 | // Implements the polymorphic HasSubstr(substring) matcher, which |
| 975 | // can be used as a Matcher<T> as long as T can be converted to a |
| 976 | // string. |
| 977 | template <typename StringType> |
| 978 | class HasSubstrMatcher { |
| 979 | public: |
| 980 | explicit HasSubstrMatcher(const StringType& substring) |
| 981 | : substring_(substring) {} |
| 982 | |
| 983 | #if GTEST_INTERNAL_HAS_STRING_VIEW |
| 984 | bool MatchAndExplain(const internal::StringView& s, |
| 985 | MatchResultListener* listener) const { |
| 986 | // This should fail to compile if StringView is used with wide |
| 987 | // strings. |
| 988 | const StringType& str = std::string(s); |
| 989 | return MatchAndExplain(str, listener); |
| 990 | } |
| 991 | #endif // GTEST_INTERNAL_HAS_STRING_VIEW |
| 992 | |
| 993 | // Accepts pointer types, particularly: |
| 994 | // const char* |
| 995 | // char* |
| 996 | // const wchar_t* |
| 997 | // wchar_t* |
| 998 | template <typename CharType> |
| 999 | bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { |
| 1000 | return s != nullptr && MatchAndExplain(StringType(s), listener); |
| 1001 | } |
| 1002 | |
| 1003 | // Matches anything that can convert to StringType. |
| 1004 | // |
| 1005 | // This is a template, not just a plain function with const StringType&, |
| 1006 | // because StringView has some interfering non-explicit constructors. |
| 1007 | template <typename MatcheeStringType> |
| 1008 | bool MatchAndExplain(const MatcheeStringType& s, |
| 1009 | MatchResultListener* /* listener */) const { |
| 1010 | return StringType(s).find(substring_) != StringType::npos; |
| 1011 | } |
| 1012 | |
| 1013 | // Describes what this matcher matches. |
| 1014 | void DescribeTo(::std::ostream* os) const { |
| 1015 | *os << "has substring " ; |
| 1016 | UniversalPrint(substring_, os); |
| 1017 | } |
| 1018 | |
| 1019 | void DescribeNegationTo(::std::ostream* os) const { |
| 1020 | *os << "has no substring " ; |
| 1021 | UniversalPrint(substring_, os); |
| 1022 | } |
| 1023 | |
| 1024 | private: |
| 1025 | const StringType substring_; |
| 1026 | }; |
| 1027 | |
| 1028 | // Implements the polymorphic StartsWith(substring) matcher, which |
| 1029 | // can be used as a Matcher<T> as long as T can be converted to a |
| 1030 | // string. |
| 1031 | template <typename StringType> |
| 1032 | class StartsWithMatcher { |
| 1033 | public: |
| 1034 | explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {} |
| 1035 | |
| 1036 | #if GTEST_INTERNAL_HAS_STRING_VIEW |
| 1037 | bool MatchAndExplain(const internal::StringView& s, |
| 1038 | MatchResultListener* listener) const { |
| 1039 | // This should fail to compile if StringView is used with wide |
| 1040 | // strings. |
| 1041 | const StringType& str = std::string(s); |
| 1042 | return MatchAndExplain(str, listener); |
| 1043 | } |
| 1044 | #endif // GTEST_INTERNAL_HAS_STRING_VIEW |
| 1045 | |
| 1046 | // Accepts pointer types, particularly: |
| 1047 | // const char* |
| 1048 | // char* |
| 1049 | // const wchar_t* |
| 1050 | // wchar_t* |
| 1051 | template <typename CharType> |
| 1052 | bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { |
| 1053 | return s != nullptr && MatchAndExplain(StringType(s), listener); |
| 1054 | } |
| 1055 | |
| 1056 | // Matches anything that can convert to StringType. |
| 1057 | // |
| 1058 | // This is a template, not just a plain function with const StringType&, |
| 1059 | // because StringView has some interfering non-explicit constructors. |
| 1060 | template <typename MatcheeStringType> |
| 1061 | bool MatchAndExplain(const MatcheeStringType& s, |
| 1062 | MatchResultListener* /* listener */) const { |
| 1063 | const StringType s2(s); |
| 1064 | return s2.length() >= prefix_.length() && |
| 1065 | s2.substr(0, prefix_.length()) == prefix_; |
| 1066 | } |
| 1067 | |
| 1068 | void DescribeTo(::std::ostream* os) const { |
| 1069 | *os << "starts with " ; |
| 1070 | UniversalPrint(prefix_, os); |
| 1071 | } |
| 1072 | |
| 1073 | void DescribeNegationTo(::std::ostream* os) const { |
| 1074 | *os << "doesn't start with " ; |
| 1075 | UniversalPrint(prefix_, os); |
| 1076 | } |
| 1077 | |
| 1078 | private: |
| 1079 | const StringType prefix_; |
| 1080 | }; |
| 1081 | |
| 1082 | // Implements the polymorphic EndsWith(substring) matcher, which |
| 1083 | // can be used as a Matcher<T> as long as T can be converted to a |
| 1084 | // string. |
| 1085 | template <typename StringType> |
| 1086 | class EndsWithMatcher { |
| 1087 | public: |
| 1088 | explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {} |
| 1089 | |
| 1090 | #if GTEST_INTERNAL_HAS_STRING_VIEW |
| 1091 | bool MatchAndExplain(const internal::StringView& s, |
| 1092 | MatchResultListener* listener) const { |
| 1093 | // This should fail to compile if StringView is used with wide |
| 1094 | // strings. |
| 1095 | const StringType& str = std::string(s); |
| 1096 | return MatchAndExplain(str, listener); |
| 1097 | } |
| 1098 | #endif // GTEST_INTERNAL_HAS_STRING_VIEW |
| 1099 | |
| 1100 | // Accepts pointer types, particularly: |
| 1101 | // const char* |
| 1102 | // char* |
| 1103 | // const wchar_t* |
| 1104 | // wchar_t* |
| 1105 | template <typename CharType> |
| 1106 | bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { |
| 1107 | return s != nullptr && MatchAndExplain(StringType(s), listener); |
| 1108 | } |
| 1109 | |
| 1110 | // Matches anything that can convert to StringType. |
| 1111 | // |
| 1112 | // This is a template, not just a plain function with const StringType&, |
| 1113 | // because StringView has some interfering non-explicit constructors. |
| 1114 | template <typename MatcheeStringType> |
| 1115 | bool MatchAndExplain(const MatcheeStringType& s, |
| 1116 | MatchResultListener* /* listener */) const { |
| 1117 | const StringType s2(s); |
| 1118 | return s2.length() >= suffix_.length() && |
| 1119 | s2.substr(s2.length() - suffix_.length()) == suffix_; |
| 1120 | } |
| 1121 | |
| 1122 | void DescribeTo(::std::ostream* os) const { |
| 1123 | *os << "ends with " ; |
| 1124 | UniversalPrint(suffix_, os); |
| 1125 | } |
| 1126 | |
| 1127 | void DescribeNegationTo(::std::ostream* os) const { |
| 1128 | *os << "doesn't end with " ; |
| 1129 | UniversalPrint(suffix_, os); |
| 1130 | } |
| 1131 | |
| 1132 | private: |
| 1133 | const StringType suffix_; |
| 1134 | }; |
| 1135 | |
| 1136 | // Implements the polymorphic WhenBase64Unescaped(matcher) matcher, which can be |
| 1137 | // used as a Matcher<T> as long as T can be converted to a string. |
| 1138 | class WhenBase64UnescapedMatcher { |
| 1139 | public: |
| 1140 | using is_gtest_matcher = void; |
| 1141 | |
| 1142 | explicit WhenBase64UnescapedMatcher( |
| 1143 | const Matcher<const std::string&>& internal_matcher) |
| 1144 | : internal_matcher_(internal_matcher) {} |
| 1145 | |
| 1146 | // Matches anything that can convert to std::string. |
| 1147 | template <typename MatcheeStringType> |
| 1148 | bool MatchAndExplain(const MatcheeStringType& s, |
| 1149 | MatchResultListener* listener) const { |
| 1150 | const std::string s2(s); // NOLINT (needed for working with string_view). |
| 1151 | std::string unescaped; |
| 1152 | if (!internal::Base64Unescape(encoded: s2, decoded: &unescaped)) { |
| 1153 | if (listener != nullptr) { |
| 1154 | *listener << "is not a valid base64 escaped string" ; |
| 1155 | } |
| 1156 | return false; |
| 1157 | } |
| 1158 | return MatchPrintAndExplain(value&: unescaped, matcher: internal_matcher_, listener); |
| 1159 | } |
| 1160 | |
| 1161 | void DescribeTo(::std::ostream* os) const { |
| 1162 | *os << "matches after Base64Unescape " ; |
| 1163 | internal_matcher_.DescribeTo(os); |
| 1164 | } |
| 1165 | |
| 1166 | void DescribeNegationTo(::std::ostream* os) const { |
| 1167 | *os << "does not match after Base64Unescape " ; |
| 1168 | internal_matcher_.DescribeTo(os); |
| 1169 | } |
| 1170 | |
| 1171 | private: |
| 1172 | const Matcher<const std::string&> internal_matcher_; |
| 1173 | }; |
| 1174 | |
| 1175 | // Implements a matcher that compares the two fields of a 2-tuple |
| 1176 | // using one of the ==, <=, <, etc, operators. The two fields being |
| 1177 | // compared don't have to have the same type. |
| 1178 | // |
| 1179 | // The matcher defined here is polymorphic (for example, Eq() can be |
| 1180 | // used to match a std::tuple<int, short>, a std::tuple<const long&, double>, |
| 1181 | // etc). Therefore we use a template type conversion operator in the |
| 1182 | // implementation. |
| 1183 | template <typename D, typename Op> |
| 1184 | class PairMatchBase { |
| 1185 | public: |
| 1186 | template <typename T1, typename T2> |
| 1187 | operator Matcher<::std::tuple<T1, T2>>() const { |
| 1188 | return Matcher<::std::tuple<T1, T2>>(new Impl<const ::std::tuple<T1, T2>&>); |
| 1189 | } |
| 1190 | template <typename T1, typename T2> |
| 1191 | operator Matcher<const ::std::tuple<T1, T2>&>() const { |
| 1192 | return MakeMatcher(new Impl<const ::std::tuple<T1, T2>&>); |
| 1193 | } |
| 1194 | |
| 1195 | private: |
| 1196 | static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT |
| 1197 | return os << D::Desc(); |
| 1198 | } |
| 1199 | |
| 1200 | template <typename Tuple> |
| 1201 | class Impl : public MatcherInterface<Tuple> { |
| 1202 | public: |
| 1203 | bool MatchAndExplain(Tuple args, |
| 1204 | MatchResultListener* /* listener */) const override { |
| 1205 | return Op()(::std::get<0>(args), ::std::get<1>(args)); |
| 1206 | } |
| 1207 | void DescribeTo(::std::ostream* os) const override { |
| 1208 | *os << "are " << GetDesc; |
| 1209 | } |
| 1210 | void DescribeNegationTo(::std::ostream* os) const override { |
| 1211 | *os << "aren't " << GetDesc; |
| 1212 | } |
| 1213 | }; |
| 1214 | }; |
| 1215 | |
| 1216 | class Eq2Matcher : public PairMatchBase<Eq2Matcher, std::equal_to<>> { |
| 1217 | public: |
| 1218 | static const char* Desc() { return "an equal pair" ; } |
| 1219 | }; |
| 1220 | class Ne2Matcher : public PairMatchBase<Ne2Matcher, std::not_equal_to<>> { |
| 1221 | public: |
| 1222 | static const char* Desc() { return "an unequal pair" ; } |
| 1223 | }; |
| 1224 | class Lt2Matcher : public PairMatchBase<Lt2Matcher, std::less<>> { |
| 1225 | public: |
| 1226 | static const char* Desc() { return "a pair where the first < the second" ; } |
| 1227 | }; |
| 1228 | class Gt2Matcher : public PairMatchBase<Gt2Matcher, std::greater<>> { |
| 1229 | public: |
| 1230 | static const char* Desc() { return "a pair where the first > the second" ; } |
| 1231 | }; |
| 1232 | class Le2Matcher : public PairMatchBase<Le2Matcher, std::less_equal<>> { |
| 1233 | public: |
| 1234 | static const char* Desc() { return "a pair where the first <= the second" ; } |
| 1235 | }; |
| 1236 | class Ge2Matcher : public PairMatchBase<Ge2Matcher, std::greater_equal<>> { |
| 1237 | public: |
| 1238 | static const char* Desc() { return "a pair where the first >= the second" ; } |
| 1239 | }; |
| 1240 | |
| 1241 | // Implements the Not(...) matcher for a particular argument type T. |
| 1242 | // We do not nest it inside the NotMatcher class template, as that |
| 1243 | // will prevent different instantiations of NotMatcher from sharing |
| 1244 | // the same NotMatcherImpl<T> class. |
| 1245 | template <typename T> |
| 1246 | class NotMatcherImpl : public MatcherInterface<const T&> { |
| 1247 | public: |
| 1248 | explicit NotMatcherImpl(const Matcher<T>& matcher) : matcher_(matcher) {} |
| 1249 | |
| 1250 | bool MatchAndExplain(const T& x, |
| 1251 | MatchResultListener* listener) const override { |
| 1252 | return !matcher_.MatchAndExplain(x, listener); |
| 1253 | } |
| 1254 | |
| 1255 | void DescribeTo(::std::ostream* os) const override { |
| 1256 | matcher_.DescribeNegationTo(os); |
| 1257 | } |
| 1258 | |
| 1259 | void DescribeNegationTo(::std::ostream* os) const override { |
| 1260 | matcher_.DescribeTo(os); |
| 1261 | } |
| 1262 | |
| 1263 | private: |
| 1264 | const Matcher<T> matcher_; |
| 1265 | }; |
| 1266 | |
| 1267 | // Implements the Not(m) matcher, which matches a value that doesn't |
| 1268 | // match matcher m. |
| 1269 | template <typename InnerMatcher> |
| 1270 | class NotMatcher { |
| 1271 | public: |
| 1272 | explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {} |
| 1273 | |
| 1274 | // This template type conversion operator allows Not(m) to be used |
| 1275 | // to match any type m can match. |
| 1276 | template <typename T> |
| 1277 | operator Matcher<T>() const { |
| 1278 | return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_))); |
| 1279 | } |
| 1280 | |
| 1281 | private: |
| 1282 | InnerMatcher matcher_; |
| 1283 | }; |
| 1284 | |
| 1285 | // Implements the AllOf(m1, m2) matcher for a particular argument type |
| 1286 | // T. We do not nest it inside the BothOfMatcher class template, as |
| 1287 | // that will prevent different instantiations of BothOfMatcher from |
| 1288 | // sharing the same BothOfMatcherImpl<T> class. |
| 1289 | template <typename T> |
| 1290 | class AllOfMatcherImpl : public MatcherInterface<const T&> { |
| 1291 | public: |
| 1292 | explicit AllOfMatcherImpl(std::vector<Matcher<T>> matchers) |
| 1293 | : matchers_(std::move(matchers)) {} |
| 1294 | |
| 1295 | void DescribeTo(::std::ostream* os) const override { |
| 1296 | *os << "(" ; |
| 1297 | for (size_t i = 0; i < matchers_.size(); ++i) { |
| 1298 | if (i != 0) *os << ") and (" ; |
| 1299 | matchers_[i].DescribeTo(os); |
| 1300 | } |
| 1301 | *os << ")" ; |
| 1302 | } |
| 1303 | |
| 1304 | void DescribeNegationTo(::std::ostream* os) const override { |
| 1305 | *os << "(" ; |
| 1306 | for (size_t i = 0; i < matchers_.size(); ++i) { |
| 1307 | if (i != 0) *os << ") or (" ; |
| 1308 | matchers_[i].DescribeNegationTo(os); |
| 1309 | } |
| 1310 | *os << ")" ; |
| 1311 | } |
| 1312 | |
| 1313 | bool MatchAndExplain(const T& x, |
| 1314 | MatchResultListener* listener) const override { |
| 1315 | if (!listener->IsInterested()) { |
| 1316 | // Fast path to avoid unnecessary formatting. |
| 1317 | for (const Matcher<T>& matcher : matchers_) { |
| 1318 | if (!matcher.Matches(x)) { |
| 1319 | return false; |
| 1320 | } |
| 1321 | } |
| 1322 | return true; |
| 1323 | } |
| 1324 | // This method uses matcher's explanation when explaining the result. |
| 1325 | // However, if matcher doesn't provide one, this method uses matcher's |
| 1326 | // description. |
| 1327 | std::string all_match_result; |
| 1328 | for (const Matcher<T>& matcher : matchers_) { |
| 1329 | StringMatchResultListener slistener; |
| 1330 | // Return explanation for first failed matcher. |
| 1331 | if (!matcher.MatchAndExplain(x, &slistener)) { |
| 1332 | const std::string explanation = slistener.str(); |
| 1333 | if (!explanation.empty()) { |
| 1334 | *listener << explanation; |
| 1335 | } else { |
| 1336 | *listener << "which doesn't match (" << Describe(matcher) << ")" ; |
| 1337 | } |
| 1338 | return false; |
| 1339 | } |
| 1340 | // Keep track of explanations in case all matchers succeed. |
| 1341 | std::string explanation = slistener.str(); |
| 1342 | if (explanation.empty()) { |
| 1343 | explanation = Describe(matcher); |
| 1344 | } |
| 1345 | if (all_match_result.empty()) { |
| 1346 | all_match_result = explanation; |
| 1347 | } else { |
| 1348 | if (!explanation.empty()) { |
| 1349 | all_match_result += ", and " ; |
| 1350 | all_match_result += explanation; |
| 1351 | } |
| 1352 | } |
| 1353 | } |
| 1354 | |
| 1355 | *listener << all_match_result; |
| 1356 | return true; |
| 1357 | } |
| 1358 | |
| 1359 | private: |
| 1360 | // Returns matcher description as a string. |
| 1361 | std::string Describe(const Matcher<T>& matcher) const { |
| 1362 | StringMatchResultListener listener; |
| 1363 | matcher.DescribeTo(listener.stream()); |
| 1364 | return listener.str(); |
| 1365 | } |
| 1366 | const std::vector<Matcher<T>> matchers_; |
| 1367 | }; |
| 1368 | |
| 1369 | // VariadicMatcher is used for the variadic implementation of |
| 1370 | // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...). |
| 1371 | // CombiningMatcher<T> is used to recursively combine the provided matchers |
| 1372 | // (of type Args...). |
| 1373 | template <template <typename T> class CombiningMatcher, typename... Args> |
| 1374 | class VariadicMatcher { |
| 1375 | public: |
| 1376 | VariadicMatcher(const Args&... matchers) // NOLINT |
| 1377 | : matchers_(matchers...) { |
| 1378 | static_assert(sizeof...(Args) > 0, "Must have at least one matcher." ); |
| 1379 | } |
| 1380 | |
| 1381 | VariadicMatcher(const VariadicMatcher&) = default; |
| 1382 | VariadicMatcher& operator=(const VariadicMatcher&) = delete; |
| 1383 | |
| 1384 | // This template type conversion operator allows an |
| 1385 | // VariadicMatcher<Matcher1, Matcher2...> object to match any type that |
| 1386 | // all of the provided matchers (Matcher1, Matcher2, ...) can match. |
| 1387 | template <typename T> |
| 1388 | operator Matcher<T>() const { |
| 1389 | std::vector<Matcher<T>> values; |
| 1390 | CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>()); |
| 1391 | return Matcher<T>(new CombiningMatcher<T>(std::move(values))); |
| 1392 | } |
| 1393 | |
| 1394 | private: |
| 1395 | template <typename T, size_t I> |
| 1396 | void CreateVariadicMatcher(std::vector<Matcher<T>>* values, |
| 1397 | std::integral_constant<size_t, I>) const { |
| 1398 | values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_))); |
| 1399 | CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>()); |
| 1400 | } |
| 1401 | |
| 1402 | template <typename T> |
| 1403 | void CreateVariadicMatcher( |
| 1404 | std::vector<Matcher<T>>*, |
| 1405 | std::integral_constant<size_t, sizeof...(Args)>) const {} |
| 1406 | |
| 1407 | std::tuple<Args...> matchers_; |
| 1408 | }; |
| 1409 | |
| 1410 | template <typename... Args> |
| 1411 | using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>; |
| 1412 | |
| 1413 | // Implements the AnyOf(m1, m2) matcher for a particular argument type |
| 1414 | // T. We do not nest it inside the AnyOfMatcher class template, as |
| 1415 | // that will prevent different instantiations of AnyOfMatcher from |
| 1416 | // sharing the same EitherOfMatcherImpl<T> class. |
| 1417 | template <typename T> |
| 1418 | class AnyOfMatcherImpl : public MatcherInterface<const T&> { |
| 1419 | public: |
| 1420 | explicit AnyOfMatcherImpl(std::vector<Matcher<T>> matchers) |
| 1421 | : matchers_(std::move(matchers)) {} |
| 1422 | |
| 1423 | void DescribeTo(::std::ostream* os) const override { |
| 1424 | *os << "(" ; |
| 1425 | for (size_t i = 0; i < matchers_.size(); ++i) { |
| 1426 | if (i != 0) *os << ") or (" ; |
| 1427 | matchers_[i].DescribeTo(os); |
| 1428 | } |
| 1429 | *os << ")" ; |
| 1430 | } |
| 1431 | |
| 1432 | void DescribeNegationTo(::std::ostream* os) const override { |
| 1433 | *os << "(" ; |
| 1434 | for (size_t i = 0; i < matchers_.size(); ++i) { |
| 1435 | if (i != 0) *os << ") and (" ; |
| 1436 | matchers_[i].DescribeNegationTo(os); |
| 1437 | } |
| 1438 | *os << ")" ; |
| 1439 | } |
| 1440 | |
| 1441 | bool MatchAndExplain(const T& x, |
| 1442 | MatchResultListener* listener) const override { |
| 1443 | if (!listener->IsInterested()) { |
| 1444 | // Fast path to avoid unnecessary formatting of match explanations. |
| 1445 | for (const Matcher<T>& matcher : matchers_) { |
| 1446 | if (matcher.Matches(x)) { |
| 1447 | return true; |
| 1448 | } |
| 1449 | } |
| 1450 | return false; |
| 1451 | } |
| 1452 | // This method uses matcher's explanation when explaining the result. |
| 1453 | // However, if matcher doesn't provide one, this method uses matcher's |
| 1454 | // description. |
| 1455 | std::string no_match_result; |
| 1456 | for (const Matcher<T>& matcher : matchers_) { |
| 1457 | StringMatchResultListener slistener; |
| 1458 | // Return explanation for first match. |
| 1459 | if (matcher.MatchAndExplain(x, &slistener)) { |
| 1460 | const std::string explanation = slistener.str(); |
| 1461 | if (!explanation.empty()) { |
| 1462 | *listener << explanation; |
| 1463 | } else { |
| 1464 | *listener << "which matches (" << Describe(matcher) << ")" ; |
| 1465 | } |
| 1466 | return true; |
| 1467 | } |
| 1468 | // Keep track of explanations in case there is no match. |
| 1469 | std::string explanation = slistener.str(); |
| 1470 | if (explanation.empty()) { |
| 1471 | explanation = DescribeNegation(matcher); |
| 1472 | } |
| 1473 | if (no_match_result.empty()) { |
| 1474 | no_match_result = explanation; |
| 1475 | } else { |
| 1476 | if (!explanation.empty()) { |
| 1477 | no_match_result += ", and " ; |
| 1478 | no_match_result += explanation; |
| 1479 | } |
| 1480 | } |
| 1481 | } |
| 1482 | |
| 1483 | *listener << no_match_result; |
| 1484 | return false; |
| 1485 | } |
| 1486 | |
| 1487 | private: |
| 1488 | // Returns matcher description as a string. |
| 1489 | std::string Describe(const Matcher<T>& matcher) const { |
| 1490 | StringMatchResultListener listener; |
| 1491 | matcher.DescribeTo(listener.stream()); |
| 1492 | return listener.str(); |
| 1493 | } |
| 1494 | |
| 1495 | std::string DescribeNegation(const Matcher<T>& matcher) const { |
| 1496 | StringMatchResultListener listener; |
| 1497 | matcher.DescribeNegationTo(listener.stream()); |
| 1498 | return listener.str(); |
| 1499 | } |
| 1500 | |
| 1501 | const std::vector<Matcher<T>> matchers_; |
| 1502 | }; |
| 1503 | |
| 1504 | // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...). |
| 1505 | template <typename... Args> |
| 1506 | using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>; |
| 1507 | |
| 1508 | // ConditionalMatcher is the implementation of Conditional(cond, m1, m2) |
| 1509 | template <typename MatcherTrue, typename MatcherFalse> |
| 1510 | class ConditionalMatcher { |
| 1511 | public: |
| 1512 | ConditionalMatcher(bool condition, MatcherTrue matcher_true, |
| 1513 | MatcherFalse matcher_false) |
| 1514 | : condition_(condition), |
| 1515 | matcher_true_(std::move(matcher_true)), |
| 1516 | matcher_false_(std::move(matcher_false)) {} |
| 1517 | |
| 1518 | template <typename T> |
| 1519 | operator Matcher<T>() const { // NOLINT(runtime/explicit) |
| 1520 | return condition_ ? SafeMatcherCast<T>(matcher_true_) |
| 1521 | : SafeMatcherCast<T>(matcher_false_); |
| 1522 | } |
| 1523 | |
| 1524 | private: |
| 1525 | bool condition_; |
| 1526 | MatcherTrue matcher_true_; |
| 1527 | MatcherFalse matcher_false_; |
| 1528 | }; |
| 1529 | |
| 1530 | // Wrapper for implementation of Any/AllOfArray(). |
| 1531 | template <template <class> class MatcherImpl, typename T> |
| 1532 | class SomeOfArrayMatcher { |
| 1533 | public: |
| 1534 | // Constructs the matcher from a sequence of element values or |
| 1535 | // element matchers. |
| 1536 | template <typename Iter> |
| 1537 | SomeOfArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} |
| 1538 | |
| 1539 | template <typename U> |
| 1540 | operator Matcher<U>() const { // NOLINT |
| 1541 | using RawU = typename std::decay<U>::type; |
| 1542 | std::vector<Matcher<RawU>> matchers; |
| 1543 | matchers.reserve(matchers_.size()); |
| 1544 | for (const auto& matcher : matchers_) { |
| 1545 | matchers.push_back(MatcherCast<RawU>(matcher)); |
| 1546 | } |
| 1547 | return Matcher<U>(new MatcherImpl<RawU>(std::move(matchers))); |
| 1548 | } |
| 1549 | |
| 1550 | private: |
| 1551 | const std::vector<std::remove_const_t<T>> matchers_; |
| 1552 | }; |
| 1553 | |
| 1554 | template <typename T> |
| 1555 | using AllOfArrayMatcher = SomeOfArrayMatcher<AllOfMatcherImpl, T>; |
| 1556 | |
| 1557 | template <typename T> |
| 1558 | using AnyOfArrayMatcher = SomeOfArrayMatcher<AnyOfMatcherImpl, T>; |
| 1559 | |
| 1560 | // Used for implementing Truly(pred), which turns a predicate into a |
| 1561 | // matcher. |
| 1562 | template <typename Predicate> |
| 1563 | class TrulyMatcher { |
| 1564 | public: |
| 1565 | explicit TrulyMatcher(Predicate pred) : predicate_(pred) {} |
| 1566 | |
| 1567 | // This method template allows Truly(pred) to be used as a matcher |
| 1568 | // for type T where T is the argument type of predicate 'pred'. The |
| 1569 | // argument is passed by reference as the predicate may be |
| 1570 | // interested in the address of the argument. |
| 1571 | template <typename T> |
| 1572 | bool MatchAndExplain(T& x, // NOLINT |
| 1573 | MatchResultListener* listener) const { |
| 1574 | // Without the if-statement, MSVC sometimes warns about converting |
| 1575 | // a value to bool (warning 4800). |
| 1576 | // |
| 1577 | // We cannot write 'return !!predicate_(x);' as that doesn't work |
| 1578 | // when predicate_(x) returns a class convertible to bool but |
| 1579 | // having no operator!(). |
| 1580 | if (predicate_(x)) return true; |
| 1581 | *listener << "didn't satisfy the given predicate" ; |
| 1582 | return false; |
| 1583 | } |
| 1584 | |
| 1585 | void DescribeTo(::std::ostream* os) const { |
| 1586 | *os << "satisfies the given predicate" ; |
| 1587 | } |
| 1588 | |
| 1589 | void DescribeNegationTo(::std::ostream* os) const { |
| 1590 | *os << "doesn't satisfy the given predicate" ; |
| 1591 | } |
| 1592 | |
| 1593 | private: |
| 1594 | Predicate predicate_; |
| 1595 | }; |
| 1596 | |
| 1597 | // Used for implementing Matches(matcher), which turns a matcher into |
| 1598 | // a predicate. |
| 1599 | template <typename M> |
| 1600 | class MatcherAsPredicate { |
| 1601 | public: |
| 1602 | explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {} |
| 1603 | |
| 1604 | // This template operator() allows Matches(m) to be used as a |
| 1605 | // predicate on type T where m is a matcher on type T. |
| 1606 | // |
| 1607 | // The argument x is passed by reference instead of by value, as |
| 1608 | // some matcher may be interested in its address (e.g. as in |
| 1609 | // Matches(Ref(n))(x)). |
| 1610 | template <typename T> |
| 1611 | bool operator()(const T& x) const { |
| 1612 | // We let matcher_ commit to a particular type here instead of |
| 1613 | // when the MatcherAsPredicate object was constructed. This |
| 1614 | // allows us to write Matches(m) where m is a polymorphic matcher |
| 1615 | // (e.g. Eq(5)). |
| 1616 | // |
| 1617 | // If we write Matcher<T>(matcher_).Matches(x) here, it won't |
| 1618 | // compile when matcher_ has type Matcher<const T&>; if we write |
| 1619 | // Matcher<const T&>(matcher_).Matches(x) here, it won't compile |
| 1620 | // when matcher_ has type Matcher<T>; if we just write |
| 1621 | // matcher_.Matches(x), it won't compile when matcher_ is |
| 1622 | // polymorphic, e.g. Eq(5). |
| 1623 | // |
| 1624 | // MatcherCast<const T&>() is necessary for making the code work |
| 1625 | // in all of the above situations. |
| 1626 | return MatcherCast<const T&>(matcher_).Matches(x); |
| 1627 | } |
| 1628 | |
| 1629 | private: |
| 1630 | M matcher_; |
| 1631 | }; |
| 1632 | |
| 1633 | // For implementing ASSERT_THAT() and EXPECT_THAT(). The template |
| 1634 | // argument M must be a type that can be converted to a matcher. |
| 1635 | template <typename M> |
| 1636 | class PredicateFormatterFromMatcher { |
| 1637 | public: |
| 1638 | explicit PredicateFormatterFromMatcher(M m) : matcher_(std::move(m)) {} |
| 1639 | |
| 1640 | // This template () operator allows a PredicateFormatterFromMatcher |
| 1641 | // object to act as a predicate-formatter suitable for using with |
| 1642 | // Google Test's EXPECT_PRED_FORMAT1() macro. |
| 1643 | template <typename T> |
| 1644 | AssertionResult operator()(const char* value_text, const T& x) const { |
| 1645 | // We convert matcher_ to a Matcher<const T&> *now* instead of |
| 1646 | // when the PredicateFormatterFromMatcher object was constructed, |
| 1647 | // as matcher_ may be polymorphic (e.g. NotNull()) and we won't |
| 1648 | // know which type to instantiate it to until we actually see the |
| 1649 | // type of x here. |
| 1650 | // |
| 1651 | // We write SafeMatcherCast<const T&>(matcher_) instead of |
| 1652 | // Matcher<const T&>(matcher_), as the latter won't compile when |
| 1653 | // matcher_ has type Matcher<T> (e.g. An<int>()). |
| 1654 | // We don't write MatcherCast<const T&> either, as that allows |
| 1655 | // potentially unsafe downcasting of the matcher argument. |
| 1656 | const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_); |
| 1657 | |
| 1658 | // The expected path here is that the matcher should match (i.e. that most |
| 1659 | // tests pass) so optimize for this case. |
| 1660 | if (matcher.Matches(x)) { |
| 1661 | return AssertionSuccess(); |
| 1662 | } |
| 1663 | |
| 1664 | ::std::stringstream ss; |
| 1665 | ss << "Value of: " << value_text << "\n" |
| 1666 | << "Expected: " ; |
| 1667 | matcher.DescribeTo(&ss); |
| 1668 | |
| 1669 | // Rerun the matcher to "PrintAndExplain" the failure. |
| 1670 | StringMatchResultListener listener; |
| 1671 | if (MatchPrintAndExplain(x, matcher, &listener)) { |
| 1672 | ss << "\n The matcher failed on the initial attempt; but passed when " |
| 1673 | "rerun to generate the explanation." ; |
| 1674 | } |
| 1675 | ss << "\n Actual: " << listener.str(); |
| 1676 | return AssertionFailure() << ss.str(); |
| 1677 | } |
| 1678 | |
| 1679 | private: |
| 1680 | const M matcher_; |
| 1681 | }; |
| 1682 | |
| 1683 | // A helper function for converting a matcher to a predicate-formatter |
| 1684 | // without the user needing to explicitly write the type. This is |
| 1685 | // used for implementing ASSERT_THAT() and EXPECT_THAT(). |
| 1686 | // Implementation detail: 'matcher' is received by-value to force decaying. |
| 1687 | template <typename M> |
| 1688 | inline PredicateFormatterFromMatcher<M> MakePredicateFormatterFromMatcher( |
| 1689 | M matcher) { |
| 1690 | return PredicateFormatterFromMatcher<M>(std::move(matcher)); |
| 1691 | } |
| 1692 | |
| 1693 | // Implements the polymorphic IsNan() matcher, which matches any floating type |
| 1694 | // value that is Nan. |
| 1695 | class IsNanMatcher { |
| 1696 | public: |
| 1697 | template <typename FloatType> |
| 1698 | bool MatchAndExplain(const FloatType& f, |
| 1699 | MatchResultListener* /* listener */) const { |
| 1700 | return (::std::isnan)(f); |
| 1701 | } |
| 1702 | |
| 1703 | void DescribeTo(::std::ostream* os) const { *os << "is NaN" ; } |
| 1704 | void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NaN" ; } |
| 1705 | }; |
| 1706 | |
| 1707 | // Implements the polymorphic floating point equality matcher, which matches |
| 1708 | // two float values using ULP-based approximation or, optionally, a |
| 1709 | // user-specified epsilon. The template is meant to be instantiated with |
| 1710 | // FloatType being either float or double. |
| 1711 | template <typename FloatType> |
| 1712 | class FloatingEqMatcher { |
| 1713 | public: |
| 1714 | // Constructor for FloatingEqMatcher. |
| 1715 | // The matcher's input will be compared with expected. The matcher treats two |
| 1716 | // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards, |
| 1717 | // equality comparisons between NANs will always return false. We specify a |
| 1718 | // negative max_abs_error_ term to indicate that ULP-based approximation will |
| 1719 | // be used for comparison. |
| 1720 | FloatingEqMatcher(FloatType expected, bool nan_eq_nan) |
| 1721 | : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {} |
| 1722 | |
| 1723 | // Constructor that supports a user-specified max_abs_error that will be used |
| 1724 | // for comparison instead of ULP-based approximation. The max absolute |
| 1725 | // should be non-negative. |
| 1726 | FloatingEqMatcher(FloatType expected, bool nan_eq_nan, |
| 1727 | FloatType max_abs_error) |
| 1728 | : expected_(expected), |
| 1729 | nan_eq_nan_(nan_eq_nan), |
| 1730 | max_abs_error_(max_abs_error) { |
| 1731 | GTEST_CHECK_(max_abs_error >= 0) |
| 1732 | << ", where max_abs_error is" << max_abs_error; |
| 1733 | } |
| 1734 | |
| 1735 | // Implements floating point equality matcher as a Matcher<T>. |
| 1736 | template <typename T> |
| 1737 | class Impl : public MatcherInterface<T> { |
| 1738 | public: |
| 1739 | Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error) |
| 1740 | : expected_(expected), |
| 1741 | nan_eq_nan_(nan_eq_nan), |
| 1742 | max_abs_error_(max_abs_error) {} |
| 1743 | |
| 1744 | bool MatchAndExplain(T value, |
| 1745 | MatchResultListener* listener) const override { |
| 1746 | const FloatingPoint<FloatType> actual(value), expected(expected_); |
| 1747 | |
| 1748 | // Compares NaNs first, if nan_eq_nan_ is true. |
| 1749 | if (actual.is_nan() || expected.is_nan()) { |
| 1750 | if (actual.is_nan() && expected.is_nan()) { |
| 1751 | return nan_eq_nan_; |
| 1752 | } |
| 1753 | // One is nan; the other is not nan. |
| 1754 | return false; |
| 1755 | } |
| 1756 | if (HasMaxAbsError()) { |
| 1757 | // We perform an equality check so that inf will match inf, regardless |
| 1758 | // of error bounds. If the result of value - expected_ would result in |
| 1759 | // overflow or if either value is inf, the default result is infinity, |
| 1760 | // which should only match if max_abs_error_ is also infinity. |
| 1761 | if (value == expected_) { |
| 1762 | return true; |
| 1763 | } |
| 1764 | |
| 1765 | const FloatType diff = value - expected_; |
| 1766 | if (::std::fabs(diff) <= max_abs_error_) { |
| 1767 | return true; |
| 1768 | } |
| 1769 | |
| 1770 | if (listener->IsInterested()) { |
| 1771 | *listener << "which is " << diff << " from " << expected_; |
| 1772 | } |
| 1773 | return false; |
| 1774 | } else { |
| 1775 | return actual.AlmostEquals(expected); |
| 1776 | } |
| 1777 | } |
| 1778 | |
| 1779 | void DescribeTo(::std::ostream* os) const override { |
| 1780 | // os->precision() returns the previously set precision, which we |
| 1781 | // store to restore the ostream to its original configuration |
| 1782 | // after outputting. |
| 1783 | const ::std::streamsize old_precision = |
| 1784 | os->precision(::std::numeric_limits<FloatType>::digits10 + 2); |
| 1785 | if (FloatingPoint<FloatType>(expected_).is_nan()) { |
| 1786 | if (nan_eq_nan_) { |
| 1787 | *os << "is NaN" ; |
| 1788 | } else { |
| 1789 | *os << "never matches" ; |
| 1790 | } |
| 1791 | } else { |
| 1792 | *os << "is approximately " << expected_; |
| 1793 | if (HasMaxAbsError()) { |
| 1794 | *os << " (absolute error <= " << max_abs_error_ << ")" ; |
| 1795 | } |
| 1796 | } |
| 1797 | os->precision(prec: old_precision); |
| 1798 | } |
| 1799 | |
| 1800 | void DescribeNegationTo(::std::ostream* os) const override { |
| 1801 | // As before, get original precision. |
| 1802 | const ::std::streamsize old_precision = |
| 1803 | os->precision(::std::numeric_limits<FloatType>::digits10 + 2); |
| 1804 | if (FloatingPoint<FloatType>(expected_).is_nan()) { |
| 1805 | if (nan_eq_nan_) { |
| 1806 | *os << "isn't NaN" ; |
| 1807 | } else { |
| 1808 | *os << "is anything" ; |
| 1809 | } |
| 1810 | } else { |
| 1811 | *os << "isn't approximately " << expected_; |
| 1812 | if (HasMaxAbsError()) { |
| 1813 | *os << " (absolute error > " << max_abs_error_ << ")" ; |
| 1814 | } |
| 1815 | } |
| 1816 | // Restore original precision. |
| 1817 | os->precision(prec: old_precision); |
| 1818 | } |
| 1819 | |
| 1820 | private: |
| 1821 | bool HasMaxAbsError() const { return max_abs_error_ >= 0; } |
| 1822 | |
| 1823 | const FloatType expected_; |
| 1824 | const bool nan_eq_nan_; |
| 1825 | // max_abs_error will be used for value comparison when >= 0. |
| 1826 | const FloatType max_abs_error_; |
| 1827 | }; |
| 1828 | |
| 1829 | // The following 3 type conversion operators allow FloatEq(expected) and |
| 1830 | // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a |
| 1831 | // Matcher<const float&>, or a Matcher<float&>, but nothing else. |
| 1832 | operator Matcher<FloatType>() const { |
| 1833 | return MakeMatcher( |
| 1834 | new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_)); |
| 1835 | } |
| 1836 | |
| 1837 | operator Matcher<const FloatType&>() const { |
| 1838 | return MakeMatcher( |
| 1839 | new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_)); |
| 1840 | } |
| 1841 | |
| 1842 | operator Matcher<FloatType&>() const { |
| 1843 | return MakeMatcher( |
| 1844 | new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_)); |
| 1845 | } |
| 1846 | |
| 1847 | private: |
| 1848 | const FloatType expected_; |
| 1849 | const bool nan_eq_nan_; |
| 1850 | // max_abs_error will be used for value comparison when >= 0. |
| 1851 | const FloatType max_abs_error_; |
| 1852 | }; |
| 1853 | |
| 1854 | // A 2-tuple ("binary") wrapper around FloatingEqMatcher: |
| 1855 | // FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false) |
| 1856 | // against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e) |
| 1857 | // against y. The former implements "Eq", the latter "Near". At present, there |
| 1858 | // is no version that compares NaNs as equal. |
| 1859 | template <typename FloatType> |
| 1860 | class FloatingEq2Matcher { |
| 1861 | public: |
| 1862 | FloatingEq2Matcher() { Init(max_abs_error_val: -1, nan_eq_nan_val: false); } |
| 1863 | |
| 1864 | explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(max_abs_error_val: -1, nan_eq_nan_val: nan_eq_nan); } |
| 1865 | |
| 1866 | explicit FloatingEq2Matcher(FloatType max_abs_error) { |
| 1867 | Init(max_abs_error_val: max_abs_error, nan_eq_nan_val: false); |
| 1868 | } |
| 1869 | |
| 1870 | FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) { |
| 1871 | Init(max_abs_error_val: max_abs_error, nan_eq_nan_val: nan_eq_nan); |
| 1872 | } |
| 1873 | |
| 1874 | template <typename T1, typename T2> |
| 1875 | operator Matcher<::std::tuple<T1, T2>>() const { |
| 1876 | return MakeMatcher( |
| 1877 | new Impl<::std::tuple<T1, T2>>(max_abs_error_, nan_eq_nan_)); |
| 1878 | } |
| 1879 | template <typename T1, typename T2> |
| 1880 | operator Matcher<const ::std::tuple<T1, T2>&>() const { |
| 1881 | return MakeMatcher( |
| 1882 | new Impl<const ::std::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_)); |
| 1883 | } |
| 1884 | |
| 1885 | private: |
| 1886 | static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT |
| 1887 | return os << "an almost-equal pair" ; |
| 1888 | } |
| 1889 | |
| 1890 | template <typename Tuple> |
| 1891 | class Impl : public MatcherInterface<Tuple> { |
| 1892 | public: |
| 1893 | Impl(FloatType max_abs_error, bool nan_eq_nan) |
| 1894 | : max_abs_error_(max_abs_error), nan_eq_nan_(nan_eq_nan) {} |
| 1895 | |
| 1896 | bool MatchAndExplain(Tuple args, |
| 1897 | MatchResultListener* listener) const override { |
| 1898 | if (max_abs_error_ == -1) { |
| 1899 | FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_); |
| 1900 | return static_cast<Matcher<FloatType>>(fm).MatchAndExplain( |
| 1901 | ::std::get<1>(args), listener); |
| 1902 | } else { |
| 1903 | FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_, |
| 1904 | max_abs_error_); |
| 1905 | return static_cast<Matcher<FloatType>>(fm).MatchAndExplain( |
| 1906 | ::std::get<1>(args), listener); |
| 1907 | } |
| 1908 | } |
| 1909 | void DescribeTo(::std::ostream* os) const override { |
| 1910 | *os << "are " << GetDesc; |
| 1911 | } |
| 1912 | void DescribeNegationTo(::std::ostream* os) const override { |
| 1913 | *os << "aren't " << GetDesc; |
| 1914 | } |
| 1915 | |
| 1916 | private: |
| 1917 | FloatType max_abs_error_; |
| 1918 | const bool nan_eq_nan_; |
| 1919 | }; |
| 1920 | |
| 1921 | void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) { |
| 1922 | max_abs_error_ = max_abs_error_val; |
| 1923 | nan_eq_nan_ = nan_eq_nan_val; |
| 1924 | } |
| 1925 | FloatType max_abs_error_; |
| 1926 | bool nan_eq_nan_; |
| 1927 | }; |
| 1928 | |
| 1929 | // Implements the Pointee(m) matcher for matching a pointer whose |
| 1930 | // pointee matches matcher m. The pointer can be either raw or smart. |
| 1931 | template <typename InnerMatcher> |
| 1932 | class PointeeMatcher { |
| 1933 | public: |
| 1934 | explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {} |
| 1935 | |
| 1936 | // This type conversion operator template allows Pointee(m) to be |
| 1937 | // used as a matcher for any pointer type whose pointee type is |
| 1938 | // compatible with the inner matcher, where type Pointer can be |
| 1939 | // either a raw pointer or a smart pointer. |
| 1940 | // |
| 1941 | // The reason we do this instead of relying on |
| 1942 | // MakePolymorphicMatcher() is that the latter is not flexible |
| 1943 | // enough for implementing the DescribeTo() method of Pointee(). |
| 1944 | template <typename Pointer> |
| 1945 | operator Matcher<Pointer>() const { |
| 1946 | return Matcher<Pointer>(new Impl<const Pointer&>(matcher_)); |
| 1947 | } |
| 1948 | |
| 1949 | private: |
| 1950 | // The monomorphic implementation that works for a particular pointer type. |
| 1951 | template <typename Pointer> |
| 1952 | class Impl : public MatcherInterface<Pointer> { |
| 1953 | public: |
| 1954 | using Pointee = |
| 1955 | typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_( |
| 1956 | Pointer)>::element_type; |
| 1957 | |
| 1958 | explicit Impl(const InnerMatcher& matcher) |
| 1959 | : matcher_(MatcherCast<const Pointee&>(matcher)) {} |
| 1960 | |
| 1961 | void DescribeTo(::std::ostream* os) const override { |
| 1962 | *os << "points to a value that " ; |
| 1963 | matcher_.DescribeTo(os); |
| 1964 | } |
| 1965 | |
| 1966 | void DescribeNegationTo(::std::ostream* os) const override { |
| 1967 | *os << "does not point to a value that " ; |
| 1968 | matcher_.DescribeTo(os); |
| 1969 | } |
| 1970 | |
| 1971 | bool MatchAndExplain(Pointer pointer, |
| 1972 | MatchResultListener* listener) const override { |
| 1973 | if (GetRawPointer(pointer) == nullptr) return false; |
| 1974 | |
| 1975 | *listener << "which points to " ; |
| 1976 | return MatchPrintAndExplain(*pointer, matcher_, listener); |
| 1977 | } |
| 1978 | |
| 1979 | private: |
| 1980 | const Matcher<const Pointee&> matcher_; |
| 1981 | }; |
| 1982 | |
| 1983 | const InnerMatcher matcher_; |
| 1984 | }; |
| 1985 | |
| 1986 | // Implements the Pointer(m) matcher |
| 1987 | // Implements the Pointer(m) matcher for matching a pointer that matches matcher |
| 1988 | // m. The pointer can be either raw or smart, and will match `m` against the |
| 1989 | // raw pointer. |
| 1990 | template <typename InnerMatcher> |
| 1991 | class PointerMatcher { |
| 1992 | public: |
| 1993 | explicit PointerMatcher(const InnerMatcher& matcher) : matcher_(matcher) {} |
| 1994 | |
| 1995 | // This type conversion operator template allows Pointer(m) to be |
| 1996 | // used as a matcher for any pointer type whose pointer type is |
| 1997 | // compatible with the inner matcher, where type PointerType can be |
| 1998 | // either a raw pointer or a smart pointer. |
| 1999 | // |
| 2000 | // The reason we do this instead of relying on |
| 2001 | // MakePolymorphicMatcher() is that the latter is not flexible |
| 2002 | // enough for implementing the DescribeTo() method of Pointer(). |
| 2003 | template <typename PointerType> |
| 2004 | operator Matcher<PointerType>() const { // NOLINT |
| 2005 | return Matcher<PointerType>(new Impl<const PointerType&>(matcher_)); |
| 2006 | } |
| 2007 | |
| 2008 | private: |
| 2009 | // The monomorphic implementation that works for a particular pointer type. |
| 2010 | template <typename PointerType> |
| 2011 | class Impl : public MatcherInterface<PointerType> { |
| 2012 | public: |
| 2013 | using Pointer = |
| 2014 | const typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_( |
| 2015 | PointerType)>::element_type*; |
| 2016 | |
| 2017 | explicit Impl(const InnerMatcher& matcher) |
| 2018 | : matcher_(MatcherCast<Pointer>(matcher)) {} |
| 2019 | |
| 2020 | void DescribeTo(::std::ostream* os) const override { |
| 2021 | *os << "is a pointer that " ; |
| 2022 | matcher_.DescribeTo(os); |
| 2023 | } |
| 2024 | |
| 2025 | void DescribeNegationTo(::std::ostream* os) const override { |
| 2026 | *os << "is not a pointer that " ; |
| 2027 | matcher_.DescribeTo(os); |
| 2028 | } |
| 2029 | |
| 2030 | bool MatchAndExplain(PointerType pointer, |
| 2031 | MatchResultListener* listener) const override { |
| 2032 | *listener << "which is a pointer that " ; |
| 2033 | Pointer p = GetRawPointer(pointer); |
| 2034 | return MatchPrintAndExplain(p, matcher_, listener); |
| 2035 | } |
| 2036 | |
| 2037 | private: |
| 2038 | Matcher<Pointer> matcher_; |
| 2039 | }; |
| 2040 | |
| 2041 | const InnerMatcher matcher_; |
| 2042 | }; |
| 2043 | |
| 2044 | #if GTEST_HAS_RTTI |
| 2045 | // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or |
| 2046 | // reference that matches inner_matcher when dynamic_cast<T> is applied. |
| 2047 | // The result of dynamic_cast<To> is forwarded to the inner matcher. |
| 2048 | // If To is a pointer and the cast fails, the inner matcher will receive NULL. |
| 2049 | // If To is a reference and the cast fails, this matcher returns false |
| 2050 | // immediately. |
| 2051 | template <typename To> |
| 2052 | class WhenDynamicCastToMatcherBase { |
| 2053 | public: |
| 2054 | explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher) |
| 2055 | : matcher_(matcher) {} |
| 2056 | |
| 2057 | void DescribeTo(::std::ostream* os) const { |
| 2058 | GetCastTypeDescription(os); |
| 2059 | matcher_.DescribeTo(os); |
| 2060 | } |
| 2061 | |
| 2062 | void DescribeNegationTo(::std::ostream* os) const { |
| 2063 | GetCastTypeDescription(os); |
| 2064 | matcher_.DescribeNegationTo(os); |
| 2065 | } |
| 2066 | |
| 2067 | protected: |
| 2068 | const Matcher<To> matcher_; |
| 2069 | |
| 2070 | static std::string GetToName() { return GetTypeName<To>(); } |
| 2071 | |
| 2072 | private: |
| 2073 | static void GetCastTypeDescription(::std::ostream* os) { |
| 2074 | *os << "when dynamic_cast to " << GetToName() << ", " ; |
| 2075 | } |
| 2076 | }; |
| 2077 | |
| 2078 | // Primary template. |
| 2079 | // To is a pointer. Cast and forward the result. |
| 2080 | template <typename To> |
| 2081 | class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> { |
| 2082 | public: |
| 2083 | explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher) |
| 2084 | : WhenDynamicCastToMatcherBase<To>(matcher) {} |
| 2085 | |
| 2086 | template <typename From> |
| 2087 | bool MatchAndExplain(From from, MatchResultListener* listener) const { |
| 2088 | To to = dynamic_cast<To>(from); |
| 2089 | return MatchPrintAndExplain(to, this->matcher_, listener); |
| 2090 | } |
| 2091 | }; |
| 2092 | |
| 2093 | // Specialize for references. |
| 2094 | // In this case we return false if the dynamic_cast fails. |
| 2095 | template <typename To> |
| 2096 | class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> { |
| 2097 | public: |
| 2098 | explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher) |
| 2099 | : WhenDynamicCastToMatcherBase<To&>(matcher) {} |
| 2100 | |
| 2101 | template <typename From> |
| 2102 | bool MatchAndExplain(From& from, MatchResultListener* listener) const { |
| 2103 | // We don't want an std::bad_cast here, so do the cast with pointers. |
| 2104 | To* to = dynamic_cast<To*>(&from); |
| 2105 | if (to == nullptr) { |
| 2106 | *listener << "which cannot be dynamic_cast to " << this->GetToName(); |
| 2107 | return false; |
| 2108 | } |
| 2109 | return MatchPrintAndExplain(*to, this->matcher_, listener); |
| 2110 | } |
| 2111 | }; |
| 2112 | #endif // GTEST_HAS_RTTI |
| 2113 | |
| 2114 | // Implements the Field() matcher for matching a field (i.e. member |
| 2115 | // variable) of an object. |
| 2116 | template <typename Class, typename FieldType> |
| 2117 | class FieldMatcher { |
| 2118 | public: |
| 2119 | FieldMatcher(FieldType Class::* field, |
| 2120 | const Matcher<const FieldType&>& matcher) |
| 2121 | : field_(field), matcher_(matcher), whose_field_("whose given field " ) {} |
| 2122 | |
| 2123 | FieldMatcher(const std::string& field_name, FieldType Class::* field, |
| 2124 | const Matcher<const FieldType&>& matcher) |
| 2125 | : field_(field), |
| 2126 | matcher_(matcher), |
| 2127 | whose_field_("whose field `" + field_name + "` " ) {} |
| 2128 | |
| 2129 | void DescribeTo(::std::ostream* os) const { |
| 2130 | *os << "is an object " << whose_field_; |
| 2131 | matcher_.DescribeTo(os); |
| 2132 | } |
| 2133 | |
| 2134 | void DescribeNegationTo(::std::ostream* os) const { |
| 2135 | *os << "is an object " << whose_field_; |
| 2136 | matcher_.DescribeNegationTo(os); |
| 2137 | } |
| 2138 | |
| 2139 | template <typename T> |
| 2140 | bool MatchAndExplain(const T& value, MatchResultListener* listener) const { |
| 2141 | // FIXME: The dispatch on std::is_pointer was introduced as a workaround for |
| 2142 | // a compiler bug, and can now be removed. |
| 2143 | return MatchAndExplainImpl( |
| 2144 | typename std::is_pointer<typename std::remove_const<T>::type>::type(), |
| 2145 | value, listener); |
| 2146 | } |
| 2147 | |
| 2148 | private: |
| 2149 | bool MatchAndExplainImpl(std::false_type /* is_not_pointer */, |
| 2150 | const Class& obj, |
| 2151 | MatchResultListener* listener) const { |
| 2152 | *listener << whose_field_ << "is " ; |
| 2153 | return MatchPrintAndExplain(obj.*field_, matcher_, listener); |
| 2154 | } |
| 2155 | |
| 2156 | bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p, |
| 2157 | MatchResultListener* listener) const { |
| 2158 | if (p == nullptr) return false; |
| 2159 | |
| 2160 | *listener << "which points to an object " ; |
| 2161 | // Since *p has a field, it must be a class/struct/union type and |
| 2162 | // thus cannot be a pointer. Therefore we pass false_type() as |
| 2163 | // the first argument. |
| 2164 | return MatchAndExplainImpl(std::false_type(), *p, listener); |
| 2165 | } |
| 2166 | |
| 2167 | const FieldType Class::* field_; |
| 2168 | const Matcher<const FieldType&> matcher_; |
| 2169 | |
| 2170 | // Contains either "whose given field " if the name of the field is unknown |
| 2171 | // or "whose field `name_of_field` " if the name is known. |
| 2172 | const std::string whose_field_; |
| 2173 | }; |
| 2174 | |
| 2175 | // Implements the Property() matcher for matching a property |
| 2176 | // (i.e. return value of a getter method) of an object. |
| 2177 | // |
| 2178 | // Property is a const-qualified member function of Class returning |
| 2179 | // PropertyType. |
| 2180 | template <typename Class, typename PropertyType, typename Property> |
| 2181 | class PropertyMatcher { |
| 2182 | public: |
| 2183 | typedef const PropertyType& RefToConstProperty; |
| 2184 | |
| 2185 | PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher) |
| 2186 | : property_(property), |
| 2187 | matcher_(matcher), |
| 2188 | whose_property_("whose given property " ) {} |
| 2189 | |
| 2190 | PropertyMatcher(const std::string& property_name, Property property, |
| 2191 | const Matcher<RefToConstProperty>& matcher) |
| 2192 | : property_(property), |
| 2193 | matcher_(matcher), |
| 2194 | whose_property_("whose property `" + property_name + "` " ) {} |
| 2195 | |
| 2196 | void DescribeTo(::std::ostream* os) const { |
| 2197 | *os << "is an object " << whose_property_; |
| 2198 | matcher_.DescribeTo(os); |
| 2199 | } |
| 2200 | |
| 2201 | void DescribeNegationTo(::std::ostream* os) const { |
| 2202 | *os << "is an object " << whose_property_; |
| 2203 | matcher_.DescribeNegationTo(os); |
| 2204 | } |
| 2205 | |
| 2206 | template <typename T> |
| 2207 | bool MatchAndExplain(const T& value, MatchResultListener* listener) const { |
| 2208 | return MatchAndExplainImpl( |
| 2209 | typename std::is_pointer<typename std::remove_const<T>::type>::type(), |
| 2210 | value, listener); |
| 2211 | } |
| 2212 | |
| 2213 | private: |
| 2214 | bool MatchAndExplainImpl(std::false_type /* is_not_pointer */, |
| 2215 | const Class& obj, |
| 2216 | MatchResultListener* listener) const { |
| 2217 | *listener << whose_property_ << "is " ; |
| 2218 | // Cannot pass the return value (for example, int) to MatchPrintAndExplain, |
| 2219 | // which takes a non-const reference as argument. |
| 2220 | RefToConstProperty result = (obj.*property_)(); |
| 2221 | return MatchPrintAndExplain(result, matcher_, listener); |
| 2222 | } |
| 2223 | |
| 2224 | bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p, |
| 2225 | MatchResultListener* listener) const { |
| 2226 | if (p == nullptr) return false; |
| 2227 | |
| 2228 | *listener << "which points to an object " ; |
| 2229 | // Since *p has a property method, it must be a class/struct/union |
| 2230 | // type and thus cannot be a pointer. Therefore we pass |
| 2231 | // false_type() as the first argument. |
| 2232 | return MatchAndExplainImpl(std::false_type(), *p, listener); |
| 2233 | } |
| 2234 | |
| 2235 | Property property_; |
| 2236 | const Matcher<RefToConstProperty> matcher_; |
| 2237 | |
| 2238 | // Contains either "whose given property " if the name of the property is |
| 2239 | // unknown or "whose property `name_of_property` " if the name is known. |
| 2240 | const std::string whose_property_; |
| 2241 | }; |
| 2242 | |
| 2243 | // Type traits specifying various features of different functors for ResultOf. |
| 2244 | // The default template specifies features for functor objects. |
| 2245 | template <typename Functor> |
| 2246 | struct CallableTraits { |
| 2247 | typedef Functor StorageType; |
| 2248 | |
| 2249 | static void CheckIsValid(Functor /* functor */) {} |
| 2250 | |
| 2251 | template <typename T> |
| 2252 | static auto Invoke(Functor f, const T& arg) -> decltype(f(arg)) { |
| 2253 | return f(arg); |
| 2254 | } |
| 2255 | }; |
| 2256 | |
| 2257 | // Specialization for function pointers. |
| 2258 | template <typename ArgType, typename ResType> |
| 2259 | struct CallableTraits<ResType (*)(ArgType)> { |
| 2260 | typedef ResType ResultType; |
| 2261 | typedef ResType (*StorageType)(ArgType); |
| 2262 | |
| 2263 | static void CheckIsValid(ResType (*f)(ArgType)) { |
| 2264 | GTEST_CHECK_(f != nullptr) |
| 2265 | << "NULL function pointer is passed into ResultOf()." ; |
| 2266 | } |
| 2267 | template <typename T> |
| 2268 | static ResType Invoke(ResType (*f)(ArgType), T arg) { |
| 2269 | return (*f)(arg); |
| 2270 | } |
| 2271 | }; |
| 2272 | |
| 2273 | // Implements the ResultOf() matcher for matching a return value of a |
| 2274 | // unary function of an object. |
| 2275 | template <typename Callable, typename InnerMatcher> |
| 2276 | class ResultOfMatcher { |
| 2277 | public: |
| 2278 | ResultOfMatcher(Callable callable, InnerMatcher matcher) |
| 2279 | : ResultOfMatcher(/*result_description=*/"" , std::move(callable), |
| 2280 | std::move(matcher)) {} |
| 2281 | |
| 2282 | ResultOfMatcher(const std::string& result_description, Callable callable, |
| 2283 | InnerMatcher matcher) |
| 2284 | : result_description_(result_description), |
| 2285 | callable_(std::move(callable)), |
| 2286 | matcher_(std::move(matcher)) { |
| 2287 | CallableTraits<Callable>::CheckIsValid(callable_); |
| 2288 | } |
| 2289 | |
| 2290 | template <typename T> |
| 2291 | operator Matcher<T>() const { |
| 2292 | return Matcher<T>( |
| 2293 | new Impl<const T&>(result_description_, callable_, matcher_)); |
| 2294 | } |
| 2295 | |
| 2296 | private: |
| 2297 | typedef typename CallableTraits<Callable>::StorageType CallableStorageType; |
| 2298 | |
| 2299 | template <typename T> |
| 2300 | class Impl : public MatcherInterface<T> { |
| 2301 | using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>( |
| 2302 | std::declval<CallableStorageType>(), std::declval<T>())); |
| 2303 | using InnerType = std::conditional_t< |
| 2304 | std::is_lvalue_reference<ResultType>::value, |
| 2305 | const typename std::remove_reference<ResultType>::type&, ResultType>; |
| 2306 | |
| 2307 | public: |
| 2308 | template <typename M> |
| 2309 | Impl(const std::string& result_description, |
| 2310 | const CallableStorageType& callable, const M& matcher) |
| 2311 | : result_description_(result_description), |
| 2312 | callable_(callable), |
| 2313 | matcher_(MatcherCast<InnerType>(matcher)) {} |
| 2314 | |
| 2315 | void DescribeTo(::std::ostream* os) const override { |
| 2316 | if (result_description_.empty()) { |
| 2317 | *os << "is mapped by the given callable to a value that " ; |
| 2318 | } else { |
| 2319 | *os << "whose " << result_description_ << " " ; |
| 2320 | } |
| 2321 | matcher_.DescribeTo(os); |
| 2322 | } |
| 2323 | |
| 2324 | void DescribeNegationTo(::std::ostream* os) const override { |
| 2325 | if (result_description_.empty()) { |
| 2326 | *os << "is mapped by the given callable to a value that " ; |
| 2327 | } else { |
| 2328 | *os << "whose " << result_description_ << " " ; |
| 2329 | } |
| 2330 | matcher_.DescribeNegationTo(os); |
| 2331 | } |
| 2332 | |
| 2333 | bool MatchAndExplain(T obj, MatchResultListener* listener) const override { |
| 2334 | if (result_description_.empty()) { |
| 2335 | *listener << "which is mapped by the given callable to " ; |
| 2336 | } else { |
| 2337 | *listener << "whose " << result_description_ << " is " ; |
| 2338 | } |
| 2339 | // Cannot pass the return value directly to MatchPrintAndExplain, which |
| 2340 | // takes a non-const reference as argument. |
| 2341 | // Also, specifying template argument explicitly is needed because T could |
| 2342 | // be a non-const reference (e.g. Matcher<Uncopyable&>). |
| 2343 | InnerType result = |
| 2344 | CallableTraits<Callable>::template Invoke<T>(callable_, obj); |
| 2345 | return MatchPrintAndExplain(result, matcher_, listener); |
| 2346 | } |
| 2347 | |
| 2348 | private: |
| 2349 | const std::string result_description_; |
| 2350 | // Functors often define operator() as non-const method even though |
| 2351 | // they are actually stateless. But we need to use them even when |
| 2352 | // 'this' is a const pointer. It's the user's responsibility not to |
| 2353 | // use stateful callables with ResultOf(), which doesn't guarantee |
| 2354 | // how many times the callable will be invoked. |
| 2355 | mutable CallableStorageType callable_; |
| 2356 | const Matcher<InnerType> matcher_; |
| 2357 | }; // class Impl |
| 2358 | |
| 2359 | const std::string result_description_; |
| 2360 | const CallableStorageType callable_; |
| 2361 | const InnerMatcher matcher_; |
| 2362 | }; |
| 2363 | |
| 2364 | // Implements a matcher that checks the size of an STL-style container. |
| 2365 | template <typename SizeMatcher> |
| 2366 | class SizeIsMatcher { |
| 2367 | public: |
| 2368 | explicit SizeIsMatcher(const SizeMatcher& size_matcher) |
| 2369 | : size_matcher_(size_matcher) {} |
| 2370 | |
| 2371 | template <typename Container> |
| 2372 | operator Matcher<Container>() const { |
| 2373 | return Matcher<Container>(new Impl<const Container&>(size_matcher_)); |
| 2374 | } |
| 2375 | |
| 2376 | template <typename Container> |
| 2377 | class Impl : public MatcherInterface<Container> { |
| 2378 | public: |
| 2379 | using SizeType = decltype(std::declval<Container>().size()); |
| 2380 | explicit Impl(const SizeMatcher& size_matcher) |
| 2381 | : size_matcher_(MatcherCast<SizeType>(size_matcher)) {} |
| 2382 | |
| 2383 | void DescribeTo(::std::ostream* os) const override { |
| 2384 | *os << "has a size that " ; |
| 2385 | size_matcher_.DescribeTo(os); |
| 2386 | } |
| 2387 | void DescribeNegationTo(::std::ostream* os) const override { |
| 2388 | *os << "has a size that " ; |
| 2389 | size_matcher_.DescribeNegationTo(os); |
| 2390 | } |
| 2391 | |
| 2392 | bool MatchAndExplain(Container container, |
| 2393 | MatchResultListener* listener) const override { |
| 2394 | SizeType size = container.size(); |
| 2395 | StringMatchResultListener size_listener; |
| 2396 | const bool result = size_matcher_.MatchAndExplain(size, &size_listener); |
| 2397 | *listener << "whose size " << size |
| 2398 | << (result ? " matches" : " doesn't match" ); |
| 2399 | PrintIfNotEmpty(explanation: size_listener.str(), os: listener->stream()); |
| 2400 | return result; |
| 2401 | } |
| 2402 | |
| 2403 | private: |
| 2404 | const Matcher<SizeType> size_matcher_; |
| 2405 | }; |
| 2406 | |
| 2407 | private: |
| 2408 | const SizeMatcher size_matcher_; |
| 2409 | }; |
| 2410 | |
| 2411 | // Implements a matcher that checks the begin()..end() distance of an STL-style |
| 2412 | // container. |
| 2413 | template <typename DistanceMatcher> |
| 2414 | class BeginEndDistanceIsMatcher { |
| 2415 | public: |
| 2416 | explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher) |
| 2417 | : distance_matcher_(distance_matcher) {} |
| 2418 | |
| 2419 | template <typename Container> |
| 2420 | operator Matcher<Container>() const { |
| 2421 | return Matcher<Container>(new Impl<const Container&>(distance_matcher_)); |
| 2422 | } |
| 2423 | |
| 2424 | template <typename Container> |
| 2425 | class Impl : public MatcherInterface<Container> { |
| 2426 | public: |
| 2427 | typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_( |
| 2428 | Container)> |
| 2429 | ContainerView; |
| 2430 | typedef typename std::iterator_traits< |
| 2431 | typename ContainerView::type::const_iterator>::difference_type |
| 2432 | DistanceType; |
| 2433 | explicit Impl(const DistanceMatcher& distance_matcher) |
| 2434 | : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {} |
| 2435 | |
| 2436 | void DescribeTo(::std::ostream* os) const override { |
| 2437 | *os << "distance between begin() and end() " ; |
| 2438 | distance_matcher_.DescribeTo(os); |
| 2439 | } |
| 2440 | void DescribeNegationTo(::std::ostream* os) const override { |
| 2441 | *os << "distance between begin() and end() " ; |
| 2442 | distance_matcher_.DescribeNegationTo(os); |
| 2443 | } |
| 2444 | |
| 2445 | bool MatchAndExplain(Container container, |
| 2446 | MatchResultListener* listener) const override { |
| 2447 | using std::begin; |
| 2448 | using std::end; |
| 2449 | DistanceType distance = std::distance(begin(container), end(container)); |
| 2450 | StringMatchResultListener distance_listener; |
| 2451 | const bool result = |
| 2452 | distance_matcher_.MatchAndExplain(distance, &distance_listener); |
| 2453 | *listener << "whose distance between begin() and end() " << distance |
| 2454 | << (result ? " matches" : " doesn't match" ); |
| 2455 | PrintIfNotEmpty(explanation: distance_listener.str(), os: listener->stream()); |
| 2456 | return result; |
| 2457 | } |
| 2458 | |
| 2459 | private: |
| 2460 | const Matcher<DistanceType> distance_matcher_; |
| 2461 | }; |
| 2462 | |
| 2463 | private: |
| 2464 | const DistanceMatcher distance_matcher_; |
| 2465 | }; |
| 2466 | |
| 2467 | // Implements an equality matcher for any STL-style container whose elements |
| 2468 | // support ==. This matcher is like Eq(), but its failure explanations provide |
| 2469 | // more detailed information that is useful when the container is used as a set. |
| 2470 | // The failure message reports elements that are in one of the operands but not |
| 2471 | // the other. The failure messages do not report duplicate or out-of-order |
| 2472 | // elements in the containers (which don't properly matter to sets, but can |
| 2473 | // occur if the containers are vectors or lists, for example). |
| 2474 | // |
| 2475 | // Uses the container's const_iterator, value_type, operator ==, |
| 2476 | // begin(), and end(). |
| 2477 | template <typename Container> |
| 2478 | class ContainerEqMatcher { |
| 2479 | public: |
| 2480 | typedef internal::StlContainerView<Container> View; |
| 2481 | typedef typename View::type StlContainer; |
| 2482 | typedef typename View::const_reference StlContainerReference; |
| 2483 | |
| 2484 | static_assert(!std::is_const<Container>::value, |
| 2485 | "Container type must not be const" ); |
| 2486 | static_assert(!std::is_reference<Container>::value, |
| 2487 | "Container type must not be a reference" ); |
| 2488 | |
| 2489 | // We make a copy of expected in case the elements in it are modified |
| 2490 | // after this matcher is created. |
| 2491 | explicit ContainerEqMatcher(const Container& expected) |
| 2492 | : expected_(View::Copy(expected)) {} |
| 2493 | |
| 2494 | void DescribeTo(::std::ostream* os) const { |
| 2495 | *os << "equals " ; |
| 2496 | UniversalPrint(expected_, os); |
| 2497 | } |
| 2498 | void DescribeNegationTo(::std::ostream* os) const { |
| 2499 | *os << "does not equal " ; |
| 2500 | UniversalPrint(expected_, os); |
| 2501 | } |
| 2502 | |
| 2503 | template <typename LhsContainer> |
| 2504 | bool MatchAndExplain(const LhsContainer& lhs, |
| 2505 | MatchResultListener* listener) const { |
| 2506 | typedef internal::StlContainerView< |
| 2507 | typename std::remove_const<LhsContainer>::type> |
| 2508 | LhsView; |
| 2509 | StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); |
| 2510 | if (lhs_stl_container == expected_) return true; |
| 2511 | |
| 2512 | ::std::ostream* const os = listener->stream(); |
| 2513 | if (os != nullptr) { |
| 2514 | // Something is different. Check for extra values first. |
| 2515 | bool = false; |
| 2516 | for (auto it = lhs_stl_container.begin(); it != lhs_stl_container.end(); |
| 2517 | ++it) { |
| 2518 | if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) == |
| 2519 | expected_.end()) { |
| 2520 | if (printed_header) { |
| 2521 | *os << ", " ; |
| 2522 | } else { |
| 2523 | *os << "which has these unexpected elements: " ; |
| 2524 | printed_header = true; |
| 2525 | } |
| 2526 | UniversalPrint(*it, os); |
| 2527 | } |
| 2528 | } |
| 2529 | |
| 2530 | // Now check for missing values. |
| 2531 | bool = false; |
| 2532 | for (auto it = expected_.begin(); it != expected_.end(); ++it) { |
| 2533 | if (internal::ArrayAwareFind(lhs_stl_container.begin(), |
| 2534 | lhs_stl_container.end(), |
| 2535 | *it) == lhs_stl_container.end()) { |
| 2536 | if (printed_header2) { |
| 2537 | *os << ", " ; |
| 2538 | } else { |
| 2539 | *os << (printed_header ? ",\nand" : "which" ) |
| 2540 | << " doesn't have these expected elements: " ; |
| 2541 | printed_header2 = true; |
| 2542 | } |
| 2543 | UniversalPrint(*it, os); |
| 2544 | } |
| 2545 | } |
| 2546 | } |
| 2547 | |
| 2548 | return false; |
| 2549 | } |
| 2550 | |
| 2551 | private: |
| 2552 | const StlContainer expected_; |
| 2553 | }; |
| 2554 | |
| 2555 | // A comparator functor that uses the < operator to compare two values. |
| 2556 | struct LessComparator { |
| 2557 | template <typename T, typename U> |
| 2558 | bool operator()(const T& lhs, const U& rhs) const { |
| 2559 | return lhs < rhs; |
| 2560 | } |
| 2561 | }; |
| 2562 | |
| 2563 | // Implements WhenSortedBy(comparator, container_matcher). |
| 2564 | template <typename Comparator, typename ContainerMatcher> |
| 2565 | class WhenSortedByMatcher { |
| 2566 | public: |
| 2567 | WhenSortedByMatcher(const Comparator& comparator, |
| 2568 | const ContainerMatcher& matcher) |
| 2569 | : comparator_(comparator), matcher_(matcher) {} |
| 2570 | |
| 2571 | template <typename LhsContainer> |
| 2572 | operator Matcher<LhsContainer>() const { |
| 2573 | return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_)); |
| 2574 | } |
| 2575 | |
| 2576 | template <typename LhsContainer> |
| 2577 | class Impl : public MatcherInterface<LhsContainer> { |
| 2578 | public: |
| 2579 | typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_( |
| 2580 | LhsContainer)> |
| 2581 | LhsView; |
| 2582 | typedef typename LhsView::type LhsStlContainer; |
| 2583 | typedef typename LhsView::const_reference LhsStlContainerReference; |
| 2584 | // Transforms std::pair<const Key, Value> into std::pair<Key, Value> |
| 2585 | // so that we can match associative containers. |
| 2586 | typedef |
| 2587 | typename RemoveConstFromKey<typename LhsStlContainer::value_type>::type |
| 2588 | LhsValue; |
| 2589 | |
| 2590 | Impl(const Comparator& comparator, const ContainerMatcher& matcher) |
| 2591 | : comparator_(comparator), matcher_(matcher) {} |
| 2592 | |
| 2593 | void DescribeTo(::std::ostream* os) const override { |
| 2594 | *os << "(when sorted) " ; |
| 2595 | matcher_.DescribeTo(os); |
| 2596 | } |
| 2597 | |
| 2598 | void DescribeNegationTo(::std::ostream* os) const override { |
| 2599 | *os << "(when sorted) " ; |
| 2600 | matcher_.DescribeNegationTo(os); |
| 2601 | } |
| 2602 | |
| 2603 | bool MatchAndExplain(LhsContainer lhs, |
| 2604 | MatchResultListener* listener) const override { |
| 2605 | LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); |
| 2606 | ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(), |
| 2607 | lhs_stl_container.end()); |
| 2608 | ::std::sort(sorted_container.begin(), sorted_container.end(), |
| 2609 | comparator_); |
| 2610 | |
| 2611 | if (!listener->IsInterested()) { |
| 2612 | // If the listener is not interested, we do not need to |
| 2613 | // construct the inner explanation. |
| 2614 | return matcher_.Matches(sorted_container); |
| 2615 | } |
| 2616 | |
| 2617 | *listener << "which is " ; |
| 2618 | UniversalPrint(sorted_container, listener->stream()); |
| 2619 | *listener << " when sorted" ; |
| 2620 | |
| 2621 | StringMatchResultListener inner_listener; |
| 2622 | const bool match = |
| 2623 | matcher_.MatchAndExplain(sorted_container, &inner_listener); |
| 2624 | PrintIfNotEmpty(explanation: inner_listener.str(), os: listener->stream()); |
| 2625 | return match; |
| 2626 | } |
| 2627 | |
| 2628 | private: |
| 2629 | const Comparator comparator_; |
| 2630 | const Matcher<const ::std::vector<LhsValue>&> matcher_; |
| 2631 | |
| 2632 | Impl(const Impl&) = delete; |
| 2633 | Impl& operator=(const Impl&) = delete; |
| 2634 | }; |
| 2635 | |
| 2636 | private: |
| 2637 | const Comparator comparator_; |
| 2638 | const ContainerMatcher matcher_; |
| 2639 | }; |
| 2640 | |
| 2641 | // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher |
| 2642 | // must be able to be safely cast to Matcher<std::tuple<const T1&, const |
| 2643 | // T2&> >, where T1 and T2 are the types of elements in the LHS |
| 2644 | // container and the RHS container respectively. |
| 2645 | template <typename TupleMatcher, typename RhsContainer> |
| 2646 | class PointwiseMatcher { |
| 2647 | static_assert( |
| 2648 | !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value, |
| 2649 | "use UnorderedPointwise with hash tables" ); |
| 2650 | |
| 2651 | public: |
| 2652 | typedef internal::StlContainerView<RhsContainer> RhsView; |
| 2653 | typedef typename RhsView::type RhsStlContainer; |
| 2654 | typedef typename RhsStlContainer::value_type RhsValue; |
| 2655 | |
| 2656 | static_assert(!std::is_const<RhsContainer>::value, |
| 2657 | "RhsContainer type must not be const" ); |
| 2658 | static_assert(!std::is_reference<RhsContainer>::value, |
| 2659 | "RhsContainer type must not be a reference" ); |
| 2660 | |
| 2661 | // Like ContainerEq, we make a copy of rhs in case the elements in |
| 2662 | // it are modified after this matcher is created. |
| 2663 | PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs) |
| 2664 | : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {} |
| 2665 | |
| 2666 | template <typename LhsContainer> |
| 2667 | operator Matcher<LhsContainer>() const { |
| 2668 | static_assert( |
| 2669 | !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value, |
| 2670 | "use UnorderedPointwise with hash tables" ); |
| 2671 | |
| 2672 | return Matcher<LhsContainer>( |
| 2673 | new Impl<const LhsContainer&>(tuple_matcher_, rhs_)); |
| 2674 | } |
| 2675 | |
| 2676 | template <typename LhsContainer> |
| 2677 | class Impl : public MatcherInterface<LhsContainer> { |
| 2678 | public: |
| 2679 | typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_( |
| 2680 | LhsContainer)> |
| 2681 | LhsView; |
| 2682 | typedef typename LhsView::type LhsStlContainer; |
| 2683 | typedef typename LhsView::const_reference LhsStlContainerReference; |
| 2684 | typedef typename LhsStlContainer::value_type LhsValue; |
| 2685 | // We pass the LHS value and the RHS value to the inner matcher by |
| 2686 | // reference, as they may be expensive to copy. We must use tuple |
| 2687 | // instead of pair here, as a pair cannot hold references (C++ 98, |
| 2688 | // 20.2.2 [lib.pairs]). |
| 2689 | typedef ::std::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg; |
| 2690 | |
| 2691 | Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs) |
| 2692 | // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher. |
| 2693 | : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)), |
| 2694 | rhs_(rhs) {} |
| 2695 | |
| 2696 | void DescribeTo(::std::ostream* os) const override { |
| 2697 | *os << "contains " << rhs_.size() |
| 2698 | << " values, where each value and its corresponding value in " ; |
| 2699 | UniversalPrinter<RhsStlContainer>::Print(rhs_, os); |
| 2700 | *os << " " ; |
| 2701 | mono_tuple_matcher_.DescribeTo(os); |
| 2702 | } |
| 2703 | void DescribeNegationTo(::std::ostream* os) const override { |
| 2704 | *os << "doesn't contain exactly " << rhs_.size() |
| 2705 | << " values, or contains a value x at some index i" |
| 2706 | << " where x and the i-th value of " ; |
| 2707 | UniversalPrint(rhs_, os); |
| 2708 | *os << " " ; |
| 2709 | mono_tuple_matcher_.DescribeNegationTo(os); |
| 2710 | } |
| 2711 | |
| 2712 | bool MatchAndExplain(LhsContainer lhs, |
| 2713 | MatchResultListener* listener) const override { |
| 2714 | LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); |
| 2715 | const size_t actual_size = lhs_stl_container.size(); |
| 2716 | if (actual_size != rhs_.size()) { |
| 2717 | *listener << "which contains " << actual_size << " values" ; |
| 2718 | return false; |
| 2719 | } |
| 2720 | |
| 2721 | auto left = lhs_stl_container.begin(); |
| 2722 | auto right = rhs_.begin(); |
| 2723 | for (size_t i = 0; i != actual_size; ++i, ++left, ++right) { |
| 2724 | if (listener->IsInterested()) { |
| 2725 | StringMatchResultListener inner_listener; |
| 2726 | // Create InnerMatcherArg as a temporarily object to avoid it outlives |
| 2727 | // *left and *right. Dereference or the conversion to `const T&` may |
| 2728 | // return temp objects, e.g. for vector<bool>. |
| 2729 | if (!mono_tuple_matcher_.MatchAndExplain( |
| 2730 | InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left), |
| 2731 | ImplicitCast_<const RhsValue&>(*right)), |
| 2732 | &inner_listener)) { |
| 2733 | *listener << "where the value pair (" ; |
| 2734 | UniversalPrint(*left, listener->stream()); |
| 2735 | *listener << ", " ; |
| 2736 | UniversalPrint(*right, listener->stream()); |
| 2737 | *listener << ") at index #" << i << " don't match" ; |
| 2738 | PrintIfNotEmpty(explanation: inner_listener.str(), os: listener->stream()); |
| 2739 | return false; |
| 2740 | } |
| 2741 | } else { |
| 2742 | if (!mono_tuple_matcher_.Matches( |
| 2743 | InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left), |
| 2744 | ImplicitCast_<const RhsValue&>(*right)))) |
| 2745 | return false; |
| 2746 | } |
| 2747 | } |
| 2748 | |
| 2749 | return true; |
| 2750 | } |
| 2751 | |
| 2752 | private: |
| 2753 | const Matcher<InnerMatcherArg> mono_tuple_matcher_; |
| 2754 | const RhsStlContainer rhs_; |
| 2755 | }; |
| 2756 | |
| 2757 | private: |
| 2758 | const TupleMatcher tuple_matcher_; |
| 2759 | const RhsStlContainer rhs_; |
| 2760 | }; |
| 2761 | |
| 2762 | // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl. |
| 2763 | template <typename Container> |
| 2764 | class QuantifierMatcherImpl : public MatcherInterface<Container> { |
| 2765 | public: |
| 2766 | typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; |
| 2767 | typedef StlContainerView<RawContainer> View; |
| 2768 | typedef typename View::type StlContainer; |
| 2769 | typedef typename View::const_reference StlContainerReference; |
| 2770 | typedef typename StlContainer::value_type Element; |
| 2771 | |
| 2772 | template <typename InnerMatcher> |
| 2773 | explicit QuantifierMatcherImpl(InnerMatcher inner_matcher) |
| 2774 | : inner_matcher_( |
| 2775 | testing::SafeMatcherCast<const Element&>(inner_matcher)) {} |
| 2776 | |
| 2777 | // Checks whether: |
| 2778 | // * All elements in the container match, if all_elements_should_match. |
| 2779 | // * Any element in the container matches, if !all_elements_should_match. |
| 2780 | bool MatchAndExplainImpl(bool all_elements_should_match, Container container, |
| 2781 | MatchResultListener* listener) const { |
| 2782 | StlContainerReference stl_container = View::ConstReference(container); |
| 2783 | size_t i = 0; |
| 2784 | for (auto it = stl_container.begin(); it != stl_container.end(); |
| 2785 | ++it, ++i) { |
| 2786 | StringMatchResultListener inner_listener; |
| 2787 | const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener); |
| 2788 | |
| 2789 | if (matches != all_elements_should_match) { |
| 2790 | *listener << "whose element #" << i |
| 2791 | << (matches ? " matches" : " doesn't match" ); |
| 2792 | PrintIfNotEmpty(explanation: inner_listener.str(), os: listener->stream()); |
| 2793 | return !all_elements_should_match; |
| 2794 | } |
| 2795 | } |
| 2796 | return all_elements_should_match; |
| 2797 | } |
| 2798 | |
| 2799 | bool MatchAndExplainImpl(const Matcher<size_t>& count_matcher, |
| 2800 | Container container, |
| 2801 | MatchResultListener* listener) const { |
| 2802 | StlContainerReference stl_container = View::ConstReference(container); |
| 2803 | size_t i = 0; |
| 2804 | std::vector<size_t> match_elements; |
| 2805 | for (auto it = stl_container.begin(); it != stl_container.end(); |
| 2806 | ++it, ++i) { |
| 2807 | StringMatchResultListener inner_listener; |
| 2808 | const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener); |
| 2809 | if (matches) { |
| 2810 | match_elements.push_back(x: i); |
| 2811 | } |
| 2812 | } |
| 2813 | if (listener->IsInterested()) { |
| 2814 | if (match_elements.empty()) { |
| 2815 | *listener << "has no element that matches" ; |
| 2816 | } else if (match_elements.size() == 1) { |
| 2817 | *listener << "whose element #" << match_elements[0] << " matches" ; |
| 2818 | } else { |
| 2819 | *listener << "whose elements (" ; |
| 2820 | std::string sep = "" ; |
| 2821 | for (size_t e : match_elements) { |
| 2822 | *listener << sep << e; |
| 2823 | sep = ", " ; |
| 2824 | } |
| 2825 | *listener << ") match" ; |
| 2826 | } |
| 2827 | } |
| 2828 | StringMatchResultListener count_listener; |
| 2829 | if (count_matcher.MatchAndExplain(x: match_elements.size(), listener: &count_listener)) { |
| 2830 | *listener << " and whose match quantity of " << match_elements.size() |
| 2831 | << " matches" ; |
| 2832 | PrintIfNotEmpty(explanation: count_listener.str(), os: listener->stream()); |
| 2833 | return true; |
| 2834 | } else { |
| 2835 | if (match_elements.empty()) { |
| 2836 | *listener << " and" ; |
| 2837 | } else { |
| 2838 | *listener << " but" ; |
| 2839 | } |
| 2840 | *listener << " whose match quantity of " << match_elements.size() |
| 2841 | << " does not match" ; |
| 2842 | PrintIfNotEmpty(explanation: count_listener.str(), os: listener->stream()); |
| 2843 | return false; |
| 2844 | } |
| 2845 | } |
| 2846 | |
| 2847 | protected: |
| 2848 | const Matcher<const Element&> inner_matcher_; |
| 2849 | }; |
| 2850 | |
| 2851 | // Implements Contains(element_matcher) for the given argument type Container. |
| 2852 | // Symmetric to EachMatcherImpl. |
| 2853 | template <typename Container> |
| 2854 | class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> { |
| 2855 | public: |
| 2856 | template <typename InnerMatcher> |
| 2857 | explicit ContainsMatcherImpl(InnerMatcher inner_matcher) |
| 2858 | : QuantifierMatcherImpl<Container>(inner_matcher) {} |
| 2859 | |
| 2860 | // Describes what this matcher does. |
| 2861 | void DescribeTo(::std::ostream* os) const override { |
| 2862 | *os << "contains at least one element that " ; |
| 2863 | this->inner_matcher_.DescribeTo(os); |
| 2864 | } |
| 2865 | |
| 2866 | void DescribeNegationTo(::std::ostream* os) const override { |
| 2867 | *os << "doesn't contain any element that " ; |
| 2868 | this->inner_matcher_.DescribeTo(os); |
| 2869 | } |
| 2870 | |
| 2871 | bool MatchAndExplain(Container container, |
| 2872 | MatchResultListener* listener) const override { |
| 2873 | return this->MatchAndExplainImpl(false, container, listener); |
| 2874 | } |
| 2875 | }; |
| 2876 | |
| 2877 | // Implements DistanceFrom(target, get_distance, distance_matcher) for the given |
| 2878 | // argument types: |
| 2879 | // * V is the type of the value to be matched. |
| 2880 | // * T is the type of the target value. |
| 2881 | // * Distance is the type of the distance between V and T. |
| 2882 | // * GetDistance is the type of the functor for computing the distance between |
| 2883 | // V and T. |
| 2884 | template <typename V, typename T, typename Distance, typename GetDistance> |
| 2885 | class DistanceFromMatcherImpl : public MatcherInterface<V> { |
| 2886 | public: |
| 2887 | // Arguments: |
| 2888 | // * target: the target value. |
| 2889 | // * get_distance: the functor for computing the distance between the value |
| 2890 | // being matched and target. |
| 2891 | // * distance_matcher: the matcher for checking the distance. |
| 2892 | DistanceFromMatcherImpl(T target, GetDistance get_distance, |
| 2893 | Matcher<const Distance&> distance_matcher) |
| 2894 | : target_(std::move(target)), |
| 2895 | get_distance_(std::move(get_distance)), |
| 2896 | distance_matcher_(std::move(distance_matcher)) {} |
| 2897 | |
| 2898 | // Describes what this matcher does. |
| 2899 | void DescribeTo(::std::ostream* os) const override { |
| 2900 | distance_matcher_.DescribeTo(os); |
| 2901 | *os << " away from " << PrintToString(target_); |
| 2902 | } |
| 2903 | |
| 2904 | void DescribeNegationTo(::std::ostream* os) const override { |
| 2905 | distance_matcher_.DescribeNegationTo(os); |
| 2906 | *os << " away from " << PrintToString(target_); |
| 2907 | } |
| 2908 | |
| 2909 | bool MatchAndExplain(V value, MatchResultListener* listener) const override { |
| 2910 | const auto distance = get_distance_(value, target_); |
| 2911 | const bool match = distance_matcher_.Matches(distance); |
| 2912 | if (!match && listener->IsInterested()) { |
| 2913 | *listener << "which is " << PrintToString(distance) << " away from " |
| 2914 | << PrintToString(target_); |
| 2915 | } |
| 2916 | return match; |
| 2917 | } |
| 2918 | |
| 2919 | private: |
| 2920 | const T target_; |
| 2921 | const GetDistance get_distance_; |
| 2922 | const Matcher<const Distance&> distance_matcher_; |
| 2923 | }; |
| 2924 | |
| 2925 | // Implements Each(element_matcher) for the given argument type Container. |
| 2926 | // Symmetric to ContainsMatcherImpl. |
| 2927 | template <typename Container> |
| 2928 | class EachMatcherImpl : public QuantifierMatcherImpl<Container> { |
| 2929 | public: |
| 2930 | template <typename InnerMatcher> |
| 2931 | explicit EachMatcherImpl(InnerMatcher inner_matcher) |
| 2932 | : QuantifierMatcherImpl<Container>(inner_matcher) {} |
| 2933 | |
| 2934 | // Describes what this matcher does. |
| 2935 | void DescribeTo(::std::ostream* os) const override { |
| 2936 | *os << "only contains elements that " ; |
| 2937 | this->inner_matcher_.DescribeTo(os); |
| 2938 | } |
| 2939 | |
| 2940 | void DescribeNegationTo(::std::ostream* os) const override { |
| 2941 | *os << "contains some element that " ; |
| 2942 | this->inner_matcher_.DescribeNegationTo(os); |
| 2943 | } |
| 2944 | |
| 2945 | bool MatchAndExplain(Container container, |
| 2946 | MatchResultListener* listener) const override { |
| 2947 | return this->MatchAndExplainImpl(true, container, listener); |
| 2948 | } |
| 2949 | }; |
| 2950 | |
| 2951 | // Implements Contains(element_matcher).Times(n) for the given argument type |
| 2952 | // Container. |
| 2953 | template <typename Container> |
| 2954 | class ContainsTimesMatcherImpl : public QuantifierMatcherImpl<Container> { |
| 2955 | public: |
| 2956 | template <typename InnerMatcher> |
| 2957 | explicit ContainsTimesMatcherImpl(InnerMatcher inner_matcher, |
| 2958 | Matcher<size_t> count_matcher) |
| 2959 | : QuantifierMatcherImpl<Container>(inner_matcher), |
| 2960 | count_matcher_(std::move(count_matcher)) {} |
| 2961 | |
| 2962 | void DescribeTo(::std::ostream* os) const override { |
| 2963 | *os << "quantity of elements that match " ; |
| 2964 | this->inner_matcher_.DescribeTo(os); |
| 2965 | *os << " " ; |
| 2966 | count_matcher_.DescribeTo(os); |
| 2967 | } |
| 2968 | |
| 2969 | void DescribeNegationTo(::std::ostream* os) const override { |
| 2970 | *os << "quantity of elements that match " ; |
| 2971 | this->inner_matcher_.DescribeTo(os); |
| 2972 | *os << " " ; |
| 2973 | count_matcher_.DescribeNegationTo(os); |
| 2974 | } |
| 2975 | |
| 2976 | bool MatchAndExplain(Container container, |
| 2977 | MatchResultListener* listener) const override { |
| 2978 | return this->MatchAndExplainImpl(count_matcher_, container, listener); |
| 2979 | } |
| 2980 | |
| 2981 | private: |
| 2982 | const Matcher<size_t> count_matcher_; |
| 2983 | }; |
| 2984 | |
| 2985 | // Implements polymorphic Contains(element_matcher).Times(n). |
| 2986 | template <typename M> |
| 2987 | class ContainsTimesMatcher { |
| 2988 | public: |
| 2989 | explicit ContainsTimesMatcher(M m, Matcher<size_t> count_matcher) |
| 2990 | : inner_matcher_(m), count_matcher_(std::move(count_matcher)) {} |
| 2991 | |
| 2992 | template <typename Container> |
| 2993 | operator Matcher<Container>() const { // NOLINT |
| 2994 | return Matcher<Container>(new ContainsTimesMatcherImpl<const Container&>( |
| 2995 | inner_matcher_, count_matcher_)); |
| 2996 | } |
| 2997 | |
| 2998 | private: |
| 2999 | const M inner_matcher_; |
| 3000 | const Matcher<size_t> count_matcher_; |
| 3001 | }; |
| 3002 | |
| 3003 | // Implements polymorphic Contains(element_matcher). |
| 3004 | template <typename M> |
| 3005 | class ContainsMatcher { |
| 3006 | public: |
| 3007 | explicit ContainsMatcher(M m) : inner_matcher_(m) {} |
| 3008 | |
| 3009 | template <typename Container> |
| 3010 | operator Matcher<Container>() const { // NOLINT |
| 3011 | return Matcher<Container>( |
| 3012 | new ContainsMatcherImpl<const Container&>(inner_matcher_)); |
| 3013 | } |
| 3014 | |
| 3015 | ContainsTimesMatcher<M> Times(Matcher<size_t> count_matcher) const { |
| 3016 | return ContainsTimesMatcher<M>(inner_matcher_, std::move(count_matcher)); |
| 3017 | } |
| 3018 | |
| 3019 | private: |
| 3020 | const M inner_matcher_; |
| 3021 | }; |
| 3022 | |
| 3023 | // Implements polymorphic Each(element_matcher). |
| 3024 | template <typename M> |
| 3025 | class EachMatcher { |
| 3026 | public: |
| 3027 | explicit EachMatcher(M m) : inner_matcher_(m) {} |
| 3028 | |
| 3029 | template <typename Container> |
| 3030 | operator Matcher<Container>() const { // NOLINT |
| 3031 | return Matcher<Container>( |
| 3032 | new EachMatcherImpl<const Container&>(inner_matcher_)); |
| 3033 | } |
| 3034 | |
| 3035 | private: |
| 3036 | const M inner_matcher_; |
| 3037 | }; |
| 3038 | |
| 3039 | namespace pair_getters { |
| 3040 | using std::get; |
| 3041 | template <typename T> |
| 3042 | auto First(T& x, Rank0) -> decltype(get<0>(x)) { // NOLINT |
| 3043 | return get<0>(x); |
| 3044 | } |
| 3045 | template <typename T> |
| 3046 | auto First(T& x, Rank1) -> decltype((x.first)) { // NOLINT |
| 3047 | return x.first; |
| 3048 | } |
| 3049 | |
| 3050 | template <typename T> |
| 3051 | auto Second(T& x, Rank0) -> decltype(get<1>(x)) { // NOLINT |
| 3052 | return get<1>(x); |
| 3053 | } |
| 3054 | template <typename T> |
| 3055 | auto Second(T& x, Rank1) -> decltype((x.second)) { // NOLINT |
| 3056 | return x.second; |
| 3057 | } |
| 3058 | } // namespace pair_getters |
| 3059 | |
| 3060 | // Default functor for computing the distance between two values. |
| 3061 | struct DefaultGetDistance { |
| 3062 | template <typename T, typename U> |
| 3063 | auto operator()(const T& lhs, const U& rhs) const { |
| 3064 | using std::abs; |
| 3065 | // Allow finding abs() in the type's namespace via ADL. |
| 3066 | return abs(lhs - rhs); |
| 3067 | } |
| 3068 | }; |
| 3069 | |
| 3070 | // Implements polymorphic DistanceFrom(target, get_distance, distance_matcher) |
| 3071 | // matcher. Template arguments: |
| 3072 | // * T is the type of the target value. |
| 3073 | // * GetDistance is the type of the functor for computing the distance between |
| 3074 | // the value being matched and the target. |
| 3075 | // * DistanceMatcher is the type of the matcher for checking the distance. |
| 3076 | template <typename T, typename GetDistance, typename DistanceMatcher> |
| 3077 | class DistanceFromMatcher { |
| 3078 | public: |
| 3079 | // Arguments: |
| 3080 | // * target: the target value. |
| 3081 | // * get_distance: the functor for computing the distance between the value |
| 3082 | // being matched and target. |
| 3083 | // * distance_matcher: the matcher for checking the distance. |
| 3084 | DistanceFromMatcher(T target, GetDistance get_distance, |
| 3085 | DistanceMatcher distance_matcher) |
| 3086 | : target_(std::move(target)), |
| 3087 | get_distance_(std::move(get_distance)), |
| 3088 | distance_matcher_(std::move(distance_matcher)) {} |
| 3089 | |
| 3090 | DistanceFromMatcher(const DistanceFromMatcher& other) = default; |
| 3091 | |
| 3092 | // Implicitly converts to a monomorphic matcher of the given type. |
| 3093 | template <typename V> |
| 3094 | operator Matcher<V>() const { // NOLINT |
| 3095 | using Distance = decltype(get_distance_(std::declval<V>(), target_)); |
| 3096 | return Matcher<V>(new DistanceFromMatcherImpl<V, T, Distance, GetDistance>( |
| 3097 | target_, get_distance_, distance_matcher_)); |
| 3098 | } |
| 3099 | |
| 3100 | private: |
| 3101 | const T target_; |
| 3102 | const GetDistance get_distance_; |
| 3103 | const DistanceMatcher distance_matcher_; |
| 3104 | }; |
| 3105 | |
| 3106 | // Implements Key(inner_matcher) for the given argument pair type. |
| 3107 | // Key(inner_matcher) matches an std::pair whose 'first' field matches |
| 3108 | // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an |
| 3109 | // std::map that contains at least one element whose key is >= 5. |
| 3110 | template <typename PairType> |
| 3111 | class KeyMatcherImpl : public MatcherInterface<PairType> { |
| 3112 | public: |
| 3113 | typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; |
| 3114 | typedef typename RawPairType::first_type KeyType; |
| 3115 | |
| 3116 | template <typename InnerMatcher> |
| 3117 | explicit KeyMatcherImpl(InnerMatcher inner_matcher) |
| 3118 | : inner_matcher_( |
| 3119 | testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {} |
| 3120 | |
| 3121 | // Returns true if and only if 'key_value.first' (the key) matches the inner |
| 3122 | // matcher. |
| 3123 | bool MatchAndExplain(PairType key_value, |
| 3124 | MatchResultListener* listener) const override { |
| 3125 | StringMatchResultListener inner_listener; |
| 3126 | const bool match = inner_matcher_.MatchAndExplain( |
| 3127 | pair_getters::First(key_value, Rank1()), &inner_listener); |
| 3128 | const std::string explanation = inner_listener.str(); |
| 3129 | if (!explanation.empty()) { |
| 3130 | *listener << "whose first field is a value " << explanation; |
| 3131 | } |
| 3132 | return match; |
| 3133 | } |
| 3134 | |
| 3135 | // Describes what this matcher does. |
| 3136 | void DescribeTo(::std::ostream* os) const override { |
| 3137 | *os << "has a key that " ; |
| 3138 | inner_matcher_.DescribeTo(os); |
| 3139 | } |
| 3140 | |
| 3141 | // Describes what the negation of this matcher does. |
| 3142 | void DescribeNegationTo(::std::ostream* os) const override { |
| 3143 | *os << "doesn't have a key that " ; |
| 3144 | inner_matcher_.DescribeTo(os); |
| 3145 | } |
| 3146 | |
| 3147 | private: |
| 3148 | const Matcher<const KeyType&> inner_matcher_; |
| 3149 | }; |
| 3150 | |
| 3151 | // Implements polymorphic Key(matcher_for_key). |
| 3152 | template <typename M> |
| 3153 | class KeyMatcher { |
| 3154 | public: |
| 3155 | explicit KeyMatcher(M m) : matcher_for_key_(m) {} |
| 3156 | |
| 3157 | template <typename PairType> |
| 3158 | operator Matcher<PairType>() const { |
| 3159 | return Matcher<PairType>( |
| 3160 | new KeyMatcherImpl<const PairType&>(matcher_for_key_)); |
| 3161 | } |
| 3162 | |
| 3163 | private: |
| 3164 | const M matcher_for_key_; |
| 3165 | }; |
| 3166 | |
| 3167 | // Implements polymorphic Address(matcher_for_address). |
| 3168 | template <typename InnerMatcher> |
| 3169 | class AddressMatcher { |
| 3170 | public: |
| 3171 | explicit AddressMatcher(InnerMatcher m) : matcher_(m) {} |
| 3172 | |
| 3173 | template <typename Type> |
| 3174 | operator Matcher<Type>() const { // NOLINT |
| 3175 | return Matcher<Type>(new Impl<const Type&>(matcher_)); |
| 3176 | } |
| 3177 | |
| 3178 | private: |
| 3179 | // The monomorphic implementation that works for a particular object type. |
| 3180 | template <typename Type> |
| 3181 | class Impl : public MatcherInterface<Type> { |
| 3182 | public: |
| 3183 | using Address = const GTEST_REMOVE_REFERENCE_AND_CONST_(Type) *; |
| 3184 | explicit Impl(const InnerMatcher& matcher) |
| 3185 | : matcher_(MatcherCast<Address>(matcher)) {} |
| 3186 | |
| 3187 | void DescribeTo(::std::ostream* os) const override { |
| 3188 | *os << "has address that " ; |
| 3189 | matcher_.DescribeTo(os); |
| 3190 | } |
| 3191 | |
| 3192 | void DescribeNegationTo(::std::ostream* os) const override { |
| 3193 | *os << "does not have address that " ; |
| 3194 | matcher_.DescribeTo(os); |
| 3195 | } |
| 3196 | |
| 3197 | bool MatchAndExplain(Type object, |
| 3198 | MatchResultListener* listener) const override { |
| 3199 | *listener << "which has address " ; |
| 3200 | Address address = std::addressof(object); |
| 3201 | return MatchPrintAndExplain(address, matcher_, listener); |
| 3202 | } |
| 3203 | |
| 3204 | private: |
| 3205 | const Matcher<Address> matcher_; |
| 3206 | }; |
| 3207 | const InnerMatcher matcher_; |
| 3208 | }; |
| 3209 | |
| 3210 | // Implements Pair(first_matcher, second_matcher) for the given argument pair |
| 3211 | // type with its two matchers. See Pair() function below. |
| 3212 | template <typename PairType> |
| 3213 | class PairMatcherImpl : public MatcherInterface<PairType> { |
| 3214 | public: |
| 3215 | typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; |
| 3216 | typedef typename RawPairType::first_type FirstType; |
| 3217 | typedef typename RawPairType::second_type SecondType; |
| 3218 | |
| 3219 | template <typename FirstMatcher, typename SecondMatcher> |
| 3220 | PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher) |
| 3221 | : first_matcher_( |
| 3222 | testing::SafeMatcherCast<const FirstType&>(first_matcher)), |
| 3223 | second_matcher_( |
| 3224 | testing::SafeMatcherCast<const SecondType&>(second_matcher)) {} |
| 3225 | |
| 3226 | // Describes what this matcher does. |
| 3227 | void DescribeTo(::std::ostream* os) const override { |
| 3228 | *os << "has a first field that " ; |
| 3229 | first_matcher_.DescribeTo(os); |
| 3230 | *os << ", and has a second field that " ; |
| 3231 | second_matcher_.DescribeTo(os); |
| 3232 | } |
| 3233 | |
| 3234 | // Describes what the negation of this matcher does. |
| 3235 | void DescribeNegationTo(::std::ostream* os) const override { |
| 3236 | *os << "has a first field that " ; |
| 3237 | first_matcher_.DescribeNegationTo(os); |
| 3238 | *os << ", or has a second field that " ; |
| 3239 | second_matcher_.DescribeNegationTo(os); |
| 3240 | } |
| 3241 | |
| 3242 | // Returns true if and only if 'a_pair.first' matches first_matcher and |
| 3243 | // 'a_pair.second' matches second_matcher. |
| 3244 | bool MatchAndExplain(PairType a_pair, |
| 3245 | MatchResultListener* listener) const override { |
| 3246 | if (!listener->IsInterested()) { |
| 3247 | // If the listener is not interested, we don't need to construct the |
| 3248 | // explanation. |
| 3249 | return first_matcher_.Matches(pair_getters::First(a_pair, Rank1())) && |
| 3250 | second_matcher_.Matches(pair_getters::Second(a_pair, Rank1())); |
| 3251 | } |
| 3252 | StringMatchResultListener first_inner_listener; |
| 3253 | if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank1()), |
| 3254 | &first_inner_listener)) { |
| 3255 | *listener << "whose first field does not match" ; |
| 3256 | PrintIfNotEmpty(explanation: first_inner_listener.str(), os: listener->stream()); |
| 3257 | return false; |
| 3258 | } |
| 3259 | StringMatchResultListener second_inner_listener; |
| 3260 | if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank1()), |
| 3261 | &second_inner_listener)) { |
| 3262 | *listener << "whose second field does not match" ; |
| 3263 | PrintIfNotEmpty(explanation: second_inner_listener.str(), os: listener->stream()); |
| 3264 | return false; |
| 3265 | } |
| 3266 | ExplainSuccess(first_explanation: first_inner_listener.str(), second_explanation: second_inner_listener.str(), |
| 3267 | listener); |
| 3268 | return true; |
| 3269 | } |
| 3270 | |
| 3271 | private: |
| 3272 | void ExplainSuccess(const std::string& first_explanation, |
| 3273 | const std::string& second_explanation, |
| 3274 | MatchResultListener* listener) const { |
| 3275 | *listener << "whose both fields match" ; |
| 3276 | if (!first_explanation.empty()) { |
| 3277 | *listener << ", where the first field is a value " << first_explanation; |
| 3278 | } |
| 3279 | if (!second_explanation.empty()) { |
| 3280 | *listener << ", " ; |
| 3281 | if (!first_explanation.empty()) { |
| 3282 | *listener << "and " ; |
| 3283 | } else { |
| 3284 | *listener << "where " ; |
| 3285 | } |
| 3286 | *listener << "the second field is a value " << second_explanation; |
| 3287 | } |
| 3288 | } |
| 3289 | |
| 3290 | const Matcher<const FirstType&> first_matcher_; |
| 3291 | const Matcher<const SecondType&> second_matcher_; |
| 3292 | }; |
| 3293 | |
| 3294 | // Implements polymorphic Pair(first_matcher, second_matcher). |
| 3295 | template <typename FirstMatcher, typename SecondMatcher> |
| 3296 | class PairMatcher { |
| 3297 | public: |
| 3298 | PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher) |
| 3299 | : first_matcher_(first_matcher), second_matcher_(second_matcher) {} |
| 3300 | |
| 3301 | template <typename PairType> |
| 3302 | operator Matcher<PairType>() const { |
| 3303 | return Matcher<PairType>( |
| 3304 | new PairMatcherImpl<const PairType&>(first_matcher_, second_matcher_)); |
| 3305 | } |
| 3306 | |
| 3307 | private: |
| 3308 | const FirstMatcher first_matcher_; |
| 3309 | const SecondMatcher second_matcher_; |
| 3310 | }; |
| 3311 | |
| 3312 | template <typename T, size_t... I> |
| 3313 | auto UnpackStructImpl(const T& t, std::index_sequence<I...>, int) |
| 3314 | -> decltype(std::tie(get<I>(t)...)) { |
| 3315 | static_assert(std::tuple_size<T>::value == sizeof...(I), |
| 3316 | "Number of arguments doesn't match the number of fields." ); |
| 3317 | return std::tie(get<I>(t)...); |
| 3318 | } |
| 3319 | |
| 3320 | #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606 |
| 3321 | template <typename T> |
| 3322 | auto UnpackStructImpl(const T& t, std::make_index_sequence<1>, char) { |
| 3323 | const auto& [a] = t; |
| 3324 | return std::tie(a); |
| 3325 | } |
| 3326 | template <typename T> |
| 3327 | auto UnpackStructImpl(const T& t, std::make_index_sequence<2>, char) { |
| 3328 | const auto& [a, b] = t; |
| 3329 | return std::tie(a, b); |
| 3330 | } |
| 3331 | template <typename T> |
| 3332 | auto UnpackStructImpl(const T& t, std::make_index_sequence<3>, char) { |
| 3333 | const auto& [a, b, c] = t; |
| 3334 | return std::tie(a, b, c); |
| 3335 | } |
| 3336 | template <typename T> |
| 3337 | auto UnpackStructImpl(const T& t, std::make_index_sequence<4>, char) { |
| 3338 | const auto& [a, b, c, d] = t; |
| 3339 | return std::tie(a, b, c, d); |
| 3340 | } |
| 3341 | template <typename T> |
| 3342 | auto UnpackStructImpl(const T& t, std::make_index_sequence<5>, char) { |
| 3343 | const auto& [a, b, c, d, e] = t; |
| 3344 | return std::tie(a, b, c, d, e); |
| 3345 | } |
| 3346 | template <typename T> |
| 3347 | auto UnpackStructImpl(const T& t, std::make_index_sequence<6>, char) { |
| 3348 | const auto& [a, b, c, d, e, f] = t; |
| 3349 | return std::tie(a, b, c, d, e, f); |
| 3350 | } |
| 3351 | template <typename T> |
| 3352 | auto UnpackStructImpl(const T& t, std::make_index_sequence<7>, char) { |
| 3353 | const auto& [a, b, c, d, e, f, g] = t; |
| 3354 | return std::tie(a, b, c, d, e, f, g); |
| 3355 | } |
| 3356 | template <typename T> |
| 3357 | auto UnpackStructImpl(const T& t, std::make_index_sequence<8>, char) { |
| 3358 | const auto& [a, b, c, d, e, f, g, h] = t; |
| 3359 | return std::tie(a, b, c, d, e, f, g, h); |
| 3360 | } |
| 3361 | template <typename T> |
| 3362 | auto UnpackStructImpl(const T& t, std::make_index_sequence<9>, char) { |
| 3363 | const auto& [a, b, c, d, e, f, g, h, i] = t; |
| 3364 | return std::tie(a, b, c, d, e, f, g, h, i); |
| 3365 | } |
| 3366 | template <typename T> |
| 3367 | auto UnpackStructImpl(const T& t, std::make_index_sequence<10>, char) { |
| 3368 | const auto& [a, b, c, d, e, f, g, h, i, j] = t; |
| 3369 | return std::tie(a, b, c, d, e, f, g, h, i, j); |
| 3370 | } |
| 3371 | template <typename T> |
| 3372 | auto UnpackStructImpl(const T& t, std::make_index_sequence<11>, char) { |
| 3373 | const auto& [a, b, c, d, e, f, g, h, i, j, k] = t; |
| 3374 | return std::tie(a, b, c, d, e, f, g, h, i, j, k); |
| 3375 | } |
| 3376 | template <typename T> |
| 3377 | auto UnpackStructImpl(const T& t, std::make_index_sequence<12>, char) { |
| 3378 | const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t; |
| 3379 | return std::tie(a, b, c, d, e, f, g, h, i, j, k, l); |
| 3380 | } |
| 3381 | template <typename T> |
| 3382 | auto UnpackStructImpl(const T& t, std::make_index_sequence<13>, char) { |
| 3383 | const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t; |
| 3384 | return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m); |
| 3385 | } |
| 3386 | template <typename T> |
| 3387 | auto UnpackStructImpl(const T& t, std::make_index_sequence<14>, char) { |
| 3388 | const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t; |
| 3389 | return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n); |
| 3390 | } |
| 3391 | template <typename T> |
| 3392 | auto UnpackStructImpl(const T& t, std::make_index_sequence<15>, char) { |
| 3393 | const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t; |
| 3394 | return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o); |
| 3395 | } |
| 3396 | template <typename T> |
| 3397 | auto UnpackStructImpl(const T& t, std::make_index_sequence<16>, char) { |
| 3398 | const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t; |
| 3399 | return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p); |
| 3400 | } |
| 3401 | template <typename T> |
| 3402 | auto UnpackStructImpl(const T& t, std::make_index_sequence<17>, char) { |
| 3403 | const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q] = t; |
| 3404 | return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q); |
| 3405 | } |
| 3406 | template <typename T> |
| 3407 | auto UnpackStructImpl(const T& t, std::make_index_sequence<18>, char) { |
| 3408 | const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r] = t; |
| 3409 | return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r); |
| 3410 | } |
| 3411 | template <typename T> |
| 3412 | auto UnpackStructImpl(const T& t, std::make_index_sequence<19>, char) { |
| 3413 | const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s] = t; |
| 3414 | return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s); |
| 3415 | } |
| 3416 | template <typename T> |
| 3417 | auto UnpackStructImpl(const T& u, std::make_index_sequence<20>, char) { |
| 3418 | const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t] = u; |
| 3419 | return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t); |
| 3420 | } |
| 3421 | template <typename T> |
| 3422 | auto UnpackStructImpl(const T& in, std::make_index_sequence<21>, char) { |
| 3423 | const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u] = |
| 3424 | in; |
| 3425 | return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, |
| 3426 | u); |
| 3427 | } |
| 3428 | |
| 3429 | template <typename T> |
| 3430 | auto UnpackStructImpl(const T& in, std::make_index_sequence<22>, char) { |
| 3431 | const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, |
| 3432 | v] = in; |
| 3433 | return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, |
| 3434 | v); |
| 3435 | } |
| 3436 | #endif // defined(__cpp_structured_bindings) |
| 3437 | |
| 3438 | template <size_t I, typename T> |
| 3439 | auto UnpackStruct(const T& t) |
| 3440 | -> decltype((UnpackStructImpl)(t, std::make_index_sequence<I>{}, 0)) { |
| 3441 | return (UnpackStructImpl)(t, std::make_index_sequence<I>{}, 0); |
| 3442 | } |
| 3443 | |
| 3444 | // Helper function to do comma folding in C++11. |
| 3445 | // The array ensures left-to-right order of evaluation. |
| 3446 | // Usage: VariadicExpand({expr...}); |
| 3447 | template <typename T, size_t N> |
| 3448 | void VariadicExpand(const T (&)[N]) {} |
| 3449 | |
| 3450 | template <typename Struct, typename StructSize> |
| 3451 | class FieldsAreMatcherImpl; |
| 3452 | |
| 3453 | template <typename Struct, size_t... I> |
| 3454 | class FieldsAreMatcherImpl<Struct, std::index_sequence<I...>> |
| 3455 | : public MatcherInterface<Struct> { |
| 3456 | using UnpackedType = |
| 3457 | decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>())); |
| 3458 | using MatchersType = std::tuple< |
| 3459 | Matcher<const typename std::tuple_element<I, UnpackedType>::type&>...>; |
| 3460 | |
| 3461 | public: |
| 3462 | template <typename Inner> |
| 3463 | explicit FieldsAreMatcherImpl(const Inner& matchers) |
| 3464 | : matchers_(testing::SafeMatcherCast< |
| 3465 | const typename std::tuple_element<I, UnpackedType>::type&>( |
| 3466 | std::get<I>(matchers))...) {} |
| 3467 | |
| 3468 | void DescribeTo(::std::ostream* os) const override { |
| 3469 | const char* separator = "" ; |
| 3470 | VariadicExpand( |
| 3471 | {(*os << separator << "has field #" << I << " that " , |
| 3472 | std::get<I>(matchers_).DescribeTo(os), separator = ", and " )...}); |
| 3473 | } |
| 3474 | |
| 3475 | void DescribeNegationTo(::std::ostream* os) const override { |
| 3476 | const char* separator = "" ; |
| 3477 | VariadicExpand({(*os << separator << "has field #" << I << " that " , |
| 3478 | std::get<I>(matchers_).DescribeNegationTo(os), |
| 3479 | separator = ", or " )...}); |
| 3480 | } |
| 3481 | |
| 3482 | bool MatchAndExplain(Struct t, MatchResultListener* listener) const override { |
| 3483 | return MatchInternal(tuple: (UnpackStruct<sizeof...(I)>)(t), listener); |
| 3484 | } |
| 3485 | |
| 3486 | private: |
| 3487 | bool MatchInternal(UnpackedType tuple, MatchResultListener* listener) const { |
| 3488 | if (!listener->IsInterested()) { |
| 3489 | // If the listener is not interested, we don't need to construct the |
| 3490 | // explanation. |
| 3491 | bool good = true; |
| 3492 | VariadicExpand({good = good && std::get<I>(matchers_).Matches( |
| 3493 | std::get<I>(tuple))...}); |
| 3494 | return good; |
| 3495 | } |
| 3496 | |
| 3497 | size_t failed_pos = ~size_t{}; |
| 3498 | |
| 3499 | std::vector<StringMatchResultListener> inner_listener(sizeof...(I)); |
| 3500 | |
| 3501 | VariadicExpand( |
| 3502 | {failed_pos == ~size_t{} && !std::get<I>(matchers_).MatchAndExplain( |
| 3503 | std::get<I>(tuple), &inner_listener[I]) |
| 3504 | ? failed_pos = I |
| 3505 | : 0 ...}); |
| 3506 | if (failed_pos != ~size_t{}) { |
| 3507 | *listener << "whose field #" << failed_pos << " does not match" ; |
| 3508 | PrintIfNotEmpty(explanation: inner_listener[failed_pos].str(), os: listener->stream()); |
| 3509 | return false; |
| 3510 | } |
| 3511 | |
| 3512 | *listener << "whose all elements match" ; |
| 3513 | const char* separator = ", where" ; |
| 3514 | for (size_t index = 0; index < sizeof...(I); ++index) { |
| 3515 | const std::string str = inner_listener[index].str(); |
| 3516 | if (!str.empty()) { |
| 3517 | *listener << separator << " field #" << index << " is a value " << str; |
| 3518 | separator = ", and" ; |
| 3519 | } |
| 3520 | } |
| 3521 | |
| 3522 | return true; |
| 3523 | } |
| 3524 | |
| 3525 | MatchersType matchers_; |
| 3526 | }; |
| 3527 | |
| 3528 | template <typename... Inner> |
| 3529 | class FieldsAreMatcher { |
| 3530 | public: |
| 3531 | explicit FieldsAreMatcher(Inner... inner) : matchers_(std::move(inner)...) {} |
| 3532 | |
| 3533 | template <typename Struct> |
| 3534 | operator Matcher<Struct>() const { // NOLINT |
| 3535 | return Matcher<Struct>( |
| 3536 | new FieldsAreMatcherImpl<const Struct&, |
| 3537 | std::index_sequence_for<Inner...>>(matchers_)); |
| 3538 | } |
| 3539 | |
| 3540 | private: |
| 3541 | std::tuple<Inner...> matchers_; |
| 3542 | }; |
| 3543 | |
| 3544 | // Implements ElementsAre() and ElementsAreArray(). |
| 3545 | template <typename Container> |
| 3546 | class ElementsAreMatcherImpl : public MatcherInterface<Container> { |
| 3547 | public: |
| 3548 | typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; |
| 3549 | typedef internal::StlContainerView<RawContainer> View; |
| 3550 | typedef typename View::type StlContainer; |
| 3551 | typedef typename View::const_reference StlContainerReference; |
| 3552 | typedef typename StlContainer::value_type Element; |
| 3553 | |
| 3554 | // Constructs the matcher from a sequence of element values or |
| 3555 | // element matchers. |
| 3556 | template <typename InputIter> |
| 3557 | ElementsAreMatcherImpl(InputIter first, InputIter last) { |
| 3558 | while (first != last) { |
| 3559 | matchers_.push_back(MatcherCast<const Element&>(*first++)); |
| 3560 | } |
| 3561 | } |
| 3562 | |
| 3563 | // Describes what this matcher does. |
| 3564 | void DescribeTo(::std::ostream* os) const override { |
| 3565 | if (count() == 0) { |
| 3566 | *os << "is empty" ; |
| 3567 | } else if (count() == 1) { |
| 3568 | *os << "has 1 element that " ; |
| 3569 | matchers_[0].DescribeTo(os); |
| 3570 | } else { |
| 3571 | *os << "has " << Elements(count: count()) << " where\n" ; |
| 3572 | for (size_t i = 0; i != count(); ++i) { |
| 3573 | *os << "element #" << i << " " ; |
| 3574 | matchers_[i].DescribeTo(os); |
| 3575 | if (i + 1 < count()) { |
| 3576 | *os << ",\n" ; |
| 3577 | } |
| 3578 | } |
| 3579 | } |
| 3580 | } |
| 3581 | |
| 3582 | // Describes what the negation of this matcher does. |
| 3583 | void DescribeNegationTo(::std::ostream* os) const override { |
| 3584 | if (count() == 0) { |
| 3585 | *os << "isn't empty" ; |
| 3586 | return; |
| 3587 | } |
| 3588 | |
| 3589 | *os << "doesn't have " << Elements(count: count()) << ", or\n" ; |
| 3590 | for (size_t i = 0; i != count(); ++i) { |
| 3591 | *os << "element #" << i << " " ; |
| 3592 | matchers_[i].DescribeNegationTo(os); |
| 3593 | if (i + 1 < count()) { |
| 3594 | *os << ", or\n" ; |
| 3595 | } |
| 3596 | } |
| 3597 | } |
| 3598 | |
| 3599 | bool MatchAndExplain(Container container, |
| 3600 | MatchResultListener* listener) const override { |
| 3601 | // To work with stream-like "containers", we must only walk |
| 3602 | // through the elements in one pass. |
| 3603 | |
| 3604 | const bool listener_interested = listener->IsInterested(); |
| 3605 | |
| 3606 | // explanations[i] is the explanation of the element at index i. |
| 3607 | ::std::vector<std::string> explanations(count()); |
| 3608 | StlContainerReference stl_container = View::ConstReference(container); |
| 3609 | auto it = stl_container.begin(); |
| 3610 | size_t exam_pos = 0; |
| 3611 | bool unmatched_found = false; |
| 3612 | |
| 3613 | // Go through the elements and matchers in pairs, until we reach |
| 3614 | // the end of either the elements or the matchers, or until we find a |
| 3615 | // mismatch. |
| 3616 | for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) { |
| 3617 | bool match; // Does the current element match the current matcher? |
| 3618 | if (listener_interested) { |
| 3619 | StringMatchResultListener s; |
| 3620 | match = matchers_[exam_pos].MatchAndExplain(*it, &s); |
| 3621 | explanations[exam_pos] = s.str(); |
| 3622 | } else { |
| 3623 | match = matchers_[exam_pos].Matches(*it); |
| 3624 | } |
| 3625 | |
| 3626 | if (!match) { |
| 3627 | unmatched_found = true; |
| 3628 | // We cannot store the iterator for the unmatched element to be used |
| 3629 | // later, as some users use ElementsAre() with a "container" whose |
| 3630 | // iterator is not copy-constructible or copy-assignable. |
| 3631 | // |
| 3632 | // We cannot store a pointer to the element either, as some container's |
| 3633 | // iterators return a temporary. |
| 3634 | // |
| 3635 | // We cannot store the element itself either, as the element may not be |
| 3636 | // copyable. |
| 3637 | // |
| 3638 | // Therefore, we just remember the index of the unmatched element, |
| 3639 | // and use it later to print the unmatched element. |
| 3640 | break; |
| 3641 | } |
| 3642 | } |
| 3643 | // If unmatched_found is true, exam_pos is the index of the mismatch. |
| 3644 | |
| 3645 | // Find how many elements the actual container has. We avoid |
| 3646 | // calling size() s.t. this code works for stream-like "containers" |
| 3647 | // that don't define size(). |
| 3648 | size_t actual_count = exam_pos; |
| 3649 | for (; it != stl_container.end(); ++it) { |
| 3650 | ++actual_count; |
| 3651 | } |
| 3652 | |
| 3653 | if (actual_count != count()) { |
| 3654 | // The element count doesn't match. If the container is empty, |
| 3655 | // there's no need to explain anything as Google Mock already |
| 3656 | // prints the empty container. Otherwise we just need to show |
| 3657 | // how many elements there actually are. |
| 3658 | if (listener_interested && (actual_count != 0)) { |
| 3659 | *listener << "which has " << Elements(count: actual_count); |
| 3660 | } |
| 3661 | return false; |
| 3662 | } |
| 3663 | |
| 3664 | if (unmatched_found) { |
| 3665 | // The element count matches, but the exam_pos-th element doesn't match. |
| 3666 | if (listener_interested) { |
| 3667 | // Find the unmatched element. |
| 3668 | auto unmatched_it = stl_container.begin(); |
| 3669 | // We cannot call std::advance() on the iterator, as some users use |
| 3670 | // ElementsAre() with a "container" whose iterator is incompatible with |
| 3671 | // std::advance() (e.g. it may not have the difference_type member |
| 3672 | // type). |
| 3673 | for (size_t i = 0; i != exam_pos; ++i) { |
| 3674 | ++unmatched_it; |
| 3675 | } |
| 3676 | |
| 3677 | // If the array is long or the elements' print-out is large, it may be |
| 3678 | // hard for the user to find the mismatched element and its |
| 3679 | // corresponding matcher description. Therefore we print the index, the |
| 3680 | // value of the mismatched element, and the corresponding matcher |
| 3681 | // description to ease debugging. |
| 3682 | *listener << "whose element #" << exam_pos << " (" |
| 3683 | << PrintToString(*unmatched_it) << ") " ; |
| 3684 | matchers_[exam_pos].DescribeNegationTo(listener->stream()); |
| 3685 | PrintIfNotEmpty(explanation: explanations[exam_pos], os: listener->stream()); |
| 3686 | } |
| 3687 | return false; |
| 3688 | } |
| 3689 | |
| 3690 | // Every element matches its expectation. We need to explain why |
| 3691 | // (the obvious ones can be skipped). |
| 3692 | if (listener_interested) { |
| 3693 | bool reason_printed = false; |
| 3694 | for (size_t i = 0; i != count(); ++i) { |
| 3695 | const std::string& s = explanations[i]; |
| 3696 | if (!s.empty()) { |
| 3697 | if (reason_printed) { |
| 3698 | *listener << ",\nand " ; |
| 3699 | } |
| 3700 | *listener << "whose element #" << i << " matches, " << s; |
| 3701 | reason_printed = true; |
| 3702 | } |
| 3703 | } |
| 3704 | } |
| 3705 | return true; |
| 3706 | } |
| 3707 | |
| 3708 | private: |
| 3709 | static Message Elements(size_t count) { |
| 3710 | return Message() << count << (count == 1 ? " element" : " elements" ); |
| 3711 | } |
| 3712 | |
| 3713 | size_t count() const { return matchers_.size(); } |
| 3714 | |
| 3715 | ::std::vector<Matcher<const Element&>> matchers_; |
| 3716 | }; |
| 3717 | |
| 3718 | // Connectivity matrix of (elements X matchers), in element-major order. |
| 3719 | // Initially, there are no edges. |
| 3720 | // Use NextGraph() to iterate over all possible edge configurations. |
| 3721 | // Use Randomize() to generate a random edge configuration. |
| 3722 | class GTEST_API_ MatchMatrix { |
| 3723 | public: |
| 3724 | MatchMatrix(size_t num_elements, size_t num_matchers) |
| 3725 | : num_elements_(num_elements), |
| 3726 | num_matchers_(num_matchers), |
| 3727 | matched_(num_elements_ * num_matchers_, 0) {} |
| 3728 | |
| 3729 | size_t LhsSize() const { return num_elements_; } |
| 3730 | size_t RhsSize() const { return num_matchers_; } |
| 3731 | bool HasEdge(size_t ilhs, size_t irhs) const { |
| 3732 | return matched_[SpaceIndex(ilhs, irhs)] == 1; |
| 3733 | } |
| 3734 | void SetEdge(size_t ilhs, size_t irhs, bool b) { |
| 3735 | matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0; |
| 3736 | } |
| 3737 | |
| 3738 | // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number, |
| 3739 | // adds 1 to that number; returns false if incrementing the graph left it |
| 3740 | // empty. |
| 3741 | bool NextGraph(); |
| 3742 | |
| 3743 | void Randomize(); |
| 3744 | |
| 3745 | std::string DebugString() const; |
| 3746 | |
| 3747 | private: |
| 3748 | size_t SpaceIndex(size_t ilhs, size_t irhs) const { |
| 3749 | return ilhs * num_matchers_ + irhs; |
| 3750 | } |
| 3751 | |
| 3752 | size_t num_elements_; |
| 3753 | size_t num_matchers_; |
| 3754 | |
| 3755 | // Each element is a char interpreted as bool. They are stored as a |
| 3756 | // flattened array in lhs-major order, use 'SpaceIndex()' to translate |
| 3757 | // a (ilhs, irhs) matrix coordinate into an offset. |
| 3758 | ::std::vector<char> matched_; |
| 3759 | }; |
| 3760 | |
| 3761 | typedef ::std::pair<size_t, size_t> ElementMatcherPair; |
| 3762 | typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs; |
| 3763 | |
| 3764 | // Returns a maximum bipartite matching for the specified graph 'g'. |
| 3765 | // The matching is represented as a vector of {element, matcher} pairs. |
| 3766 | GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g); |
| 3767 | |
| 3768 | struct UnorderedMatcherRequire { |
| 3769 | enum Flags { |
| 3770 | Superset = 1 << 0, |
| 3771 | Subset = 1 << 1, |
| 3772 | ExactMatch = Superset | Subset, |
| 3773 | }; |
| 3774 | }; |
| 3775 | |
| 3776 | // Untyped base class for implementing UnorderedElementsAre. By |
| 3777 | // putting logic that's not specific to the element type here, we |
| 3778 | // reduce binary bloat and increase compilation speed. |
| 3779 | class GTEST_API_ UnorderedElementsAreMatcherImplBase { |
| 3780 | protected: |
| 3781 | explicit UnorderedElementsAreMatcherImplBase( |
| 3782 | UnorderedMatcherRequire::Flags matcher_flags) |
| 3783 | : match_flags_(matcher_flags) {} |
| 3784 | |
| 3785 | // A vector of matcher describers, one for each element matcher. |
| 3786 | // Does not own the describers (and thus can be used only when the |
| 3787 | // element matchers are alive). |
| 3788 | typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec; |
| 3789 | |
| 3790 | // Describes this UnorderedElementsAre matcher. |
| 3791 | void DescribeToImpl(::std::ostream* os) const; |
| 3792 | |
| 3793 | // Describes the negation of this UnorderedElementsAre matcher. |
| 3794 | void DescribeNegationToImpl(::std::ostream* os) const; |
| 3795 | |
| 3796 | bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts, |
| 3797 | const MatchMatrix& matrix, |
| 3798 | MatchResultListener* listener) const; |
| 3799 | |
| 3800 | bool FindPairing(const MatchMatrix& matrix, |
| 3801 | MatchResultListener* listener) const; |
| 3802 | |
| 3803 | MatcherDescriberVec& matcher_describers() { return matcher_describers_; } |
| 3804 | |
| 3805 | static Message Elements(size_t n) { |
| 3806 | return Message() << n << " element" << (n == 1 ? "" : "s" ); |
| 3807 | } |
| 3808 | |
| 3809 | UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; } |
| 3810 | |
| 3811 | private: |
| 3812 | UnorderedMatcherRequire::Flags match_flags_; |
| 3813 | MatcherDescriberVec matcher_describers_; |
| 3814 | }; |
| 3815 | |
| 3816 | // Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and |
| 3817 | // IsSupersetOf. |
| 3818 | template <typename Container> |
| 3819 | class UnorderedElementsAreMatcherImpl |
| 3820 | : public MatcherInterface<Container>, |
| 3821 | public UnorderedElementsAreMatcherImplBase { |
| 3822 | public: |
| 3823 | typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; |
| 3824 | typedef internal::StlContainerView<RawContainer> View; |
| 3825 | typedef typename View::type StlContainer; |
| 3826 | typedef typename View::const_reference StlContainerReference; |
| 3827 | typedef typename StlContainer::value_type Element; |
| 3828 | |
| 3829 | template <typename InputIter> |
| 3830 | UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags, |
| 3831 | InputIter first, InputIter last) |
| 3832 | : UnorderedElementsAreMatcherImplBase(matcher_flags) { |
| 3833 | for (; first != last; ++first) { |
| 3834 | matchers_.push_back(MatcherCast<const Element&>(*first)); |
| 3835 | } |
| 3836 | for (const auto& m : matchers_) { |
| 3837 | matcher_describers().push_back(m.GetDescriber()); |
| 3838 | } |
| 3839 | } |
| 3840 | |
| 3841 | // Describes what this matcher does. |
| 3842 | void DescribeTo(::std::ostream* os) const override { |
| 3843 | return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os); |
| 3844 | } |
| 3845 | |
| 3846 | // Describes what the negation of this matcher does. |
| 3847 | void DescribeNegationTo(::std::ostream* os) const override { |
| 3848 | return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os); |
| 3849 | } |
| 3850 | |
| 3851 | bool MatchAndExplain(Container container, |
| 3852 | MatchResultListener* listener) const override { |
| 3853 | StlContainerReference stl_container = View::ConstReference(container); |
| 3854 | ::std::vector<std::string> element_printouts; |
| 3855 | MatchMatrix matrix = |
| 3856 | AnalyzeElements(stl_container.begin(), stl_container.end(), |
| 3857 | &element_printouts, listener); |
| 3858 | |
| 3859 | return VerifyMatchMatrix(element_printouts, matrix, listener) && |
| 3860 | FindPairing(matrix, listener); |
| 3861 | } |
| 3862 | |
| 3863 | private: |
| 3864 | template <typename ElementIter> |
| 3865 | MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last, |
| 3866 | ::std::vector<std::string>* element_printouts, |
| 3867 | MatchResultListener* listener) const { |
| 3868 | element_printouts->clear(); |
| 3869 | ::std::vector<char> did_match; |
| 3870 | size_t num_elements = 0; |
| 3871 | DummyMatchResultListener dummy; |
| 3872 | for (; elem_first != elem_last; ++num_elements, ++elem_first) { |
| 3873 | if (listener->IsInterested()) { |
| 3874 | element_printouts->push_back(PrintToString(*elem_first)); |
| 3875 | } |
| 3876 | for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { |
| 3877 | did_match.push_back( |
| 3878 | matchers_[irhs].MatchAndExplain(*elem_first, &dummy)); |
| 3879 | } |
| 3880 | } |
| 3881 | |
| 3882 | MatchMatrix matrix(num_elements, matchers_.size()); |
| 3883 | ::std::vector<char>::const_iterator did_match_iter = did_match.begin(); |
| 3884 | for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) { |
| 3885 | for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { |
| 3886 | matrix.SetEdge(ilhs, irhs, b: *did_match_iter++ != 0); |
| 3887 | } |
| 3888 | } |
| 3889 | return matrix; |
| 3890 | } |
| 3891 | |
| 3892 | ::std::vector<Matcher<const Element&>> matchers_; |
| 3893 | }; |
| 3894 | |
| 3895 | // Functor for use in TransformTuple. |
| 3896 | // Performs MatcherCast<Target> on an input argument of any type. |
| 3897 | template <typename Target> |
| 3898 | struct CastAndAppendTransform { |
| 3899 | template <typename Arg> |
| 3900 | Matcher<Target> operator()(const Arg& a) const { |
| 3901 | return MatcherCast<Target>(a); |
| 3902 | } |
| 3903 | }; |
| 3904 | |
| 3905 | // Implements UnorderedElementsAre. |
| 3906 | template <typename MatcherTuple> |
| 3907 | class UnorderedElementsAreMatcher { |
| 3908 | public: |
| 3909 | explicit UnorderedElementsAreMatcher(const MatcherTuple& args) |
| 3910 | : matchers_(args) {} |
| 3911 | |
| 3912 | template <typename Container> |
| 3913 | operator Matcher<Container>() const { |
| 3914 | typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; |
| 3915 | typedef typename internal::StlContainerView<RawContainer>::type View; |
| 3916 | typedef typename View::value_type Element; |
| 3917 | typedef ::std::vector<Matcher<const Element&>> MatcherVec; |
| 3918 | MatcherVec matchers; |
| 3919 | matchers.reserve(::std::tuple_size<MatcherTuple>::value); |
| 3920 | TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, |
| 3921 | ::std::back_inserter(matchers)); |
| 3922 | return Matcher<Container>( |
| 3923 | new UnorderedElementsAreMatcherImpl<const Container&>( |
| 3924 | UnorderedMatcherRequire::ExactMatch, matchers.begin(), |
| 3925 | matchers.end())); |
| 3926 | } |
| 3927 | |
| 3928 | private: |
| 3929 | const MatcherTuple matchers_; |
| 3930 | }; |
| 3931 | |
| 3932 | // Implements ElementsAre. |
| 3933 | template <typename MatcherTuple> |
| 3934 | class ElementsAreMatcher { |
| 3935 | public: |
| 3936 | explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {} |
| 3937 | |
| 3938 | template <typename Container> |
| 3939 | operator Matcher<Container>() const { |
| 3940 | static_assert( |
| 3941 | !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value || |
| 3942 | ::std::tuple_size<MatcherTuple>::value < 2, |
| 3943 | "use UnorderedElementsAre with hash tables" ); |
| 3944 | |
| 3945 | typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; |
| 3946 | typedef typename internal::StlContainerView<RawContainer>::type View; |
| 3947 | typedef typename View::value_type Element; |
| 3948 | typedef ::std::vector<Matcher<const Element&>> MatcherVec; |
| 3949 | MatcherVec matchers; |
| 3950 | matchers.reserve(::std::tuple_size<MatcherTuple>::value); |
| 3951 | TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, |
| 3952 | ::std::back_inserter(matchers)); |
| 3953 | return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>( |
| 3954 | matchers.begin(), matchers.end())); |
| 3955 | } |
| 3956 | |
| 3957 | private: |
| 3958 | const MatcherTuple matchers_; |
| 3959 | }; |
| 3960 | |
| 3961 | // Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf(). |
| 3962 | template <typename T> |
| 3963 | class UnorderedElementsAreArrayMatcher { |
| 3964 | public: |
| 3965 | template <typename Iter> |
| 3966 | UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags, |
| 3967 | Iter first, Iter last) |
| 3968 | : match_flags_(match_flags), matchers_(first, last) {} |
| 3969 | |
| 3970 | template <typename Container> |
| 3971 | operator Matcher<Container>() const { |
| 3972 | return Matcher<Container>( |
| 3973 | new UnorderedElementsAreMatcherImpl<const Container&>( |
| 3974 | match_flags_, matchers_.begin(), matchers_.end())); |
| 3975 | } |
| 3976 | |
| 3977 | private: |
| 3978 | UnorderedMatcherRequire::Flags match_flags_; |
| 3979 | std::vector<std::remove_const_t<T>> matchers_; |
| 3980 | }; |
| 3981 | |
| 3982 | // Implements ElementsAreArray(). |
| 3983 | template <typename T> |
| 3984 | class ElementsAreArrayMatcher { |
| 3985 | public: |
| 3986 | template <typename Iter> |
| 3987 | ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} |
| 3988 | |
| 3989 | template <typename Container> |
| 3990 | operator Matcher<Container>() const { |
| 3991 | static_assert( |
| 3992 | !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value, |
| 3993 | "use UnorderedElementsAreArray with hash tables" ); |
| 3994 | |
| 3995 | return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>( |
| 3996 | matchers_.begin(), matchers_.end())); |
| 3997 | } |
| 3998 | |
| 3999 | private: |
| 4000 | const std::vector<std::remove_const_t<T>> matchers_; |
| 4001 | }; |
| 4002 | |
| 4003 | // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second |
| 4004 | // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm, |
| 4005 | // second) is a polymorphic matcher that matches a value x if and only if |
| 4006 | // tm matches tuple (x, second). Useful for implementing |
| 4007 | // UnorderedPointwise() in terms of UnorderedElementsAreArray(). |
| 4008 | // |
| 4009 | // BoundSecondMatcher is copyable and assignable, as we need to put |
| 4010 | // instances of this class in a vector when implementing |
| 4011 | // UnorderedPointwise(). |
| 4012 | template <typename Tuple2Matcher, typename Second> |
| 4013 | class BoundSecondMatcher { |
| 4014 | public: |
| 4015 | BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second) |
| 4016 | : tuple2_matcher_(tm), second_value_(second) {} |
| 4017 | |
| 4018 | BoundSecondMatcher(const BoundSecondMatcher& other) = default; |
| 4019 | |
| 4020 | template <typename T> |
| 4021 | operator Matcher<T>() const { |
| 4022 | return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_)); |
| 4023 | } |
| 4024 | |
| 4025 | // We have to define this for UnorderedPointwise() to compile in |
| 4026 | // C++98 mode, as it puts BoundSecondMatcher instances in a vector, |
| 4027 | // which requires the elements to be assignable in C++98. The |
| 4028 | // compiler cannot generate the operator= for us, as Tuple2Matcher |
| 4029 | // and Second may not be assignable. |
| 4030 | // |
| 4031 | // However, this should never be called, so the implementation just |
| 4032 | // need to assert. |
| 4033 | void operator=(const BoundSecondMatcher& /*rhs*/) { |
| 4034 | GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned." ; |
| 4035 | } |
| 4036 | |
| 4037 | private: |
| 4038 | template <typename T> |
| 4039 | class Impl : public MatcherInterface<T> { |
| 4040 | public: |
| 4041 | typedef ::std::tuple<T, Second> ArgTuple; |
| 4042 | |
| 4043 | Impl(const Tuple2Matcher& tm, const Second& second) |
| 4044 | : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)), |
| 4045 | second_value_(second) {} |
| 4046 | |
| 4047 | void DescribeTo(::std::ostream* os) const override { |
| 4048 | *os << "and " ; |
| 4049 | UniversalPrint(second_value_, os); |
| 4050 | *os << " " ; |
| 4051 | mono_tuple2_matcher_.DescribeTo(os); |
| 4052 | } |
| 4053 | |
| 4054 | bool MatchAndExplain(T x, MatchResultListener* listener) const override { |
| 4055 | return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_), |
| 4056 | listener); |
| 4057 | } |
| 4058 | |
| 4059 | private: |
| 4060 | const Matcher<const ArgTuple&> mono_tuple2_matcher_; |
| 4061 | const Second second_value_; |
| 4062 | }; |
| 4063 | |
| 4064 | const Tuple2Matcher tuple2_matcher_; |
| 4065 | const Second second_value_; |
| 4066 | }; |
| 4067 | |
| 4068 | // Given a 2-tuple matcher tm and a value second, |
| 4069 | // MatcherBindSecond(tm, second) returns a matcher that matches a |
| 4070 | // value x if and only if tm matches tuple (x, second). Useful for |
| 4071 | // implementing UnorderedPointwise() in terms of UnorderedElementsAreArray(). |
| 4072 | template <typename Tuple2Matcher, typename Second> |
| 4073 | BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond( |
| 4074 | const Tuple2Matcher& tm, const Second& second) { |
| 4075 | return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second); |
| 4076 | } |
| 4077 | |
| 4078 | // Returns the description for a matcher defined using the MATCHER*() |
| 4079 | // macro where the user-supplied description string is "", if |
| 4080 | // 'negation' is false; otherwise returns the description of the |
| 4081 | // negation of the matcher. 'param_values' contains a list of strings |
| 4082 | // that are the print-out of the matcher's parameters. |
| 4083 | GTEST_API_ std::string FormatMatcherDescription( |
| 4084 | bool negation, const char* matcher_name, |
| 4085 | const std::vector<const char*>& param_names, const Strings& param_values); |
| 4086 | |
| 4087 | // Overloads to support `OptionalMatcher` being used with a type that either |
| 4088 | // supports implicit conversion to bool or a `has_value()` method. |
| 4089 | template <typename Optional> |
| 4090 | auto IsOptionalEngaged(const Optional& optional, Rank1) |
| 4091 | -> decltype(!!optional) { |
| 4092 | // The use of double-negation here is to preserve historical behavior where |
| 4093 | // the matcher used `operator!` rather than directly using `operator bool`. |
| 4094 | return !static_cast<bool>(!optional); |
| 4095 | } |
| 4096 | template <typename Optional> |
| 4097 | auto IsOptionalEngaged(const Optional& optional, Rank0) |
| 4098 | -> decltype(!optional.has_value()) { |
| 4099 | return optional.has_value(); |
| 4100 | } |
| 4101 | |
| 4102 | // Implements a matcher that checks the value of a optional<> type variable. |
| 4103 | template <typename ValueMatcher> |
| 4104 | class OptionalMatcher { |
| 4105 | public: |
| 4106 | explicit OptionalMatcher(const ValueMatcher& value_matcher) |
| 4107 | : value_matcher_(value_matcher) {} |
| 4108 | |
| 4109 | template <typename Optional> |
| 4110 | operator Matcher<Optional>() const { |
| 4111 | return Matcher<Optional>(new Impl<const Optional&>(value_matcher_)); |
| 4112 | } |
| 4113 | |
| 4114 | template <typename Optional> |
| 4115 | class Impl : public MatcherInterface<Optional> { |
| 4116 | public: |
| 4117 | typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView; |
| 4118 | typedef typename OptionalView::value_type ValueType; |
| 4119 | explicit Impl(const ValueMatcher& value_matcher) |
| 4120 | : value_matcher_(MatcherCast<ValueType>(value_matcher)) {} |
| 4121 | |
| 4122 | void DescribeTo(::std::ostream* os) const override { |
| 4123 | *os << "value " ; |
| 4124 | value_matcher_.DescribeTo(os); |
| 4125 | } |
| 4126 | |
| 4127 | void DescribeNegationTo(::std::ostream* os) const override { |
| 4128 | *os << "value " ; |
| 4129 | value_matcher_.DescribeNegationTo(os); |
| 4130 | } |
| 4131 | |
| 4132 | bool MatchAndExplain(Optional optional, |
| 4133 | MatchResultListener* listener) const override { |
| 4134 | if (!IsOptionalEngaged(optional, HighestRank())) { |
| 4135 | *listener << "which is not engaged" ; |
| 4136 | return false; |
| 4137 | } |
| 4138 | const ValueType& value = *optional; |
| 4139 | if (!listener->IsInterested()) { |
| 4140 | // Fast path to avoid unnecessary generation of match explanation. |
| 4141 | return value_matcher_.Matches(value); |
| 4142 | } |
| 4143 | StringMatchResultListener value_listener; |
| 4144 | const bool match = value_matcher_.MatchAndExplain(value, &value_listener); |
| 4145 | *listener << "whose value " << PrintToString(value) |
| 4146 | << (match ? " matches" : " doesn't match" ); |
| 4147 | PrintIfNotEmpty(explanation: value_listener.str(), os: listener->stream()); |
| 4148 | return match; |
| 4149 | } |
| 4150 | |
| 4151 | private: |
| 4152 | const Matcher<ValueType> value_matcher_; |
| 4153 | }; |
| 4154 | |
| 4155 | private: |
| 4156 | const ValueMatcher value_matcher_; |
| 4157 | }; |
| 4158 | |
| 4159 | namespace variant_matcher { |
| 4160 | // Overloads to allow VariantMatcher to do proper ADL lookup. |
| 4161 | template <typename T> |
| 4162 | void holds_alternative() {} |
| 4163 | template <typename T> |
| 4164 | void get() {} |
| 4165 | |
| 4166 | // Implements a matcher that checks the value of a variant<> type variable. |
| 4167 | template <typename T> |
| 4168 | class VariantMatcher { |
| 4169 | public: |
| 4170 | explicit VariantMatcher(::testing::Matcher<const T&> matcher) |
| 4171 | : matcher_(std::move(matcher)) {} |
| 4172 | |
| 4173 | template <typename Variant> |
| 4174 | bool MatchAndExplain(const Variant& value, |
| 4175 | ::testing::MatchResultListener* listener) const { |
| 4176 | using std::get; |
| 4177 | if (!listener->IsInterested()) { |
| 4178 | return holds_alternative<T>(value) && matcher_.Matches(get<T>(value)); |
| 4179 | } |
| 4180 | |
| 4181 | if (!holds_alternative<T>(value)) { |
| 4182 | *listener << "whose value is not of type '" << GetTypeName() << "'" ; |
| 4183 | return false; |
| 4184 | } |
| 4185 | |
| 4186 | const T& elem = get<T>(value); |
| 4187 | StringMatchResultListener elem_listener; |
| 4188 | const bool match = matcher_.MatchAndExplain(elem, &elem_listener); |
| 4189 | *listener << "whose value " << PrintToString(elem) |
| 4190 | << (match ? " matches" : " doesn't match" ); |
| 4191 | PrintIfNotEmpty(explanation: elem_listener.str(), os: listener->stream()); |
| 4192 | return match; |
| 4193 | } |
| 4194 | |
| 4195 | void DescribeTo(std::ostream* os) const { |
| 4196 | *os << "is a variant<> with value of type '" << GetTypeName() |
| 4197 | << "' and the value " ; |
| 4198 | matcher_.DescribeTo(os); |
| 4199 | } |
| 4200 | |
| 4201 | void DescribeNegationTo(std::ostream* os) const { |
| 4202 | *os << "is a variant<> with value of type other than '" << GetTypeName() |
| 4203 | << "' or the value " ; |
| 4204 | matcher_.DescribeNegationTo(os); |
| 4205 | } |
| 4206 | |
| 4207 | private: |
| 4208 | static std::string GetTypeName() { |
| 4209 | #if GTEST_HAS_RTTI |
| 4210 | GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_( |
| 4211 | return internal::GetTypeName<T>()); |
| 4212 | #endif |
| 4213 | return "the element type" ; |
| 4214 | } |
| 4215 | |
| 4216 | const ::testing::Matcher<const T&> matcher_; |
| 4217 | }; |
| 4218 | |
| 4219 | } // namespace variant_matcher |
| 4220 | |
| 4221 | namespace any_cast_matcher { |
| 4222 | |
| 4223 | // Overloads to allow AnyCastMatcher to do proper ADL lookup. |
| 4224 | template <typename T> |
| 4225 | void any_cast() {} |
| 4226 | |
| 4227 | // Implements a matcher that any_casts the value. |
| 4228 | template <typename T> |
| 4229 | class AnyCastMatcher { |
| 4230 | public: |
| 4231 | explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher) |
| 4232 | : matcher_(matcher) {} |
| 4233 | |
| 4234 | template <typename AnyType> |
| 4235 | bool MatchAndExplain(const AnyType& value, |
| 4236 | ::testing::MatchResultListener* listener) const { |
| 4237 | if (!listener->IsInterested()) { |
| 4238 | const T* ptr = any_cast<T>(&value); |
| 4239 | return ptr != nullptr && matcher_.Matches(*ptr); |
| 4240 | } |
| 4241 | |
| 4242 | const T* elem = any_cast<T>(&value); |
| 4243 | if (elem == nullptr) { |
| 4244 | *listener << "whose value is not of type '" << GetTypeName() << "'" ; |
| 4245 | return false; |
| 4246 | } |
| 4247 | |
| 4248 | StringMatchResultListener elem_listener; |
| 4249 | const bool match = matcher_.MatchAndExplain(*elem, &elem_listener); |
| 4250 | *listener << "whose value " << PrintToString(*elem) |
| 4251 | << (match ? " matches" : " doesn't match" ); |
| 4252 | PrintIfNotEmpty(explanation: elem_listener.str(), os: listener->stream()); |
| 4253 | return match; |
| 4254 | } |
| 4255 | |
| 4256 | void DescribeTo(std::ostream* os) const { |
| 4257 | *os << "is an 'any' type with value of type '" << GetTypeName() |
| 4258 | << "' and the value " ; |
| 4259 | matcher_.DescribeTo(os); |
| 4260 | } |
| 4261 | |
| 4262 | void DescribeNegationTo(std::ostream* os) const { |
| 4263 | *os << "is an 'any' type with value of type other than '" << GetTypeName() |
| 4264 | << "' or the value " ; |
| 4265 | matcher_.DescribeNegationTo(os); |
| 4266 | } |
| 4267 | |
| 4268 | private: |
| 4269 | static std::string GetTypeName() { |
| 4270 | #if GTEST_HAS_RTTI |
| 4271 | GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_( |
| 4272 | return internal::GetTypeName<T>()); |
| 4273 | #endif |
| 4274 | return "the element type" ; |
| 4275 | } |
| 4276 | |
| 4277 | const ::testing::Matcher<const T&> matcher_; |
| 4278 | }; |
| 4279 | |
| 4280 | } // namespace any_cast_matcher |
| 4281 | |
| 4282 | // Implements the Args() matcher. |
| 4283 | template <class ArgsTuple, size_t... k> |
| 4284 | class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> { |
| 4285 | public: |
| 4286 | using RawArgsTuple = typename std::decay<ArgsTuple>::type; |
| 4287 | using SelectedArgs = |
| 4288 | std::tuple<typename std::tuple_element<k, RawArgsTuple>::type...>; |
| 4289 | using MonomorphicInnerMatcher = Matcher<const SelectedArgs&>; |
| 4290 | |
| 4291 | template <typename InnerMatcher> |
| 4292 | explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher) |
| 4293 | : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {} |
| 4294 | |
| 4295 | bool MatchAndExplain(ArgsTuple args, |
| 4296 | MatchResultListener* listener) const override { |
| 4297 | // Workaround spurious C4100 on MSVC<=15.7 when k is empty. |
| 4298 | (void)args; |
| 4299 | const SelectedArgs& selected_args = |
| 4300 | std::forward_as_tuple(std::get<k>(args)...); |
| 4301 | if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args); |
| 4302 | |
| 4303 | PrintIndices(os: listener->stream()); |
| 4304 | *listener << "are " << PrintToString(selected_args); |
| 4305 | |
| 4306 | StringMatchResultListener inner_listener; |
| 4307 | const bool match = |
| 4308 | inner_matcher_.MatchAndExplain(selected_args, &inner_listener); |
| 4309 | PrintIfNotEmpty(explanation: inner_listener.str(), os: listener->stream()); |
| 4310 | return match; |
| 4311 | } |
| 4312 | |
| 4313 | void DescribeTo(::std::ostream* os) const override { |
| 4314 | *os << "are a tuple " ; |
| 4315 | PrintIndices(os); |
| 4316 | inner_matcher_.DescribeTo(os); |
| 4317 | } |
| 4318 | |
| 4319 | void DescribeNegationTo(::std::ostream* os) const override { |
| 4320 | *os << "are a tuple " ; |
| 4321 | PrintIndices(os); |
| 4322 | inner_matcher_.DescribeNegationTo(os); |
| 4323 | } |
| 4324 | |
| 4325 | private: |
| 4326 | // Prints the indices of the selected fields. |
| 4327 | static void PrintIndices(::std::ostream* os) { |
| 4328 | *os << "whose fields (" ; |
| 4329 | const char* sep = "" ; |
| 4330 | // Workaround spurious C4189 on MSVC<=15.7 when k is empty. |
| 4331 | (void)sep; |
| 4332 | // The static_cast to void is needed to silence Clang's -Wcomma warning. |
| 4333 | // This pattern looks suspiciously like we may have mismatched parentheses |
| 4334 | // and may have been trying to use the first operation of the comma operator |
| 4335 | // as a member of the array, so Clang warns that we may have made a mistake. |
| 4336 | const char* dummy[] = { |
| 4337 | "" , (static_cast<void>(*os << sep << "#" << k), sep = ", " )...}; |
| 4338 | (void)dummy; |
| 4339 | *os << ") " ; |
| 4340 | } |
| 4341 | |
| 4342 | MonomorphicInnerMatcher inner_matcher_; |
| 4343 | }; |
| 4344 | |
| 4345 | template <class InnerMatcher, size_t... k> |
| 4346 | class ArgsMatcher { |
| 4347 | public: |
| 4348 | explicit ArgsMatcher(InnerMatcher inner_matcher) |
| 4349 | : inner_matcher_(std::move(inner_matcher)) {} |
| 4350 | |
| 4351 | template <typename ArgsTuple> |
| 4352 | operator Matcher<ArgsTuple>() const { // NOLINT |
| 4353 | return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k...>(inner_matcher_)); |
| 4354 | } |
| 4355 | |
| 4356 | private: |
| 4357 | InnerMatcher inner_matcher_; |
| 4358 | }; |
| 4359 | |
| 4360 | } // namespace internal |
| 4361 | |
| 4362 | // ElementsAreArray(iterator_first, iterator_last) |
| 4363 | // ElementsAreArray(pointer, count) |
| 4364 | // ElementsAreArray(array) |
| 4365 | // ElementsAreArray(container) |
| 4366 | // ElementsAreArray({ e1, e2, ..., en }) |
| 4367 | // |
| 4368 | // The ElementsAreArray() functions are like ElementsAre(...), except |
| 4369 | // that they are given a homogeneous sequence rather than taking each |
| 4370 | // element as a function argument. The sequence can be specified as an |
| 4371 | // array, a pointer and count, a vector, an initializer list, or an |
| 4372 | // STL iterator range. In each of these cases, the underlying sequence |
| 4373 | // can be either a sequence of values or a sequence of matchers. |
| 4374 | // |
| 4375 | // All forms of ElementsAreArray() make a copy of the input matcher sequence. |
| 4376 | |
| 4377 | template <typename Iter> |
| 4378 | inline internal::ElementsAreArrayMatcher< |
| 4379 | typename ::std::iterator_traits<Iter>::value_type> |
| 4380 | ElementsAreArray(Iter first, Iter last) { |
| 4381 | typedef typename ::std::iterator_traits<Iter>::value_type T; |
| 4382 | return internal::ElementsAreArrayMatcher<T>(first, last); |
| 4383 | } |
| 4384 | |
| 4385 | template <typename T> |
| 4386 | inline auto ElementsAreArray(const T* pointer, size_t count) |
| 4387 | -> decltype(ElementsAreArray(pointer, pointer + count)) { |
| 4388 | return ElementsAreArray(pointer, pointer + count); |
| 4389 | } |
| 4390 | |
| 4391 | template <typename T, size_t N> |
| 4392 | inline auto ElementsAreArray(const T (&array)[N]) |
| 4393 | -> decltype(ElementsAreArray(array, N)) { |
| 4394 | return ElementsAreArray(array, N); |
| 4395 | } |
| 4396 | |
| 4397 | template <typename Container> |
| 4398 | inline auto ElementsAreArray(const Container& container) |
| 4399 | -> decltype(ElementsAreArray(container.begin(), container.end())) { |
| 4400 | return ElementsAreArray(container.begin(), container.end()); |
| 4401 | } |
| 4402 | |
| 4403 | template <typename T> |
| 4404 | inline auto ElementsAreArray(::std::initializer_list<T> xs) |
| 4405 | -> decltype(ElementsAreArray(xs.begin(), xs.end())) { |
| 4406 | return ElementsAreArray(xs.begin(), xs.end()); |
| 4407 | } |
| 4408 | |
| 4409 | // UnorderedElementsAreArray(iterator_first, iterator_last) |
| 4410 | // UnorderedElementsAreArray(pointer, count) |
| 4411 | // UnorderedElementsAreArray(array) |
| 4412 | // UnorderedElementsAreArray(container) |
| 4413 | // UnorderedElementsAreArray({ e1, e2, ..., en }) |
| 4414 | // |
| 4415 | // UnorderedElementsAreArray() verifies that a bijective mapping onto a |
| 4416 | // collection of matchers exists. |
| 4417 | // |
| 4418 | // The matchers can be specified as an array, a pointer and count, a container, |
| 4419 | // an initializer list, or an STL iterator range. In each of these cases, the |
| 4420 | // underlying matchers can be either values or matchers. |
| 4421 | |
| 4422 | template <typename Iter> |
| 4423 | inline internal::UnorderedElementsAreArrayMatcher< |
| 4424 | typename ::std::iterator_traits<Iter>::value_type> |
| 4425 | UnorderedElementsAreArray(Iter first, Iter last) { |
| 4426 | typedef typename ::std::iterator_traits<Iter>::value_type T; |
| 4427 | return internal::UnorderedElementsAreArrayMatcher<T>( |
| 4428 | internal::UnorderedMatcherRequire::ExactMatch, first, last); |
| 4429 | } |
| 4430 | |
| 4431 | template <typename T> |
| 4432 | inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray( |
| 4433 | const T* pointer, size_t count) { |
| 4434 | return UnorderedElementsAreArray(pointer, pointer + count); |
| 4435 | } |
| 4436 | |
| 4437 | template <typename T, size_t N> |
| 4438 | inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray( |
| 4439 | const T (&array)[N]) { |
| 4440 | return UnorderedElementsAreArray(array, N); |
| 4441 | } |
| 4442 | |
| 4443 | template <typename Container> |
| 4444 | inline internal::UnorderedElementsAreArrayMatcher< |
| 4445 | typename Container::value_type> |
| 4446 | UnorderedElementsAreArray(const Container& container) { |
| 4447 | return UnorderedElementsAreArray(container.begin(), container.end()); |
| 4448 | } |
| 4449 | |
| 4450 | template <typename T> |
| 4451 | inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray( |
| 4452 | ::std::initializer_list<T> xs) { |
| 4453 | return UnorderedElementsAreArray(xs.begin(), xs.end()); |
| 4454 | } |
| 4455 | |
| 4456 | // _ is a matcher that matches anything of any type. |
| 4457 | // |
| 4458 | // This definition is fine as: |
| 4459 | // |
| 4460 | // 1. The C++ standard permits using the name _ in a namespace that |
| 4461 | // is not the global namespace or ::std. |
| 4462 | // 2. The AnythingMatcher class has no data member or constructor, |
| 4463 | // so it's OK to create global variables of this type. |
| 4464 | // 3. c-style has approved of using _ in this case. |
| 4465 | const internal::AnythingMatcher _ = {}; |
| 4466 | // Creates a matcher that matches any value of the given type T. |
| 4467 | template <typename T> |
| 4468 | inline Matcher<T> A() { |
| 4469 | return _; |
| 4470 | } |
| 4471 | |
| 4472 | // Creates a matcher that matches any value of the given type T. |
| 4473 | template <typename T> |
| 4474 | inline Matcher<T> An() { |
| 4475 | return _; |
| 4476 | } |
| 4477 | |
| 4478 | template <typename T, typename M> |
| 4479 | Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl( |
| 4480 | const M& value, std::false_type /* convertible_to_matcher */, |
| 4481 | std::false_type /* convertible_to_T */) { |
| 4482 | return Eq(value); |
| 4483 | } |
| 4484 | |
| 4485 | // Creates a polymorphic matcher that matches any NULL pointer. |
| 4486 | inline PolymorphicMatcher<internal::IsNullMatcher> IsNull() { |
| 4487 | return MakePolymorphicMatcher(impl: internal::IsNullMatcher()); |
| 4488 | } |
| 4489 | |
| 4490 | // Creates a polymorphic matcher that matches any non-NULL pointer. |
| 4491 | // This is convenient as Not(NULL) doesn't compile (the compiler |
| 4492 | // thinks that that expression is comparing a pointer with an integer). |
| 4493 | inline PolymorphicMatcher<internal::NotNullMatcher> NotNull() { |
| 4494 | return MakePolymorphicMatcher(impl: internal::NotNullMatcher()); |
| 4495 | } |
| 4496 | |
| 4497 | // Creates a polymorphic matcher that matches any argument that |
| 4498 | // references variable x. |
| 4499 | template <typename T> |
| 4500 | inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT |
| 4501 | return internal::RefMatcher<T&>(x); |
| 4502 | } |
| 4503 | |
| 4504 | // Creates a polymorphic matcher that matches any NaN floating point. |
| 4505 | inline PolymorphicMatcher<internal::IsNanMatcher> IsNan() { |
| 4506 | return MakePolymorphicMatcher(impl: internal::IsNanMatcher()); |
| 4507 | } |
| 4508 | |
| 4509 | // Creates a matcher that matches any double argument approximately |
| 4510 | // equal to rhs, where two NANs are considered unequal. |
| 4511 | inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) { |
| 4512 | return internal::FloatingEqMatcher<double>(rhs, false); |
| 4513 | } |
| 4514 | |
| 4515 | // Creates a matcher that matches any double argument approximately |
| 4516 | // equal to rhs, including NaN values when rhs is NaN. |
| 4517 | inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) { |
| 4518 | return internal::FloatingEqMatcher<double>(rhs, true); |
| 4519 | } |
| 4520 | |
| 4521 | // Creates a matcher that matches any double argument approximately equal to |
| 4522 | // rhs, up to the specified max absolute error bound, where two NANs are |
| 4523 | // considered unequal. The max absolute error bound must be non-negative. |
| 4524 | inline internal::FloatingEqMatcher<double> DoubleNear(double rhs, |
| 4525 | double max_abs_error) { |
| 4526 | return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error); |
| 4527 | } |
| 4528 | |
| 4529 | // The DistanceFrom(target, get_distance, m) and DistanceFrom(target, m) |
| 4530 | // matchers work on arbitrary types that have the "distance" concept. What they |
| 4531 | // do: |
| 4532 | // |
| 4533 | // 1. compute the distance between the value and the target using |
| 4534 | // get_distance(value, target) if get_distance is provided; otherwise compute |
| 4535 | // the distance as abs(value - target). |
| 4536 | // 2. match the distance against the user-provided matcher m; if the match |
| 4537 | // succeeds, the DistanceFrom() match succeeds. |
| 4538 | // |
| 4539 | // Examples: |
| 4540 | // |
| 4541 | // // 0.5's distance from 0.6 should be <= 0.2. |
| 4542 | // EXPECT_THAT(0.5, DistanceFrom(0.6, Le(0.2))); |
| 4543 | // |
| 4544 | // Vector2D v1(3.0, 4.0), v2(3.2, 6.0); |
| 4545 | // // v1's distance from v2, as computed by EuclideanDistance(v1, v2), |
| 4546 | // // should be >= 1.0. |
| 4547 | // EXPECT_THAT(v1, DistanceFrom(v2, EuclideanDistance, Ge(1.0))); |
| 4548 | |
| 4549 | template <typename T, typename GetDistance, typename DistanceMatcher> |
| 4550 | inline internal::DistanceFromMatcher<T, GetDistance, DistanceMatcher> |
| 4551 | DistanceFrom(T target, GetDistance get_distance, |
| 4552 | DistanceMatcher distance_matcher) { |
| 4553 | return internal::DistanceFromMatcher<T, GetDistance, DistanceMatcher>( |
| 4554 | std::move(target), std::move(get_distance), std::move(distance_matcher)); |
| 4555 | } |
| 4556 | |
| 4557 | template <typename T, typename DistanceMatcher> |
| 4558 | inline internal::DistanceFromMatcher<T, internal::DefaultGetDistance, |
| 4559 | DistanceMatcher> |
| 4560 | DistanceFrom(T target, DistanceMatcher distance_matcher) { |
| 4561 | return DistanceFrom(std::move(target), internal::DefaultGetDistance(), |
| 4562 | std::move(distance_matcher)); |
| 4563 | } |
| 4564 | |
| 4565 | // Creates a matcher that matches any double argument approximately equal to |
| 4566 | // rhs, up to the specified max absolute error bound, including NaN values when |
| 4567 | // rhs is NaN. The max absolute error bound must be non-negative. |
| 4568 | inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear( |
| 4569 | double rhs, double max_abs_error) { |
| 4570 | return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error); |
| 4571 | } |
| 4572 | |
| 4573 | // Creates a matcher that matches any float argument approximately |
| 4574 | // equal to rhs, where two NANs are considered unequal. |
| 4575 | inline internal::FloatingEqMatcher<float> FloatEq(float rhs) { |
| 4576 | return internal::FloatingEqMatcher<float>(rhs, false); |
| 4577 | } |
| 4578 | |
| 4579 | // Creates a matcher that matches any float argument approximately |
| 4580 | // equal to rhs, including NaN values when rhs is NaN. |
| 4581 | inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) { |
| 4582 | return internal::FloatingEqMatcher<float>(rhs, true); |
| 4583 | } |
| 4584 | |
| 4585 | // Creates a matcher that matches any float argument approximately equal to |
| 4586 | // rhs, up to the specified max absolute error bound, where two NANs are |
| 4587 | // considered unequal. The max absolute error bound must be non-negative. |
| 4588 | inline internal::FloatingEqMatcher<float> FloatNear(float rhs, |
| 4589 | float max_abs_error) { |
| 4590 | return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error); |
| 4591 | } |
| 4592 | |
| 4593 | // Creates a matcher that matches any float argument approximately equal to |
| 4594 | // rhs, up to the specified max absolute error bound, including NaN values when |
| 4595 | // rhs is NaN. The max absolute error bound must be non-negative. |
| 4596 | inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear( |
| 4597 | float rhs, float max_abs_error) { |
| 4598 | return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error); |
| 4599 | } |
| 4600 | |
| 4601 | // Creates a matcher that matches a pointer (raw or smart) that points |
| 4602 | // to a value that matches inner_matcher. |
| 4603 | template <typename InnerMatcher> |
| 4604 | inline internal::PointeeMatcher<InnerMatcher> Pointee( |
| 4605 | const InnerMatcher& inner_matcher) { |
| 4606 | return internal::PointeeMatcher<InnerMatcher>(inner_matcher); |
| 4607 | } |
| 4608 | |
| 4609 | #if GTEST_HAS_RTTI |
| 4610 | // Creates a matcher that matches a pointer or reference that matches |
| 4611 | // inner_matcher when dynamic_cast<To> is applied. |
| 4612 | // The result of dynamic_cast<To> is forwarded to the inner matcher. |
| 4613 | // If To is a pointer and the cast fails, the inner matcher will receive NULL. |
| 4614 | // If To is a reference and the cast fails, this matcher returns false |
| 4615 | // immediately. |
| 4616 | template <typename To> |
| 4617 | inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To>> |
| 4618 | WhenDynamicCastTo(const Matcher<To>& inner_matcher) { |
| 4619 | return MakePolymorphicMatcher( |
| 4620 | internal::WhenDynamicCastToMatcher<To>(inner_matcher)); |
| 4621 | } |
| 4622 | #endif // GTEST_HAS_RTTI |
| 4623 | |
| 4624 | // Creates a matcher that matches an object whose given field matches |
| 4625 | // 'matcher'. For example, |
| 4626 | // Field(&Foo::number, Ge(5)) |
| 4627 | // matches a Foo object x if and only if x.number >= 5. |
| 4628 | template <typename Class, typename FieldType, typename FieldMatcher> |
| 4629 | inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field( |
| 4630 | FieldType Class::* field, const FieldMatcher& matcher) { |
| 4631 | return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>( |
| 4632 | field, MatcherCast<const FieldType&>(matcher))); |
| 4633 | // The call to MatcherCast() is required for supporting inner |
| 4634 | // matchers of compatible types. For example, it allows |
| 4635 | // Field(&Foo::bar, m) |
| 4636 | // to compile where bar is an int32 and m is a matcher for int64. |
| 4637 | } |
| 4638 | |
| 4639 | // Same as Field() but also takes the name of the field to provide better error |
| 4640 | // messages. |
| 4641 | template <typename Class, typename FieldType, typename FieldMatcher> |
| 4642 | inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field( |
| 4643 | const std::string& field_name, FieldType Class::* field, |
| 4644 | const FieldMatcher& matcher) { |
| 4645 | return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>( |
| 4646 | field_name, field, MatcherCast<const FieldType&>(matcher))); |
| 4647 | } |
| 4648 | |
| 4649 | // Creates a matcher that matches an object whose given property |
| 4650 | // matches 'matcher'. For example, |
| 4651 | // Property(&Foo::str, StartsWith("hi")) |
| 4652 | // matches a Foo object x if and only if x.str() starts with "hi". |
| 4653 | // |
| 4654 | // Warning: Don't use `Property()` against member functions that you do not |
| 4655 | // own, because taking addresses of functions is fragile and generally not part |
| 4656 | // of the contract of the function. |
| 4657 | template <typename Class, typename PropertyType, typename PropertyMatcher> |
| 4658 | inline PolymorphicMatcher<internal::PropertyMatcher< |
| 4659 | Class, PropertyType, PropertyType (Class::*)() const>> |
| 4660 | Property(PropertyType (Class::*property)() const, |
| 4661 | const PropertyMatcher& matcher) { |
| 4662 | return MakePolymorphicMatcher( |
| 4663 | internal::PropertyMatcher<Class, PropertyType, |
| 4664 | PropertyType (Class::*)() const>( |
| 4665 | property, MatcherCast<const PropertyType&>(matcher))); |
| 4666 | // The call to MatcherCast() is required for supporting inner |
| 4667 | // matchers of compatible types. For example, it allows |
| 4668 | // Property(&Foo::bar, m) |
| 4669 | // to compile where bar() returns an int32 and m is a matcher for int64. |
| 4670 | } |
| 4671 | |
| 4672 | // Same as Property() above, but also takes the name of the property to provide |
| 4673 | // better error messages. |
| 4674 | template <typename Class, typename PropertyType, typename PropertyMatcher> |
| 4675 | inline PolymorphicMatcher<internal::PropertyMatcher< |
| 4676 | Class, PropertyType, PropertyType (Class::*)() const>> |
| 4677 | Property(const std::string& property_name, |
| 4678 | PropertyType (Class::*property)() const, |
| 4679 | const PropertyMatcher& matcher) { |
| 4680 | return MakePolymorphicMatcher( |
| 4681 | internal::PropertyMatcher<Class, PropertyType, |
| 4682 | PropertyType (Class::*)() const>( |
| 4683 | property_name, property, MatcherCast<const PropertyType&>(matcher))); |
| 4684 | } |
| 4685 | |
| 4686 | // The same as above but for reference-qualified member functions. |
| 4687 | template <typename Class, typename PropertyType, typename PropertyMatcher> |
| 4688 | inline PolymorphicMatcher<internal::PropertyMatcher< |
| 4689 | Class, PropertyType, PropertyType (Class::*)() const&>> |
| 4690 | Property(PropertyType (Class::*property)() const&, |
| 4691 | const PropertyMatcher& matcher) { |
| 4692 | return MakePolymorphicMatcher( |
| 4693 | internal::PropertyMatcher<Class, PropertyType, |
| 4694 | PropertyType (Class::*)() const&>( |
| 4695 | property, MatcherCast<const PropertyType&>(matcher))); |
| 4696 | } |
| 4697 | |
| 4698 | // Three-argument form for reference-qualified member functions. |
| 4699 | template <typename Class, typename PropertyType, typename PropertyMatcher> |
| 4700 | inline PolymorphicMatcher<internal::PropertyMatcher< |
| 4701 | Class, PropertyType, PropertyType (Class::*)() const&>> |
| 4702 | Property(const std::string& property_name, |
| 4703 | PropertyType (Class::*property)() const&, |
| 4704 | const PropertyMatcher& matcher) { |
| 4705 | return MakePolymorphicMatcher( |
| 4706 | internal::PropertyMatcher<Class, PropertyType, |
| 4707 | PropertyType (Class::*)() const&>( |
| 4708 | property_name, property, MatcherCast<const PropertyType&>(matcher))); |
| 4709 | } |
| 4710 | |
| 4711 | // Creates a matcher that matches an object if and only if the result of |
| 4712 | // applying a callable to x matches 'matcher'. For example, |
| 4713 | // ResultOf(f, StartsWith("hi")) |
| 4714 | // matches a Foo object x if and only if f(x) starts with "hi". |
| 4715 | // `callable` parameter can be a function, function pointer, or a functor. It is |
| 4716 | // required to keep no state affecting the results of the calls on it and make |
| 4717 | // no assumptions about how many calls will be made. Any state it keeps must be |
| 4718 | // protected from the concurrent access. |
| 4719 | template <typename Callable, typename InnerMatcher> |
| 4720 | internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf( |
| 4721 | Callable callable, InnerMatcher matcher) { |
| 4722 | return internal::ResultOfMatcher<Callable, InnerMatcher>(std::move(callable), |
| 4723 | std::move(matcher)); |
| 4724 | } |
| 4725 | |
| 4726 | // Same as ResultOf() above, but also takes a description of the `callable` |
| 4727 | // result to provide better error messages. |
| 4728 | template <typename Callable, typename InnerMatcher> |
| 4729 | internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf( |
| 4730 | const std::string& result_description, Callable callable, |
| 4731 | InnerMatcher matcher) { |
| 4732 | return internal::ResultOfMatcher<Callable, InnerMatcher>( |
| 4733 | result_description, std::move(callable), std::move(matcher)); |
| 4734 | } |
| 4735 | |
| 4736 | // String matchers. |
| 4737 | |
| 4738 | // Matches a string equal to str. |
| 4739 | template <typename T = std::string> |
| 4740 | PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrEq( |
| 4741 | const internal::StringLike<T>& str) { |
| 4742 | return MakePolymorphicMatcher( |
| 4743 | impl: internal::StrEqualityMatcher<std::string>(std::string(str), true, true)); |
| 4744 | } |
| 4745 | |
| 4746 | // Matches a string not equal to str. |
| 4747 | template <typename T = std::string> |
| 4748 | PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrNe( |
| 4749 | const internal::StringLike<T>& str) { |
| 4750 | return MakePolymorphicMatcher( |
| 4751 | impl: internal::StrEqualityMatcher<std::string>(std::string(str), false, true)); |
| 4752 | } |
| 4753 | |
| 4754 | // Matches a string equal to str, ignoring case. |
| 4755 | template <typename T = std::string> |
| 4756 | PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseEq( |
| 4757 | const internal::StringLike<T>& str) { |
| 4758 | return MakePolymorphicMatcher( |
| 4759 | impl: internal::StrEqualityMatcher<std::string>(std::string(str), true, false)); |
| 4760 | } |
| 4761 | |
| 4762 | // Matches a string not equal to str, ignoring case. |
| 4763 | template <typename T = std::string> |
| 4764 | PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseNe( |
| 4765 | const internal::StringLike<T>& str) { |
| 4766 | return MakePolymorphicMatcher(impl: internal::StrEqualityMatcher<std::string>( |
| 4767 | std::string(str), false, false)); |
| 4768 | } |
| 4769 | |
| 4770 | // Creates a matcher that matches any string, std::string, or C string |
| 4771 | // that contains the given substring. |
| 4772 | template <typename T = std::string> |
| 4773 | PolymorphicMatcher<internal::HasSubstrMatcher<std::string>> HasSubstr( |
| 4774 | const internal::StringLike<T>& substring) { |
| 4775 | return MakePolymorphicMatcher( |
| 4776 | impl: internal::HasSubstrMatcher<std::string>(std::string(substring))); |
| 4777 | } |
| 4778 | |
| 4779 | // Matches a string that starts with 'prefix' (case-sensitive). |
| 4780 | template <typename T = std::string> |
| 4781 | PolymorphicMatcher<internal::StartsWithMatcher<std::string>> StartsWith( |
| 4782 | const internal::StringLike<T>& prefix) { |
| 4783 | return MakePolymorphicMatcher( |
| 4784 | impl: internal::StartsWithMatcher<std::string>(std::string(prefix))); |
| 4785 | } |
| 4786 | |
| 4787 | // Matches a string that ends with 'suffix' (case-sensitive). |
| 4788 | template <typename T = std::string> |
| 4789 | PolymorphicMatcher<internal::EndsWithMatcher<std::string>> EndsWith( |
| 4790 | const internal::StringLike<T>& suffix) { |
| 4791 | return MakePolymorphicMatcher( |
| 4792 | impl: internal::EndsWithMatcher<std::string>(std::string(suffix))); |
| 4793 | } |
| 4794 | |
| 4795 | #if GTEST_HAS_STD_WSTRING |
| 4796 | // Wide string matchers. |
| 4797 | |
| 4798 | // Matches a string equal to str. |
| 4799 | inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrEq( |
| 4800 | const std::wstring& str) { |
| 4801 | return MakePolymorphicMatcher( |
| 4802 | impl: internal::StrEqualityMatcher<std::wstring>(str, true, true)); |
| 4803 | } |
| 4804 | |
| 4805 | // Matches a string not equal to str. |
| 4806 | inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrNe( |
| 4807 | const std::wstring& str) { |
| 4808 | return MakePolymorphicMatcher( |
| 4809 | impl: internal::StrEqualityMatcher<std::wstring>(str, false, true)); |
| 4810 | } |
| 4811 | |
| 4812 | // Matches a string equal to str, ignoring case. |
| 4813 | inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseEq( |
| 4814 | const std::wstring& str) { |
| 4815 | return MakePolymorphicMatcher( |
| 4816 | impl: internal::StrEqualityMatcher<std::wstring>(str, true, false)); |
| 4817 | } |
| 4818 | |
| 4819 | // Matches a string not equal to str, ignoring case. |
| 4820 | inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseNe( |
| 4821 | const std::wstring& str) { |
| 4822 | return MakePolymorphicMatcher( |
| 4823 | impl: internal::StrEqualityMatcher<std::wstring>(str, false, false)); |
| 4824 | } |
| 4825 | |
| 4826 | // Creates a matcher that matches any ::wstring, std::wstring, or C wide string |
| 4827 | // that contains the given substring. |
| 4828 | inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring>> HasSubstr( |
| 4829 | const std::wstring& substring) { |
| 4830 | return MakePolymorphicMatcher( |
| 4831 | impl: internal::HasSubstrMatcher<std::wstring>(substring)); |
| 4832 | } |
| 4833 | |
| 4834 | // Matches a string that starts with 'prefix' (case-sensitive). |
| 4835 | inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring>> StartsWith( |
| 4836 | const std::wstring& prefix) { |
| 4837 | return MakePolymorphicMatcher( |
| 4838 | impl: internal::StartsWithMatcher<std::wstring>(prefix)); |
| 4839 | } |
| 4840 | |
| 4841 | // Matches a string that ends with 'suffix' (case-sensitive). |
| 4842 | inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring>> EndsWith( |
| 4843 | const std::wstring& suffix) { |
| 4844 | return MakePolymorphicMatcher( |
| 4845 | impl: internal::EndsWithMatcher<std::wstring>(suffix)); |
| 4846 | } |
| 4847 | |
| 4848 | #endif // GTEST_HAS_STD_WSTRING |
| 4849 | |
| 4850 | // Creates a polymorphic matcher that matches a 2-tuple where the |
| 4851 | // first field == the second field. |
| 4852 | inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); } |
| 4853 | |
| 4854 | // Creates a polymorphic matcher that matches a 2-tuple where the |
| 4855 | // first field >= the second field. |
| 4856 | inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); } |
| 4857 | |
| 4858 | // Creates a polymorphic matcher that matches a 2-tuple where the |
| 4859 | // first field > the second field. |
| 4860 | inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); } |
| 4861 | |
| 4862 | // Creates a polymorphic matcher that matches a 2-tuple where the |
| 4863 | // first field <= the second field. |
| 4864 | inline internal::Le2Matcher Le() { return internal::Le2Matcher(); } |
| 4865 | |
| 4866 | // Creates a polymorphic matcher that matches a 2-tuple where the |
| 4867 | // first field < the second field. |
| 4868 | inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); } |
| 4869 | |
| 4870 | // Creates a polymorphic matcher that matches a 2-tuple where the |
| 4871 | // first field != the second field. |
| 4872 | inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); } |
| 4873 | |
| 4874 | // Creates a polymorphic matcher that matches a 2-tuple where |
| 4875 | // FloatEq(first field) matches the second field. |
| 4876 | inline internal::FloatingEq2Matcher<float> FloatEq() { |
| 4877 | return internal::FloatingEq2Matcher<float>(); |
| 4878 | } |
| 4879 | |
| 4880 | // Creates a polymorphic matcher that matches a 2-tuple where |
| 4881 | // DoubleEq(first field) matches the second field. |
| 4882 | inline internal::FloatingEq2Matcher<double> DoubleEq() { |
| 4883 | return internal::FloatingEq2Matcher<double>(); |
| 4884 | } |
| 4885 | |
| 4886 | // Creates a polymorphic matcher that matches a 2-tuple where |
| 4887 | // FloatEq(first field) matches the second field with NaN equality. |
| 4888 | inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() { |
| 4889 | return internal::FloatingEq2Matcher<float>(true); |
| 4890 | } |
| 4891 | |
| 4892 | // Creates a polymorphic matcher that matches a 2-tuple where |
| 4893 | // DoubleEq(first field) matches the second field with NaN equality. |
| 4894 | inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() { |
| 4895 | return internal::FloatingEq2Matcher<double>(true); |
| 4896 | } |
| 4897 | |
| 4898 | // Creates a polymorphic matcher that matches a 2-tuple where |
| 4899 | // FloatNear(first field, max_abs_error) matches the second field. |
| 4900 | inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) { |
| 4901 | return internal::FloatingEq2Matcher<float>(max_abs_error); |
| 4902 | } |
| 4903 | |
| 4904 | // Creates a polymorphic matcher that matches a 2-tuple where |
| 4905 | // DoubleNear(first field, max_abs_error) matches the second field. |
| 4906 | inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) { |
| 4907 | return internal::FloatingEq2Matcher<double>(max_abs_error); |
| 4908 | } |
| 4909 | |
| 4910 | // Creates a polymorphic matcher that matches a 2-tuple where |
| 4911 | // FloatNear(first field, max_abs_error) matches the second field with NaN |
| 4912 | // equality. |
| 4913 | inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear( |
| 4914 | float max_abs_error) { |
| 4915 | return internal::FloatingEq2Matcher<float>(max_abs_error, true); |
| 4916 | } |
| 4917 | |
| 4918 | // Creates a polymorphic matcher that matches a 2-tuple where |
| 4919 | // DoubleNear(first field, max_abs_error) matches the second field with NaN |
| 4920 | // equality. |
| 4921 | inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear( |
| 4922 | double max_abs_error) { |
| 4923 | return internal::FloatingEq2Matcher<double>(max_abs_error, true); |
| 4924 | } |
| 4925 | |
| 4926 | // Creates a matcher that matches any value of type T that m doesn't |
| 4927 | // match. |
| 4928 | template <typename InnerMatcher> |
| 4929 | inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) { |
| 4930 | return internal::NotMatcher<InnerMatcher>(m); |
| 4931 | } |
| 4932 | |
| 4933 | // Returns a matcher that matches anything that satisfies the given |
| 4934 | // predicate. The predicate can be any unary function or functor |
| 4935 | // whose return type can be implicitly converted to bool. |
| 4936 | template <typename Predicate> |
| 4937 | inline PolymorphicMatcher<internal::TrulyMatcher<Predicate>> Truly( |
| 4938 | Predicate pred) { |
| 4939 | return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred)); |
| 4940 | } |
| 4941 | |
| 4942 | // Returns a matcher that matches the container size. The container must |
| 4943 | // support both size() and size_type which all STL-like containers provide. |
| 4944 | // Note that the parameter 'size' can be a value of type size_type as well as |
| 4945 | // matcher. For instance: |
| 4946 | // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements. |
| 4947 | // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2. |
| 4948 | template <typename SizeMatcher> |
| 4949 | inline internal::SizeIsMatcher<SizeMatcher> SizeIs( |
| 4950 | const SizeMatcher& size_matcher) { |
| 4951 | return internal::SizeIsMatcher<SizeMatcher>(size_matcher); |
| 4952 | } |
| 4953 | |
| 4954 | // Returns a matcher that matches the distance between the container's begin() |
| 4955 | // iterator and its end() iterator, i.e. the size of the container. This matcher |
| 4956 | // can be used instead of SizeIs with containers such as std::forward_list which |
| 4957 | // do not implement size(). The container must provide const_iterator (with |
| 4958 | // valid iterator_traits), begin() and end(). |
| 4959 | template <typename DistanceMatcher> |
| 4960 | inline internal::BeginEndDistanceIsMatcher<DistanceMatcher> BeginEndDistanceIs( |
| 4961 | const DistanceMatcher& distance_matcher) { |
| 4962 | return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher); |
| 4963 | } |
| 4964 | |
| 4965 | // Returns a matcher that matches an equal container. |
| 4966 | // This matcher behaves like Eq(), but in the event of mismatch lists the |
| 4967 | // values that are included in one container but not the other. (Duplicate |
| 4968 | // values and order differences are not explained.) |
| 4969 | template <typename Container> |
| 4970 | inline PolymorphicMatcher< |
| 4971 | internal::ContainerEqMatcher<typename std::remove_const<Container>::type>> |
| 4972 | ContainerEq(const Container& rhs) { |
| 4973 | return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs)); |
| 4974 | } |
| 4975 | |
| 4976 | // Returns a matcher that matches a container that, when sorted using |
| 4977 | // the given comparator, matches container_matcher. |
| 4978 | template <typename Comparator, typename ContainerMatcher> |
| 4979 | inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher> WhenSortedBy( |
| 4980 | const Comparator& comparator, const ContainerMatcher& container_matcher) { |
| 4981 | return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>( |
| 4982 | comparator, container_matcher); |
| 4983 | } |
| 4984 | |
| 4985 | // Returns a matcher that matches a container that, when sorted using |
| 4986 | // the < operator, matches container_matcher. |
| 4987 | template <typename ContainerMatcher> |
| 4988 | inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher> |
| 4989 | WhenSorted(const ContainerMatcher& container_matcher) { |
| 4990 | return internal::WhenSortedByMatcher<internal::LessComparator, |
| 4991 | ContainerMatcher>( |
| 4992 | internal::LessComparator(), container_matcher); |
| 4993 | } |
| 4994 | |
| 4995 | // Matches an STL-style container or a native array that contains the |
| 4996 | // same number of elements as in rhs, where its i-th element and rhs's |
| 4997 | // i-th element (as a pair) satisfy the given pair matcher, for all i. |
| 4998 | // TupleMatcher must be able to be safely cast to Matcher<std::tuple<const |
| 4999 | // T1&, const T2&> >, where T1 and T2 are the types of elements in the |
| 5000 | // LHS container and the RHS container respectively. |
| 5001 | template <typename TupleMatcher, typename Container> |
| 5002 | inline internal::PointwiseMatcher<TupleMatcher, |
| 5003 | typename std::remove_const<Container>::type> |
| 5004 | Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) { |
| 5005 | return internal::PointwiseMatcher<TupleMatcher, Container>(tuple_matcher, |
| 5006 | rhs); |
| 5007 | } |
| 5008 | |
| 5009 | // Supports the Pointwise(m, {a, b, c}) syntax. |
| 5010 | template <typename TupleMatcher, typename T> |
| 5011 | inline internal::PointwiseMatcher<TupleMatcher, |
| 5012 | std::vector<std::remove_const_t<T>>> |
| 5013 | Pointwise(const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) { |
| 5014 | return Pointwise(tuple_matcher, std::vector<std::remove_const_t<T>>(rhs)); |
| 5015 | } |
| 5016 | |
| 5017 | // UnorderedPointwise(pair_matcher, rhs) matches an STL-style |
| 5018 | // container or a native array that contains the same number of |
| 5019 | // elements as in rhs, where in some permutation of the container, its |
| 5020 | // i-th element and rhs's i-th element (as a pair) satisfy the given |
| 5021 | // pair matcher, for all i. Tuple2Matcher must be able to be safely |
| 5022 | // cast to Matcher<std::tuple<const T1&, const T2&> >, where T1 and T2 are |
| 5023 | // the types of elements in the LHS container and the RHS container |
| 5024 | // respectively. |
| 5025 | // |
| 5026 | // This is like Pointwise(pair_matcher, rhs), except that the element |
| 5027 | // order doesn't matter. |
| 5028 | template <typename Tuple2Matcher, typename RhsContainer> |
| 5029 | inline internal::UnorderedElementsAreArrayMatcher< |
| 5030 | typename internal::BoundSecondMatcher< |
| 5031 | Tuple2Matcher, |
| 5032 | typename internal::StlContainerView< |
| 5033 | typename std::remove_const<RhsContainer>::type>::type::value_type>> |
| 5034 | UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, |
| 5035 | const RhsContainer& rhs_container) { |
| 5036 | // RhsView allows the same code to handle RhsContainer being a |
| 5037 | // STL-style container and it being a native C-style array. |
| 5038 | typedef typename internal::StlContainerView<RhsContainer> RhsView; |
| 5039 | typedef typename RhsView::type RhsStlContainer; |
| 5040 | typedef typename RhsStlContainer::value_type Second; |
| 5041 | const RhsStlContainer& rhs_stl_container = |
| 5042 | RhsView::ConstReference(rhs_container); |
| 5043 | |
| 5044 | // Create a matcher for each element in rhs_container. |
| 5045 | ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second>> matchers; |
| 5046 | for (auto it = rhs_stl_container.begin(); it != rhs_stl_container.end(); |
| 5047 | ++it) { |
| 5048 | matchers.push_back(internal::MatcherBindSecond(tuple2_matcher, *it)); |
| 5049 | } |
| 5050 | |
| 5051 | // Delegate the work to UnorderedElementsAreArray(). |
| 5052 | return UnorderedElementsAreArray(matchers); |
| 5053 | } |
| 5054 | |
| 5055 | // Supports the UnorderedPointwise(m, {a, b, c}) syntax. |
| 5056 | template <typename Tuple2Matcher, typename T> |
| 5057 | inline internal::UnorderedElementsAreArrayMatcher< |
| 5058 | typename internal::BoundSecondMatcher<Tuple2Matcher, T>> |
| 5059 | UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, |
| 5060 | std::initializer_list<T> rhs) { |
| 5061 | return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs)); |
| 5062 | } |
| 5063 | |
| 5064 | // Matches an STL-style container or a native array that contains at |
| 5065 | // least one element matching the given value or matcher. |
| 5066 | // |
| 5067 | // Examples: |
| 5068 | // ::std::set<int> page_ids; |
| 5069 | // page_ids.insert(3); |
| 5070 | // page_ids.insert(1); |
| 5071 | // EXPECT_THAT(page_ids, Contains(1)); |
| 5072 | // EXPECT_THAT(page_ids, Contains(Gt(2))); |
| 5073 | // EXPECT_THAT(page_ids, Not(Contains(4))); // See below for Times(0) |
| 5074 | // |
| 5075 | // ::std::map<int, size_t> page_lengths; |
| 5076 | // page_lengths[1] = 100; |
| 5077 | // EXPECT_THAT(page_lengths, |
| 5078 | // Contains(::std::pair<const int, size_t>(1, 100))); |
| 5079 | // |
| 5080 | // const char* user_ids[] = { "joe", "mike", "tom" }; |
| 5081 | // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom")))); |
| 5082 | // |
| 5083 | // The matcher supports a modifier `Times` that allows to check for arbitrary |
| 5084 | // occurrences including testing for absence with Times(0). |
| 5085 | // |
| 5086 | // Examples: |
| 5087 | // ::std::vector<int> ids; |
| 5088 | // ids.insert(1); |
| 5089 | // ids.insert(1); |
| 5090 | // ids.insert(3); |
| 5091 | // EXPECT_THAT(ids, Contains(1).Times(2)); // 1 occurs 2 times |
| 5092 | // EXPECT_THAT(ids, Contains(2).Times(0)); // 2 is not present |
| 5093 | // EXPECT_THAT(ids, Contains(3).Times(Ge(1))); // 3 occurs at least once |
| 5094 | |
| 5095 | template <typename M> |
| 5096 | inline internal::ContainsMatcher<M> Contains(M matcher) { |
| 5097 | return internal::ContainsMatcher<M>(matcher); |
| 5098 | } |
| 5099 | |
| 5100 | // IsSupersetOf(iterator_first, iterator_last) |
| 5101 | // IsSupersetOf(pointer, count) |
| 5102 | // IsSupersetOf(array) |
| 5103 | // IsSupersetOf(container) |
| 5104 | // IsSupersetOf({e1, e2, ..., en}) |
| 5105 | // |
| 5106 | // IsSupersetOf() verifies that a surjective partial mapping onto a collection |
| 5107 | // of matchers exists. In other words, a container matches |
| 5108 | // IsSupersetOf({e1, ..., en}) if and only if there is a permutation |
| 5109 | // {y1, ..., yn} of some of the container's elements where y1 matches e1, |
| 5110 | // ..., and yn matches en. Obviously, the size of the container must be >= n |
| 5111 | // in order to have a match. Examples: |
| 5112 | // |
| 5113 | // - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and |
| 5114 | // 1 matches Ne(0). |
| 5115 | // - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches |
| 5116 | // both Eq(1) and Lt(2). The reason is that different matchers must be used |
| 5117 | // for elements in different slots of the container. |
| 5118 | // - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches |
| 5119 | // Eq(1) and (the second) 1 matches Lt(2). |
| 5120 | // - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first) |
| 5121 | // Gt(1) and 3 matches (the second) Gt(1). |
| 5122 | // |
| 5123 | // The matchers can be specified as an array, a pointer and count, a container, |
| 5124 | // an initializer list, or an STL iterator range. In each of these cases, the |
| 5125 | // underlying matchers can be either values or matchers. |
| 5126 | |
| 5127 | template <typename Iter> |
| 5128 | inline internal::UnorderedElementsAreArrayMatcher< |
| 5129 | typename ::std::iterator_traits<Iter>::value_type> |
| 5130 | IsSupersetOf(Iter first, Iter last) { |
| 5131 | typedef typename ::std::iterator_traits<Iter>::value_type T; |
| 5132 | return internal::UnorderedElementsAreArrayMatcher<T>( |
| 5133 | internal::UnorderedMatcherRequire::Superset, first, last); |
| 5134 | } |
| 5135 | |
| 5136 | template <typename T> |
| 5137 | inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf( |
| 5138 | const T* pointer, size_t count) { |
| 5139 | return IsSupersetOf(pointer, pointer + count); |
| 5140 | } |
| 5141 | |
| 5142 | template <typename T, size_t N> |
| 5143 | inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf( |
| 5144 | const T (&array)[N]) { |
| 5145 | return IsSupersetOf(array, N); |
| 5146 | } |
| 5147 | |
| 5148 | template <typename Container> |
| 5149 | inline internal::UnorderedElementsAreArrayMatcher< |
| 5150 | typename Container::value_type> |
| 5151 | IsSupersetOf(const Container& container) { |
| 5152 | return IsSupersetOf(container.begin(), container.end()); |
| 5153 | } |
| 5154 | |
| 5155 | template <typename T> |
| 5156 | inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf( |
| 5157 | ::std::initializer_list<T> xs) { |
| 5158 | return IsSupersetOf(xs.begin(), xs.end()); |
| 5159 | } |
| 5160 | |
| 5161 | // IsSubsetOf(iterator_first, iterator_last) |
| 5162 | // IsSubsetOf(pointer, count) |
| 5163 | // IsSubsetOf(array) |
| 5164 | // IsSubsetOf(container) |
| 5165 | // IsSubsetOf({e1, e2, ..., en}) |
| 5166 | // |
| 5167 | // IsSubsetOf() verifies that an injective mapping onto a collection of matchers |
| 5168 | // exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and |
| 5169 | // only if there is a subset of matchers {m1, ..., mk} which would match the |
| 5170 | // container using UnorderedElementsAre. Obviously, the size of the container |
| 5171 | // must be <= n in order to have a match. Examples: |
| 5172 | // |
| 5173 | // - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0). |
| 5174 | // - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1 |
| 5175 | // matches Lt(0). |
| 5176 | // - {1, 2} doesn't match IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both |
| 5177 | // match Gt(0). The reason is that different matchers must be used for |
| 5178 | // elements in different slots of the container. |
| 5179 | // |
| 5180 | // The matchers can be specified as an array, a pointer and count, a container, |
| 5181 | // an initializer list, or an STL iterator range. In each of these cases, the |
| 5182 | // underlying matchers can be either values or matchers. |
| 5183 | |
| 5184 | template <typename Iter> |
| 5185 | inline internal::UnorderedElementsAreArrayMatcher< |
| 5186 | typename ::std::iterator_traits<Iter>::value_type> |
| 5187 | IsSubsetOf(Iter first, Iter last) { |
| 5188 | typedef typename ::std::iterator_traits<Iter>::value_type T; |
| 5189 | return internal::UnorderedElementsAreArrayMatcher<T>( |
| 5190 | internal::UnorderedMatcherRequire::Subset, first, last); |
| 5191 | } |
| 5192 | |
| 5193 | template <typename T> |
| 5194 | inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf( |
| 5195 | const T* pointer, size_t count) { |
| 5196 | return IsSubsetOf(pointer, pointer + count); |
| 5197 | } |
| 5198 | |
| 5199 | template <typename T, size_t N> |
| 5200 | inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf( |
| 5201 | const T (&array)[N]) { |
| 5202 | return IsSubsetOf(array, N); |
| 5203 | } |
| 5204 | |
| 5205 | template <typename Container> |
| 5206 | inline internal::UnorderedElementsAreArrayMatcher< |
| 5207 | typename Container::value_type> |
| 5208 | IsSubsetOf(const Container& container) { |
| 5209 | return IsSubsetOf(container.begin(), container.end()); |
| 5210 | } |
| 5211 | |
| 5212 | template <typename T> |
| 5213 | inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf( |
| 5214 | ::std::initializer_list<T> xs) { |
| 5215 | return IsSubsetOf(xs.begin(), xs.end()); |
| 5216 | } |
| 5217 | |
| 5218 | // Matches an STL-style container or a native array that contains only |
| 5219 | // elements matching the given value or matcher. |
| 5220 | // |
| 5221 | // Each(m) is semantically equivalent to `Not(Contains(Not(m)))`. Only |
| 5222 | // the messages are different. |
| 5223 | // |
| 5224 | // Examples: |
| 5225 | // ::std::set<int> page_ids; |
| 5226 | // // Each(m) matches an empty container, regardless of what m is. |
| 5227 | // EXPECT_THAT(page_ids, Each(Eq(1))); |
| 5228 | // EXPECT_THAT(page_ids, Each(Eq(77))); |
| 5229 | // |
| 5230 | // page_ids.insert(3); |
| 5231 | // EXPECT_THAT(page_ids, Each(Gt(0))); |
| 5232 | // EXPECT_THAT(page_ids, Not(Each(Gt(4)))); |
| 5233 | // page_ids.insert(1); |
| 5234 | // EXPECT_THAT(page_ids, Not(Each(Lt(2)))); |
| 5235 | // |
| 5236 | // ::std::map<int, size_t> page_lengths; |
| 5237 | // page_lengths[1] = 100; |
| 5238 | // page_lengths[2] = 200; |
| 5239 | // page_lengths[3] = 300; |
| 5240 | // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100)))); |
| 5241 | // EXPECT_THAT(page_lengths, Each(Key(Le(3)))); |
| 5242 | // |
| 5243 | // const char* user_ids[] = { "joe", "mike", "tom" }; |
| 5244 | // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom"))))); |
| 5245 | template <typename M> |
| 5246 | inline internal::EachMatcher<M> Each(M matcher) { |
| 5247 | return internal::EachMatcher<M>(matcher); |
| 5248 | } |
| 5249 | |
| 5250 | // Key(inner_matcher) matches an std::pair whose 'first' field matches |
| 5251 | // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an |
| 5252 | // std::map that contains at least one element whose key is >= 5. |
| 5253 | template <typename M> |
| 5254 | inline internal::KeyMatcher<M> Key(M inner_matcher) { |
| 5255 | return internal::KeyMatcher<M>(inner_matcher); |
| 5256 | } |
| 5257 | |
| 5258 | // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field |
| 5259 | // matches first_matcher and whose 'second' field matches second_matcher. For |
| 5260 | // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used |
| 5261 | // to match a std::map<int, string> that contains exactly one element whose key |
| 5262 | // is >= 5 and whose value equals "foo". |
| 5263 | template <typename FirstMatcher, typename SecondMatcher> |
| 5264 | inline internal::PairMatcher<FirstMatcher, SecondMatcher> Pair( |
| 5265 | FirstMatcher first_matcher, SecondMatcher second_matcher) { |
| 5266 | return internal::PairMatcher<FirstMatcher, SecondMatcher>(first_matcher, |
| 5267 | second_matcher); |
| 5268 | } |
| 5269 | |
| 5270 | namespace no_adl { |
| 5271 | // Conditional() creates a matcher that conditionally uses either the first or |
| 5272 | // second matcher provided. For example, we could create an `equal if, and only |
| 5273 | // if' matcher using the Conditional wrapper as follows: |
| 5274 | // |
| 5275 | // EXPECT_THAT(result, Conditional(condition, Eq(expected), Ne(expected))); |
| 5276 | template <typename MatcherTrue, typename MatcherFalse> |
| 5277 | internal::ConditionalMatcher<MatcherTrue, MatcherFalse> Conditional( |
| 5278 | bool condition, MatcherTrue matcher_true, MatcherFalse matcher_false) { |
| 5279 | return internal::ConditionalMatcher<MatcherTrue, MatcherFalse>( |
| 5280 | condition, std::move(matcher_true), std::move(matcher_false)); |
| 5281 | } |
| 5282 | |
| 5283 | // FieldsAre(matchers...) matches piecewise the fields of compatible structs. |
| 5284 | // These include those that support `get<I>(obj)`, and when structured bindings |
| 5285 | // are enabled any class that supports them. |
| 5286 | // In particular, `std::tuple`, `std::pair`, `std::array` and aggregate types. |
| 5287 | template <typename... M> |
| 5288 | internal::FieldsAreMatcher<typename std::decay<M>::type...> FieldsAre( |
| 5289 | M&&... matchers) { |
| 5290 | return internal::FieldsAreMatcher<typename std::decay<M>::type...>( |
| 5291 | std::forward<M>(matchers)...); |
| 5292 | } |
| 5293 | |
| 5294 | // Creates a matcher that matches a pointer (raw or smart) that matches |
| 5295 | // inner_matcher. |
| 5296 | template <typename InnerMatcher> |
| 5297 | inline internal::PointerMatcher<InnerMatcher> Pointer( |
| 5298 | const InnerMatcher& inner_matcher) { |
| 5299 | return internal::PointerMatcher<InnerMatcher>(inner_matcher); |
| 5300 | } |
| 5301 | |
| 5302 | // Creates a matcher that matches an object that has an address that matches |
| 5303 | // inner_matcher. |
| 5304 | template <typename InnerMatcher> |
| 5305 | inline internal::AddressMatcher<InnerMatcher> Address( |
| 5306 | const InnerMatcher& inner_matcher) { |
| 5307 | return internal::AddressMatcher<InnerMatcher>(inner_matcher); |
| 5308 | } |
| 5309 | |
| 5310 | // Matches a base64 escaped string, when the unescaped string matches the |
| 5311 | // internal matcher. |
| 5312 | template <typename MatcherType> |
| 5313 | internal::WhenBase64UnescapedMatcher WhenBase64Unescaped( |
| 5314 | const MatcherType& internal_matcher) { |
| 5315 | return internal::WhenBase64UnescapedMatcher(internal_matcher); |
| 5316 | } |
| 5317 | } // namespace no_adl |
| 5318 | |
| 5319 | // Returns a predicate that is satisfied by anything that matches the |
| 5320 | // given matcher. |
| 5321 | template <typename M> |
| 5322 | inline internal::MatcherAsPredicate<M> Matches(M matcher) { |
| 5323 | return internal::MatcherAsPredicate<M>(matcher); |
| 5324 | } |
| 5325 | |
| 5326 | // Returns true if and only if the value matches the matcher. |
| 5327 | template <typename T, typename M> |
| 5328 | inline bool Value(const T& value, M matcher) { |
| 5329 | return testing::Matches(matcher)(value); |
| 5330 | } |
| 5331 | |
| 5332 | // Matches the value against the given matcher and explains the match |
| 5333 | // result to listener. |
| 5334 | template <typename T, typename M> |
| 5335 | inline bool ExplainMatchResult(M matcher, const T& value, |
| 5336 | MatchResultListener* listener) { |
| 5337 | return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener); |
| 5338 | } |
| 5339 | |
| 5340 | // Returns a string representation of the given matcher. Useful for description |
| 5341 | // strings of matchers defined using MATCHER_P* macros that accept matchers as |
| 5342 | // their arguments. For example: |
| 5343 | // |
| 5344 | // MATCHER_P(XAndYThat, matcher, |
| 5345 | // "X that " + DescribeMatcher<int>(matcher, negation) + |
| 5346 | // (negation ? " or" : " and") + " Y that " + |
| 5347 | // DescribeMatcher<double>(matcher, negation)) { |
| 5348 | // return ExplainMatchResult(matcher, arg.x(), result_listener) && |
| 5349 | // ExplainMatchResult(matcher, arg.y(), result_listener); |
| 5350 | // } |
| 5351 | template <typename T, typename M> |
| 5352 | std::string DescribeMatcher(const M& matcher, bool negation = false) { |
| 5353 | ::std::stringstream ss; |
| 5354 | Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher); |
| 5355 | if (negation) { |
| 5356 | monomorphic_matcher.DescribeNegationTo(&ss); |
| 5357 | } else { |
| 5358 | monomorphic_matcher.DescribeTo(&ss); |
| 5359 | } |
| 5360 | return ss.str(); |
| 5361 | } |
| 5362 | |
| 5363 | template <typename... Args> |
| 5364 | internal::ElementsAreMatcher< |
| 5365 | std::tuple<typename std::decay<const Args&>::type...>> |
| 5366 | ElementsAre(const Args&... matchers) { |
| 5367 | return internal::ElementsAreMatcher< |
| 5368 | std::tuple<typename std::decay<const Args&>::type...>>( |
| 5369 | std::make_tuple(matchers...)); |
| 5370 | } |
| 5371 | |
| 5372 | template <typename... Args> |
| 5373 | internal::UnorderedElementsAreMatcher< |
| 5374 | std::tuple<typename std::decay<const Args&>::type...>> |
| 5375 | UnorderedElementsAre(const Args&... matchers) { |
| 5376 | return internal::UnorderedElementsAreMatcher< |
| 5377 | std::tuple<typename std::decay<const Args&>::type...>>( |
| 5378 | std::make_tuple(matchers...)); |
| 5379 | } |
| 5380 | |
| 5381 | // Define variadic matcher versions. |
| 5382 | template <typename... Args> |
| 5383 | internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf( |
| 5384 | const Args&... matchers) { |
| 5385 | return internal::AllOfMatcher<typename std::decay<const Args&>::type...>( |
| 5386 | matchers...); |
| 5387 | } |
| 5388 | |
| 5389 | template <typename... Args> |
| 5390 | internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf( |
| 5391 | const Args&... matchers) { |
| 5392 | return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>( |
| 5393 | matchers...); |
| 5394 | } |
| 5395 | |
| 5396 | // AnyOfArray(array) |
| 5397 | // AnyOfArray(pointer, count) |
| 5398 | // AnyOfArray(container) |
| 5399 | // AnyOfArray({ e1, e2, ..., en }) |
| 5400 | // AnyOfArray(iterator_first, iterator_last) |
| 5401 | // |
| 5402 | // AnyOfArray() verifies whether a given value matches any member of a |
| 5403 | // collection of matchers. |
| 5404 | // |
| 5405 | // AllOfArray(array) |
| 5406 | // AllOfArray(pointer, count) |
| 5407 | // AllOfArray(container) |
| 5408 | // AllOfArray({ e1, e2, ..., en }) |
| 5409 | // AllOfArray(iterator_first, iterator_last) |
| 5410 | // |
| 5411 | // AllOfArray() verifies whether a given value matches all members of a |
| 5412 | // collection of matchers. |
| 5413 | // |
| 5414 | // The matchers can be specified as an array, a pointer and count, a container, |
| 5415 | // an initializer list, or an STL iterator range. In each of these cases, the |
| 5416 | // underlying matchers can be either values or matchers. |
| 5417 | |
| 5418 | template <typename Iter> |
| 5419 | inline internal::AnyOfArrayMatcher< |
| 5420 | typename ::std::iterator_traits<Iter>::value_type> |
| 5421 | AnyOfArray(Iter first, Iter last) { |
| 5422 | return internal::AnyOfArrayMatcher< |
| 5423 | typename ::std::iterator_traits<Iter>::value_type>(first, last); |
| 5424 | } |
| 5425 | |
| 5426 | template <typename Iter> |
| 5427 | inline internal::AllOfArrayMatcher< |
| 5428 | typename ::std::iterator_traits<Iter>::value_type> |
| 5429 | AllOfArray(Iter first, Iter last) { |
| 5430 | return internal::AllOfArrayMatcher< |
| 5431 | typename ::std::iterator_traits<Iter>::value_type>(first, last); |
| 5432 | } |
| 5433 | |
| 5434 | template <typename T> |
| 5435 | inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T* ptr, size_t count) { |
| 5436 | return AnyOfArray(ptr, ptr + count); |
| 5437 | } |
| 5438 | |
| 5439 | template <typename T> |
| 5440 | inline internal::AllOfArrayMatcher<T> AllOfArray(const T* ptr, size_t count) { |
| 5441 | return AllOfArray(ptr, ptr + count); |
| 5442 | } |
| 5443 | |
| 5444 | template <typename T, size_t N> |
| 5445 | inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T (&array)[N]) { |
| 5446 | return AnyOfArray(array, N); |
| 5447 | } |
| 5448 | |
| 5449 | template <typename T, size_t N> |
| 5450 | inline internal::AllOfArrayMatcher<T> AllOfArray(const T (&array)[N]) { |
| 5451 | return AllOfArray(array, N); |
| 5452 | } |
| 5453 | |
| 5454 | template <typename Container> |
| 5455 | inline internal::AnyOfArrayMatcher<typename Container::value_type> AnyOfArray( |
| 5456 | const Container& container) { |
| 5457 | return AnyOfArray(container.begin(), container.end()); |
| 5458 | } |
| 5459 | |
| 5460 | template <typename Container> |
| 5461 | inline internal::AllOfArrayMatcher<typename Container::value_type> AllOfArray( |
| 5462 | const Container& container) { |
| 5463 | return AllOfArray(container.begin(), container.end()); |
| 5464 | } |
| 5465 | |
| 5466 | template <typename T> |
| 5467 | inline internal::AnyOfArrayMatcher<T> AnyOfArray( |
| 5468 | ::std::initializer_list<T> xs) { |
| 5469 | return AnyOfArray(xs.begin(), xs.end()); |
| 5470 | } |
| 5471 | |
| 5472 | template <typename T> |
| 5473 | inline internal::AllOfArrayMatcher<T> AllOfArray( |
| 5474 | ::std::initializer_list<T> xs) { |
| 5475 | return AllOfArray(xs.begin(), xs.end()); |
| 5476 | } |
| 5477 | |
| 5478 | // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected |
| 5479 | // fields of it matches a_matcher. C++ doesn't support default |
| 5480 | // arguments for function templates, so we have to overload it. |
| 5481 | template <size_t... k, typename InnerMatcher> |
| 5482 | internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...> Args( |
| 5483 | InnerMatcher&& matcher) { |
| 5484 | return internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...>( |
| 5485 | std::forward<InnerMatcher>(matcher)); |
| 5486 | } |
| 5487 | |
| 5488 | // AllArgs(m) is a synonym of m. This is useful in |
| 5489 | // |
| 5490 | // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq())); |
| 5491 | // |
| 5492 | // which is easier to read than |
| 5493 | // |
| 5494 | // EXPECT_CALL(foo, Bar(_, _)).With(Eq()); |
| 5495 | template <typename InnerMatcher> |
| 5496 | inline InnerMatcher AllArgs(const InnerMatcher& matcher) { |
| 5497 | return matcher; |
| 5498 | } |
| 5499 | |
| 5500 | // Returns a matcher that matches the value of an optional<> type variable. |
| 5501 | // The matcher implementation only uses '!arg' (or 'arg.has_value()' if '!arg` |
| 5502 | // isn't a valid expression) and requires that the optional<> type has a |
| 5503 | // 'value_type' member type and that '*arg' is of type 'value_type' and is |
| 5504 | // printable using 'PrintToString'. It is compatible with |
| 5505 | // std::optional/std::experimental::optional. |
| 5506 | // Note that to compare an optional type variable against nullopt you should |
| 5507 | // use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the |
| 5508 | // optional value contains an optional itself. |
| 5509 | template <typename ValueMatcher> |
| 5510 | inline internal::OptionalMatcher<ValueMatcher> Optional( |
| 5511 | const ValueMatcher& value_matcher) { |
| 5512 | return internal::OptionalMatcher<ValueMatcher>(value_matcher); |
| 5513 | } |
| 5514 | |
| 5515 | // Returns a matcher that matches the value of a absl::any type variable. |
| 5516 | template <typename T> |
| 5517 | PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T>> AnyWith( |
| 5518 | const Matcher<const T&>& matcher) { |
| 5519 | return MakePolymorphicMatcher( |
| 5520 | internal::any_cast_matcher::AnyCastMatcher<T>(matcher)); |
| 5521 | } |
| 5522 | |
| 5523 | // Returns a matcher that matches the value of a variant<> type variable. |
| 5524 | // The matcher implementation uses ADL to find the holds_alternative and get |
| 5525 | // functions. |
| 5526 | // It is compatible with std::variant. |
| 5527 | template <typename T> |
| 5528 | PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T>> VariantWith( |
| 5529 | const Matcher<const T&>& matcher) { |
| 5530 | return MakePolymorphicMatcher( |
| 5531 | internal::variant_matcher::VariantMatcher<T>(matcher)); |
| 5532 | } |
| 5533 | |
| 5534 | #if GTEST_HAS_EXCEPTIONS |
| 5535 | |
| 5536 | // Anything inside the `internal` namespace is internal to the implementation |
| 5537 | // and must not be used in user code! |
| 5538 | namespace internal { |
| 5539 | |
| 5540 | class WithWhatMatcherImpl { |
| 5541 | public: |
| 5542 | WithWhatMatcherImpl(Matcher<std::string> matcher) |
| 5543 | : matcher_(std::move(matcher)) {} |
| 5544 | |
| 5545 | void DescribeTo(std::ostream* os) const { |
| 5546 | *os << "contains .what() that " ; |
| 5547 | matcher_.DescribeTo(os); |
| 5548 | } |
| 5549 | |
| 5550 | void DescribeNegationTo(std::ostream* os) const { |
| 5551 | *os << "contains .what() that does not " ; |
| 5552 | matcher_.DescribeTo(os); |
| 5553 | } |
| 5554 | |
| 5555 | template <typename Err> |
| 5556 | bool MatchAndExplain(const Err& err, MatchResultListener* listener) const { |
| 5557 | *listener << "which contains .what() (of value = " << err.what() |
| 5558 | << ") that " ; |
| 5559 | return matcher_.MatchAndExplain(err.what(), listener); |
| 5560 | } |
| 5561 | |
| 5562 | private: |
| 5563 | const Matcher<std::string> matcher_; |
| 5564 | }; |
| 5565 | |
| 5566 | inline PolymorphicMatcher<WithWhatMatcherImpl> WithWhat( |
| 5567 | Matcher<std::string> m) { |
| 5568 | return MakePolymorphicMatcher(WithWhatMatcherImpl(std::move(m))); |
| 5569 | } |
| 5570 | |
| 5571 | template <typename Err> |
| 5572 | class ExceptionMatcherImpl { |
| 5573 | class NeverThrown { |
| 5574 | public: |
| 5575 | const char* what() const noexcept { |
| 5576 | return "this exception should never be thrown" ; |
| 5577 | } |
| 5578 | }; |
| 5579 | |
| 5580 | // If the matchee raises an exception of a wrong type, we'd like to |
| 5581 | // catch it and print its message and type. To do that, we add an additional |
| 5582 | // catch clause: |
| 5583 | // |
| 5584 | // try { ... } |
| 5585 | // catch (const Err&) { /* an expected exception */ } |
| 5586 | // catch (const std::exception&) { /* exception of a wrong type */ } |
| 5587 | // |
| 5588 | // However, if the `Err` itself is `std::exception`, we'd end up with two |
| 5589 | // identical `catch` clauses: |
| 5590 | // |
| 5591 | // try { ... } |
| 5592 | // catch (const std::exception&) { /* an expected exception */ } |
| 5593 | // catch (const std::exception&) { /* exception of a wrong type */ } |
| 5594 | // |
| 5595 | // This can cause a warning or an error in some compilers. To resolve |
| 5596 | // the issue, we use a fake error type whenever `Err` is `std::exception`: |
| 5597 | // |
| 5598 | // try { ... } |
| 5599 | // catch (const std::exception&) { /* an expected exception */ } |
| 5600 | // catch (const NeverThrown&) { /* exception of a wrong type */ } |
| 5601 | using DefaultExceptionType = typename std::conditional< |
| 5602 | std::is_same<typename std::remove_cv< |
| 5603 | typename std::remove_reference<Err>::type>::type, |
| 5604 | std::exception>::value, |
| 5605 | const NeverThrown&, const std::exception&>::type; |
| 5606 | |
| 5607 | public: |
| 5608 | ExceptionMatcherImpl(Matcher<const Err&> matcher) |
| 5609 | : matcher_(std::move(matcher)) {} |
| 5610 | |
| 5611 | void DescribeTo(std::ostream* os) const { |
| 5612 | *os << "throws an exception which is a " << GetTypeName<Err>(); |
| 5613 | *os << " which " ; |
| 5614 | matcher_.DescribeTo(os); |
| 5615 | } |
| 5616 | |
| 5617 | void DescribeNegationTo(std::ostream* os) const { |
| 5618 | *os << "throws an exception which is not a " << GetTypeName<Err>(); |
| 5619 | *os << " which " ; |
| 5620 | matcher_.DescribeNegationTo(os); |
| 5621 | } |
| 5622 | |
| 5623 | template <typename T> |
| 5624 | bool MatchAndExplain(T&& x, MatchResultListener* listener) const { |
| 5625 | try { |
| 5626 | (void)(std::forward<T>(x)()); |
| 5627 | } catch (const Err& err) { |
| 5628 | *listener << "throws an exception which is a " << GetTypeName<Err>(); |
| 5629 | *listener << " " ; |
| 5630 | return matcher_.MatchAndExplain(err, listener); |
| 5631 | } catch (DefaultExceptionType err) { |
| 5632 | #if GTEST_HAS_RTTI |
| 5633 | *listener << "throws an exception of type " << GetTypeName(typeid(err)); |
| 5634 | *listener << " " ; |
| 5635 | #else |
| 5636 | *listener << "throws an std::exception-derived type " ; |
| 5637 | #endif |
| 5638 | *listener << "with description \"" << err.what() << "\"" ; |
| 5639 | return false; |
| 5640 | } catch (...) { |
| 5641 | *listener << "throws an exception of an unknown type" ; |
| 5642 | return false; |
| 5643 | } |
| 5644 | |
| 5645 | *listener << "does not throw any exception" ; |
| 5646 | return false; |
| 5647 | } |
| 5648 | |
| 5649 | private: |
| 5650 | const Matcher<const Err&> matcher_; |
| 5651 | }; |
| 5652 | |
| 5653 | } // namespace internal |
| 5654 | |
| 5655 | // Throws() |
| 5656 | // Throws(exceptionMatcher) |
| 5657 | // ThrowsMessage(messageMatcher) |
| 5658 | // |
| 5659 | // This matcher accepts a callable and verifies that when invoked, it throws |
| 5660 | // an exception with the given type and properties. |
| 5661 | // |
| 5662 | // Examples: |
| 5663 | // |
| 5664 | // EXPECT_THAT( |
| 5665 | // []() { throw std::runtime_error("message"); }, |
| 5666 | // Throws<std::runtime_error>()); |
| 5667 | // |
| 5668 | // EXPECT_THAT( |
| 5669 | // []() { throw std::runtime_error("message"); }, |
| 5670 | // ThrowsMessage<std::runtime_error>(HasSubstr("message"))); |
| 5671 | // |
| 5672 | // EXPECT_THAT( |
| 5673 | // []() { throw std::runtime_error("message"); }, |
| 5674 | // Throws<std::runtime_error>( |
| 5675 | // Property(&std::runtime_error::what, HasSubstr("message")))); |
| 5676 | |
| 5677 | template <typename Err> |
| 5678 | PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws() { |
| 5679 | return MakePolymorphicMatcher( |
| 5680 | internal::ExceptionMatcherImpl<Err>(A<const Err&>())); |
| 5681 | } |
| 5682 | |
| 5683 | template <typename Err, typename ExceptionMatcher> |
| 5684 | PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws( |
| 5685 | const ExceptionMatcher& exception_matcher) { |
| 5686 | // Using matcher cast allows users to pass a matcher of a more broad type. |
| 5687 | // For example user may want to pass Matcher<std::exception> |
| 5688 | // to Throws<std::runtime_error>, or Matcher<int64> to Throws<int32>. |
| 5689 | return MakePolymorphicMatcher(internal::ExceptionMatcherImpl<Err>( |
| 5690 | SafeMatcherCast<const Err&>(exception_matcher))); |
| 5691 | } |
| 5692 | |
| 5693 | template <typename Err, typename MessageMatcher> |
| 5694 | PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage( |
| 5695 | MessageMatcher&& message_matcher) { |
| 5696 | static_assert(std::is_base_of<std::exception, Err>::value, |
| 5697 | "expected an std::exception-derived type" ); |
| 5698 | return Throws<Err>(internal::WithWhat( |
| 5699 | MatcherCast<std::string>(std::forward<MessageMatcher>(message_matcher)))); |
| 5700 | } |
| 5701 | |
| 5702 | #endif // GTEST_HAS_EXCEPTIONS |
| 5703 | |
| 5704 | // These macros allow using matchers to check values in Google Test |
| 5705 | // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher) |
| 5706 | // succeed if and only if the value matches the matcher. If the assertion |
| 5707 | // fails, the value and the description of the matcher will be printed. |
| 5708 | #define ASSERT_THAT(value, matcher) \ |
| 5709 | ASSERT_PRED_FORMAT1( \ |
| 5710 | ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) |
| 5711 | #define EXPECT_THAT(value, matcher) \ |
| 5712 | EXPECT_PRED_FORMAT1( \ |
| 5713 | ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) |
| 5714 | |
| 5715 | // MATCHER* macros itself are listed below. |
| 5716 | #define MATCHER(name, description) \ |
| 5717 | class name##Matcher \ |
| 5718 | : public ::testing::internal::MatcherBaseImpl<name##Matcher> { \ |
| 5719 | public: \ |
| 5720 | template <typename arg_type> \ |
| 5721 | class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \ |
| 5722 | public: \ |
| 5723 | gmock_Impl() {} \ |
| 5724 | bool MatchAndExplain( \ |
| 5725 | const arg_type& arg, \ |
| 5726 | ::testing::MatchResultListener* result_listener) const override; \ |
| 5727 | void DescribeTo(::std::ostream* gmock_os) const override { \ |
| 5728 | *gmock_os << FormatDescription(false); \ |
| 5729 | } \ |
| 5730 | void DescribeNegationTo(::std::ostream* gmock_os) const override { \ |
| 5731 | *gmock_os << FormatDescription(true); \ |
| 5732 | } \ |
| 5733 | \ |
| 5734 | private: \ |
| 5735 | ::std::string FormatDescription(bool negation) const { \ |
| 5736 | /* NOLINTNEXTLINE readability-redundant-string-init */ \ |
| 5737 | ::std::string gmock_description = (description); \ |
| 5738 | if (!gmock_description.empty()) { \ |
| 5739 | return gmock_description; \ |
| 5740 | } \ |
| 5741 | return ::testing::internal::FormatMatcherDescription(negation, #name, \ |
| 5742 | {}, {}); \ |
| 5743 | } \ |
| 5744 | }; \ |
| 5745 | }; \ |
| 5746 | inline name##Matcher GMOCK_INTERNAL_WARNING_PUSH() \ |
| 5747 | GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-function") \ |
| 5748 | GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \ |
| 5749 | name GMOCK_INTERNAL_WARNING_POP()() { \ |
| 5750 | return {}; \ |
| 5751 | } \ |
| 5752 | template <typename arg_type> \ |
| 5753 | bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \ |
| 5754 | const arg_type& arg, \ |
| 5755 | [[maybe_unused]] ::testing::MatchResultListener* result_listener) const |
| 5756 | |
| 5757 | #define MATCHER_P(name, p0, description) \ |
| 5758 | GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (#p0), (p0)) |
| 5759 | #define MATCHER_P2(name, p0, p1, description) \ |
| 5760 | GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (#p0, #p1), \ |
| 5761 | (p0, p1)) |
| 5762 | #define MATCHER_P3(name, p0, p1, p2, description) \ |
| 5763 | GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (#p0, #p1, #p2), \ |
| 5764 | (p0, p1, p2)) |
| 5765 | #define MATCHER_P4(name, p0, p1, p2, p3, description) \ |
| 5766 | GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, \ |
| 5767 | (#p0, #p1, #p2, #p3), (p0, p1, p2, p3)) |
| 5768 | #define MATCHER_P5(name, p0, p1, p2, p3, p4, description) \ |
| 5769 | GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \ |
| 5770 | (#p0, #p1, #p2, #p3, #p4), (p0, p1, p2, p3, p4)) |
| 5771 | #define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \ |
| 5772 | GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description, \ |
| 5773 | (#p0, #p1, #p2, #p3, #p4, #p5), \ |
| 5774 | (p0, p1, p2, p3, p4, p5)) |
| 5775 | #define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \ |
| 5776 | GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description, \ |
| 5777 | (#p0, #p1, #p2, #p3, #p4, #p5, #p6), \ |
| 5778 | (p0, p1, p2, p3, p4, p5, p6)) |
| 5779 | #define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \ |
| 5780 | GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description, \ |
| 5781 | (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7), \ |
| 5782 | (p0, p1, p2, p3, p4, p5, p6, p7)) |
| 5783 | #define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \ |
| 5784 | GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description, \ |
| 5785 | (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8), \ |
| 5786 | (p0, p1, p2, p3, p4, p5, p6, p7, p8)) |
| 5787 | #define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \ |
| 5788 | GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description, \ |
| 5789 | (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9), \ |
| 5790 | (p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) |
| 5791 | |
| 5792 | #define GMOCK_INTERNAL_MATCHER(name, full_name, description, arg_names, args) \ |
| 5793 | template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \ |
| 5794 | class full_name : public ::testing::internal::MatcherBaseImpl< \ |
| 5795 | full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \ |
| 5796 | public: \ |
| 5797 | using full_name::MatcherBaseImpl::MatcherBaseImpl; \ |
| 5798 | template <typename arg_type> \ |
| 5799 | class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \ |
| 5800 | public: \ |
| 5801 | explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) \ |
| 5802 | : GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {} \ |
| 5803 | bool MatchAndExplain( \ |
| 5804 | const arg_type& arg, \ |
| 5805 | ::testing::MatchResultListener* result_listener) const override; \ |
| 5806 | void DescribeTo(::std::ostream* gmock_os) const override { \ |
| 5807 | *gmock_os << FormatDescription(false); \ |
| 5808 | } \ |
| 5809 | void DescribeNegationTo(::std::ostream* gmock_os) const override { \ |
| 5810 | *gmock_os << FormatDescription(true); \ |
| 5811 | } \ |
| 5812 | GMOCK_INTERNAL_MATCHER_MEMBERS(args) \ |
| 5813 | \ |
| 5814 | private: \ |
| 5815 | ::std::string FormatDescription(bool negation) const { \ |
| 5816 | ::std::string gmock_description; \ |
| 5817 | gmock_description = (description); \ |
| 5818 | if (!gmock_description.empty()) { \ |
| 5819 | return gmock_description; \ |
| 5820 | } \ |
| 5821 | return ::testing::internal::FormatMatcherDescription( \ |
| 5822 | negation, #name, {GMOCK_PP_REMOVE_PARENS(arg_names)}, \ |
| 5823 | ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \ |
| 5824 | ::std::tuple<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \ |
| 5825 | GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args)))); \ |
| 5826 | } \ |
| 5827 | }; \ |
| 5828 | }; \ |
| 5829 | template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \ |
| 5830 | inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name( \ |
| 5831 | GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) { \ |
| 5832 | return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \ |
| 5833 | GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args)); \ |
| 5834 | } \ |
| 5835 | template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \ |
| 5836 | template <typename arg_type> \ |
| 5837 | bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>:: \ |
| 5838 | gmock_Impl<arg_type>::MatchAndExplain( \ |
| 5839 | const arg_type& arg, \ |
| 5840 | [[maybe_unused]] ::testing::MatchResultListener* result_listener) \ |
| 5841 | const |
| 5842 | |
| 5843 | #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \ |
| 5844 | GMOCK_PP_TAIL( \ |
| 5845 | GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args)) |
| 5846 | #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \ |
| 5847 | , typename arg##_type |
| 5848 | |
| 5849 | #define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \ |
| 5850 | GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args)) |
| 5851 | #define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \ |
| 5852 | , arg##_type |
| 5853 | |
| 5854 | #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \ |
| 5855 | GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH( \ |
| 5856 | GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args)) |
| 5857 | #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \ |
| 5858 | , arg##_type gmock_p##i |
| 5859 | |
| 5860 | #define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \ |
| 5861 | GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args)) |
| 5862 | #define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \ |
| 5863 | , arg(::std::forward<arg##_type>(gmock_p##i)) |
| 5864 | |
| 5865 | #define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \ |
| 5866 | GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args) |
| 5867 | #define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \ |
| 5868 | const arg##_type arg; |
| 5869 | |
| 5870 | #define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \ |
| 5871 | GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args)) |
| 5872 | #define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg |
| 5873 | |
| 5874 | #define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \ |
| 5875 | GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args)) |
| 5876 | #define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg) \ |
| 5877 | , ::std::forward<arg##_type>(gmock_p##i) |
| 5878 | |
| 5879 | // To prevent ADL on certain functions we put them on a separate namespace. |
| 5880 | using namespace no_adl; // NOLINT |
| 5881 | |
| 5882 | } // namespace testing |
| 5883 | |
| 5884 | GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046 |
| 5885 | |
| 5886 | // Include any custom callback matchers added by the local installation. |
| 5887 | // We must include this header at the end to make sure it can use the |
| 5888 | // declarations from this file. |
| 5889 | #include "gmock/internal/custom/gmock-matchers.h" |
| 5890 | |
| 5891 | #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ |
| 5892 | |