comparison dep/fmt/test/gtest/gmock/gmock.h @ 343:1faa72660932

*: transfer back to cmake from autotools autotools just made lots of things more complicated than they should have and many things broke (i.e. translations)
author Paper <paper@paper.us.eu.org>
date Thu, 20 Jun 2024 05:56:06 -0400
parents
children
comparison
equal deleted inserted replaced
342:adb79bdde329 343:1faa72660932
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
31 // Google Mock - a framework for writing C++ mock classes.
32 //
33 // This is the main header file a user should include.
34
35 // GOOGLETEST_CM0002 DO NOT DELETE
36
37 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
38 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
39
40 // This file implements the following syntax:
41 //
42 // ON_CALL(mock_object, Method(...))
43 // .With(...) ?
44 // .WillByDefault(...);
45 //
46 // where With() is optional and WillByDefault() must appear exactly
47 // once.
48 //
49 // EXPECT_CALL(mock_object, Method(...))
50 // .With(...) ?
51 // .Times(...) ?
52 // .InSequence(...) *
53 // .WillOnce(...) *
54 // .WillRepeatedly(...) ?
55 // .RetiresOnSaturation() ? ;
56 //
57 // where all clauses are optional and WillOnce() can be repeated.
58
59 // Copyright 2007, Google Inc.
60 // All rights reserved.
61 //
62 // Redistribution and use in source and binary forms, with or without
63 // modification, are permitted provided that the following conditions are
64 // met:
65 //
66 // * Redistributions of source code must retain the above copyright
67 // notice, this list of conditions and the following disclaimer.
68 // * Redistributions in binary form must reproduce the above
69 // copyright notice, this list of conditions and the following disclaimer
70 // in the documentation and/or other materials provided with the
71 // distribution.
72 // * Neither the name of Google Inc. nor the names of its
73 // contributors may be used to endorse or promote products derived from
74 // this software without specific prior written permission.
75 //
76 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
77 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
78 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
79 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
80 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
81 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
82 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
83 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
84 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
85 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
86 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
87
88
89 // Google Mock - a framework for writing C++ mock classes.
90 //
91 // The ACTION* family of macros can be used in a namespace scope to
92 // define custom actions easily. The syntax:
93 //
94 // ACTION(name) { statements; }
95 //
96 // will define an action with the given name that executes the
97 // statements. The value returned by the statements will be used as
98 // the return value of the action. Inside the statements, you can
99 // refer to the K-th (0-based) argument of the mock function by
100 // 'argK', and refer to its type by 'argK_type'. For example:
101 //
102 // ACTION(IncrementArg1) {
103 // arg1_type temp = arg1;
104 // return ++(*temp);
105 // }
106 //
107 // allows you to write
108 //
109 // ...WillOnce(IncrementArg1());
110 //
111 // You can also refer to the entire argument tuple and its type by
112 // 'args' and 'args_type', and refer to the mock function type and its
113 // return type by 'function_type' and 'return_type'.
114 //
115 // Note that you don't need to specify the types of the mock function
116 // arguments. However rest assured that your code is still type-safe:
117 // you'll get a compiler error if *arg1 doesn't support the ++
118 // operator, or if the type of ++(*arg1) isn't compatible with the
119 // mock function's return type, for example.
120 //
121 // Sometimes you'll want to parameterize the action. For that you can use
122 // another macro:
123 //
124 // ACTION_P(name, param_name) { statements; }
125 //
126 // For example:
127 //
128 // ACTION_P(Add, n) { return arg0 + n; }
129 //
130 // will allow you to write:
131 //
132 // ...WillOnce(Add(5));
133 //
134 // Note that you don't need to provide the type of the parameter
135 // either. If you need to reference the type of a parameter named
136 // 'foo', you can write 'foo_type'. For example, in the body of
137 // ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
138 // of 'n'.
139 //
140 // We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
141 // multi-parameter actions.
142 //
143 // For the purpose of typing, you can view
144 //
145 // ACTION_Pk(Foo, p1, ..., pk) { ... }
146 //
147 // as shorthand for
148 //
149 // template <typename p1_type, ..., typename pk_type>
150 // FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
151 //
152 // In particular, you can provide the template type arguments
153 // explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
154 // although usually you can rely on the compiler to infer the types
155 // for you automatically. You can assign the result of expression
156 // Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
157 // pk_type>. This can be useful when composing actions.
158 //
159 // You can also overload actions with different numbers of parameters:
160 //
161 // ACTION_P(Plus, a) { ... }
162 // ACTION_P2(Plus, a, b) { ... }
163 //
164 // While it's tempting to always use the ACTION* macros when defining
165 // a new action, you should also consider implementing ActionInterface
166 // or using MakePolymorphicAction() instead, especially if you need to
167 // use the action a lot. While these approaches require more work,
168 // they give you more control on the types of the mock function
169 // arguments and the action parameters, which in general leads to
170 // better compiler error messages that pay off in the long run. They
171 // also allow overloading actions based on parameter types (as opposed
172 // to just based on the number of parameters).
173 //
174 // CAVEAT:
175 //
176 // ACTION*() can only be used in a namespace scope as templates cannot be
177 // declared inside of a local class.
178 // Users can, however, define any local functors (e.g. a lambda) that
179 // can be used as actions.
180 //
181 // MORE INFORMATION:
182 //
183 // To learn more about using these macros, please search for 'ACTION' on
184 // https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
185
186 // GOOGLETEST_CM0002 DO NOT DELETE
187
188 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
189 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
190
191 #ifndef _WIN32_WCE
192 # include <errno.h>
193 #endif
194
195 #include <algorithm>
196 #include <functional>
197 #include <memory>
198 #include <string>
199 #include <tuple>
200 #include <type_traits>
201 #include <utility>
202
203 // Copyright 2007, Google Inc.
204 // All rights reserved.
205 //
206 // Redistribution and use in source and binary forms, with or without
207 // modification, are permitted provided that the following conditions are
208 // met:
209 //
210 // * Redistributions of source code must retain the above copyright
211 // notice, this list of conditions and the following disclaimer.
212 // * Redistributions in binary form must reproduce the above
213 // copyright notice, this list of conditions and the following disclaimer
214 // in the documentation and/or other materials provided with the
215 // distribution.
216 // * Neither the name of Google Inc. nor the names of its
217 // contributors may be used to endorse or promote products derived from
218 // this software without specific prior written permission.
219 //
220 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
221 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
222 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
223 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
224 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
225 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
226 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
227 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
228 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
229 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
230 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
231
232
233 // Google Mock - a framework for writing C++ mock classes.
234 //
235 // This file defines some utilities useful for implementing Google
236 // Mock. They are subject to change without notice, so please DO NOT
237 // USE THEM IN USER CODE.
238
239 // GOOGLETEST_CM0002 DO NOT DELETE
240
241 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
242 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
243
244 #include <stdio.h>
245 #include <ostream> // NOLINT
246 #include <string>
247 #include <type_traits>
248 // Copyright 2008, Google Inc.
249 // All rights reserved.
250 //
251 // Redistribution and use in source and binary forms, with or without
252 // modification, are permitted provided that the following conditions are
253 // met:
254 //
255 // * Redistributions of source code must retain the above copyright
256 // notice, this list of conditions and the following disclaimer.
257 // * Redistributions in binary form must reproduce the above
258 // copyright notice, this list of conditions and the following disclaimer
259 // in the documentation and/or other materials provided with the
260 // distribution.
261 // * Neither the name of Google Inc. nor the names of its
262 // contributors may be used to endorse or promote products derived from
263 // this software without specific prior written permission.
264 //
265 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
266 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
267 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
268 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
269 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
270 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
271 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
272 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
273 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
274 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
275 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
276
277 //
278 // Low-level types and utilities for porting Google Mock to various
279 // platforms. All macros ending with _ and symbols defined in an
280 // internal namespace are subject to change without notice. Code
281 // outside Google Mock MUST NOT USE THEM DIRECTLY. Macros that don't
282 // end with _ are part of Google Mock's public API and can be used by
283 // code outside Google Mock.
284
285 // GOOGLETEST_CM0002 DO NOT DELETE
286
287 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
288 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
289
290 #include <assert.h>
291 #include <stdlib.h>
292 #include <cstdint>
293 #include <iostream>
294
295 // Most of the utilities needed for porting Google Mock are also
296 // required for Google Test and are defined in gtest-port.h.
297 //
298 // Note to maintainers: to reduce code duplication, prefer adding
299 // portability utilities to Google Test's gtest-port.h instead of
300 // here, as Google Mock depends on Google Test. Only add a utility
301 // here if it's truly specific to Google Mock.
302
303 #include "gtest/gtest.h"
304 // Copyright 2015, Google Inc.
305 // All rights reserved.
306 //
307 // Redistribution and use in source and binary forms, with or without
308 // modification, are permitted provided that the following conditions are
309 // met:
310 //
311 // * Redistributions of source code must retain the above copyright
312 // notice, this list of conditions and the following disclaimer.
313 // * Redistributions in binary form must reproduce the above
314 // copyright notice, this list of conditions and the following disclaimer
315 // in the documentation and/or other materials provided with the
316 // distribution.
317 // * Neither the name of Google Inc. nor the names of its
318 // contributors may be used to endorse or promote products derived from
319 // this software without specific prior written permission.
320 //
321 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
322 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
323 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
324 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
325 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
326 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
327 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
328 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
329 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
330 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
331 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
332 //
333 // Injection point for custom user configurations. See README for details
334 //
335 // ** Custom implementation starts here **
336
337 // GOOGLETEST_CM0002 DO NOT DELETE
338
339 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
340 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
341
342 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
343
344 // For MS Visual C++, check the compiler version. At least VS 2015 is
345 // required to compile Google Mock.
346 #if defined(_MSC_VER) && _MSC_VER < 1900
347 # error "At least Visual C++ 2015 (14.0) is required to compile Google Mock."
348 #endif
349
350 // Macro for referencing flags. This is public as we want the user to
351 // use this syntax to reference Google Mock flags.
352 #define GMOCK_FLAG(name) FLAGS_gmock_##name
353
354 #if !defined(GMOCK_DECLARE_bool_)
355
356 // Macros for declaring flags.
357 # define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name)
358 # define GMOCK_DECLARE_int32_(name) extern GTEST_API_ int32_t GMOCK_FLAG(name)
359 # define GMOCK_DECLARE_string_(name) \
360 extern GTEST_API_ ::std::string GMOCK_FLAG(name)
361
362 // Macros for defining flags.
363 # define GMOCK_DEFINE_bool_(name, default_val, doc) \
364 GTEST_API_ bool GMOCK_FLAG(name) = (default_val)
365 # define GMOCK_DEFINE_int32_(name, default_val, doc) \
366 GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val)
367 # define GMOCK_DEFINE_string_(name, default_val, doc) \
368 GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val)
369
370 #endif // !defined(GMOCK_DECLARE_bool_)
371
372 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
373
374 namespace testing {
375
376 template <typename>
377 class Matcher;
378
379 namespace internal {
380
381 // Silence MSVC C4100 (unreferenced formal parameter) and
382 // C4805('==': unsafe mix of type 'const int' and type 'const bool')
383 #ifdef _MSC_VER
384 # pragma warning(push)
385 # pragma warning(disable:4100)
386 # pragma warning(disable:4805)
387 #endif
388
389 // Joins a vector of strings as if they are fields of a tuple; returns
390 // the joined string.
391 GTEST_API_ std::string JoinAsTuple(const Strings& fields);
392
393 // Converts an identifier name to a space-separated list of lower-case
394 // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
395 // treated as one word. For example, both "FooBar123" and
396 // "foo_bar_123" are converted to "foo bar 123".
397 GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
398
399 // GetRawPointer(p) returns the raw pointer underlying p when p is a
400 // smart pointer, or returns p itself when p is already a raw pointer.
401 // The following default implementation is for the smart pointer case.
402 template <typename Pointer>
403 inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
404 return p.get();
405 }
406 // This overloaded version is for the raw pointer case.
407 template <typename Element>
408 inline Element* GetRawPointer(Element* p) { return p; }
409
410 // MSVC treats wchar_t as a native type usually, but treats it as the
411 // same as unsigned short when the compiler option /Zc:wchar_t- is
412 // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
413 // is a native type.
414 #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
415 // wchar_t is a typedef.
416 #else
417 # define GMOCK_WCHAR_T_IS_NATIVE_ 1
418 #endif
419
420 // In what follows, we use the term "kind" to indicate whether a type
421 // is bool, an integer type (excluding bool), a floating-point type,
422 // or none of them. This categorization is useful for determining
423 // when a matcher argument type can be safely converted to another
424 // type in the implementation of SafeMatcherCast.
425 enum TypeKind {
426 kBool, kInteger, kFloatingPoint, kOther
427 };
428
429 // KindOf<T>::value is the kind of type T.
430 template <typename T> struct KindOf {
431 enum { value = kOther }; // The default kind.
432 };
433
434 // This macro declares that the kind of 'type' is 'kind'.
435 #define GMOCK_DECLARE_KIND_(type, kind) \
436 template <> struct KindOf<type> { enum { value = kind }; }
437
438 GMOCK_DECLARE_KIND_(bool, kBool);
439
440 // All standard integer types.
441 GMOCK_DECLARE_KIND_(char, kInteger);
442 GMOCK_DECLARE_KIND_(signed char, kInteger);
443 GMOCK_DECLARE_KIND_(unsigned char, kInteger);
444 GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT
445 GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT
446 GMOCK_DECLARE_KIND_(int, kInteger);
447 GMOCK_DECLARE_KIND_(unsigned int, kInteger);
448 GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
449 GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
450 GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT
451 GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT
452
453 #if GMOCK_WCHAR_T_IS_NATIVE_
454 GMOCK_DECLARE_KIND_(wchar_t, kInteger);
455 #endif
456
457 // All standard floating-point types.
458 GMOCK_DECLARE_KIND_(float, kFloatingPoint);
459 GMOCK_DECLARE_KIND_(double, kFloatingPoint);
460 GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
461
462 #undef GMOCK_DECLARE_KIND_
463
464 // Evaluates to the kind of 'type'.
465 #define GMOCK_KIND_OF_(type) \
466 static_cast< ::testing::internal::TypeKind>( \
467 ::testing::internal::KindOf<type>::value)
468
469 // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
470 // is true if and only if arithmetic type From can be losslessly converted to
471 // arithmetic type To.
472 //
473 // It's the user's responsibility to ensure that both From and To are
474 // raw (i.e. has no CV modifier, is not a pointer, and is not a
475 // reference) built-in arithmetic types, kFromKind is the kind of
476 // From, and kToKind is the kind of To; the value is
477 // implementation-defined when the above pre-condition is violated.
478 template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
479 using LosslessArithmeticConvertibleImpl = std::integral_constant<
480 bool,
481 // clang-format off
482 // Converting from bool is always lossless
483 (kFromKind == kBool) ? true
484 // Converting between any other type kinds will be lossy if the type
485 // kinds are not the same.
486 : (kFromKind != kToKind) ? false
487 : (kFromKind == kInteger &&
488 // Converting between integers of different widths is allowed so long
489 // as the conversion does not go from signed to unsigned.
490 (((sizeof(From) < sizeof(To)) &&
491 !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||
492 // Converting between integers of the same width only requires the
493 // two types to have the same signedness.
494 ((sizeof(From) == sizeof(To)) &&
495 (std::is_signed<From>::value == std::is_signed<To>::value)))
496 ) ? true
497 // Floating point conversions are lossless if and only if `To` is at least
498 // as wide as `From`.
499 : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true
500 : false
501 // clang-format on
502 >;
503
504 // LosslessArithmeticConvertible<From, To>::value is true if and only if
505 // arithmetic type From can be losslessly converted to arithmetic type To.
506 //
507 // It's the user's responsibility to ensure that both From and To are
508 // raw (i.e. has no CV modifier, is not a pointer, and is not a
509 // reference) built-in arithmetic types; the value is
510 // implementation-defined when the above pre-condition is violated.
511 template <typename From, typename To>
512 using LosslessArithmeticConvertible =
513 LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,
514 GMOCK_KIND_OF_(To), To>;
515
516 // This interface knows how to report a Google Mock failure (either
517 // non-fatal or fatal).
518 class FailureReporterInterface {
519 public:
520 // The type of a failure (either non-fatal or fatal).
521 enum FailureType {
522 kNonfatal, kFatal
523 };
524
525 virtual ~FailureReporterInterface() {}
526
527 // Reports a failure that occurred at the given source file location.
528 virtual void ReportFailure(FailureType type, const char* file, int line,
529 const std::string& message) = 0;
530 };
531
532 // Returns the failure reporter used by Google Mock.
533 GTEST_API_ FailureReporterInterface* GetFailureReporter();
534
535 // Asserts that condition is true; aborts the process with the given
536 // message if condition is false. We cannot use LOG(FATAL) or CHECK()
537 // as Google Mock might be used to mock the log sink itself. We
538 // inline this function to prevent it from showing up in the stack
539 // trace.
540 inline void Assert(bool condition, const char* file, int line,
541 const std::string& msg) {
542 if (!condition) {
543 GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
544 file, line, msg);
545 }
546 }
547 inline void Assert(bool condition, const char* file, int line) {
548 Assert(condition, file, line, "Assertion failed.");
549 }
550
551 // Verifies that condition is true; generates a non-fatal failure if
552 // condition is false.
553 inline void Expect(bool condition, const char* file, int line,
554 const std::string& msg) {
555 if (!condition) {
556 GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
557 file, line, msg);
558 }
559 }
560 inline void Expect(bool condition, const char* file, int line) {
561 Expect(condition, file, line, "Expectation failed.");
562 }
563
564 // Severity level of a log.
565 enum LogSeverity {
566 kInfo = 0,
567 kWarning = 1
568 };
569
570 // Valid values for the --gmock_verbose flag.
571
572 // All logs (informational and warnings) are printed.
573 const char kInfoVerbosity[] = "info";
574 // Only warnings are printed.
575 const char kWarningVerbosity[] = "warning";
576 // No logs are printed.
577 const char kErrorVerbosity[] = "error";
578
579 // Returns true if and only if a log with the given severity is visible
580 // according to the --gmock_verbose flag.
581 GTEST_API_ bool LogIsVisible(LogSeverity severity);
582
583 // Prints the given message to stdout if and only if 'severity' >= the level
584 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
585 // 0, also prints the stack trace excluding the top
586 // stack_frames_to_skip frames. In opt mode, any positive
587 // stack_frames_to_skip is treated as 0, since we don't know which
588 // function calls will be inlined by the compiler and need to be
589 // conservative.
590 GTEST_API_ void Log(LogSeverity severity, const std::string& message,
591 int stack_frames_to_skip);
592
593 // A marker class that is used to resolve parameterless expectations to the
594 // correct overload. This must not be instantiable, to prevent client code from
595 // accidentally resolving to the overload; for example:
596 //
597 // ON_CALL(mock, Method({}, nullptr))...
598 //
599 class WithoutMatchers {
600 private:
601 WithoutMatchers() {}
602 friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
603 };
604
605 // Internal use only: access the singleton instance of WithoutMatchers.
606 GTEST_API_ WithoutMatchers GetWithoutMatchers();
607
608 // Disable MSVC warnings for infinite recursion, since in this case the
609 // the recursion is unreachable.
610 #ifdef _MSC_VER
611 # pragma warning(push)
612 # pragma warning(disable:4717)
613 #endif
614
615 // Invalid<T>() is usable as an expression of type T, but will terminate
616 // the program with an assertion failure if actually run. This is useful
617 // when a value of type T is needed for compilation, but the statement
618 // will not really be executed (or we don't care if the statement
619 // crashes).
620 template <typename T>
621 inline T Invalid() {
622 Assert(false, "", -1, "Internal error: attempt to return invalid value");
623 // This statement is unreachable, and would never terminate even if it
624 // could be reached. It is provided only to placate compiler warnings
625 // about missing return statements.
626 return Invalid<T>();
627 }
628
629 #ifdef _MSC_VER
630 # pragma warning(pop)
631 #endif
632
633 // Given a raw type (i.e. having no top-level reference or const
634 // modifier) RawContainer that's either an STL-style container or a
635 // native array, class StlContainerView<RawContainer> has the
636 // following members:
637 //
638 // - type is a type that provides an STL-style container view to
639 // (i.e. implements the STL container concept for) RawContainer;
640 // - const_reference is a type that provides a reference to a const
641 // RawContainer;
642 // - ConstReference(raw_container) returns a const reference to an STL-style
643 // container view to raw_container, which is a RawContainer.
644 // - Copy(raw_container) returns an STL-style container view of a
645 // copy of raw_container, which is a RawContainer.
646 //
647 // This generic version is used when RawContainer itself is already an
648 // STL-style container.
649 template <class RawContainer>
650 class StlContainerView {
651 public:
652 typedef RawContainer type;
653 typedef const type& const_reference;
654
655 static const_reference ConstReference(const RawContainer& container) {
656 static_assert(!std::is_const<RawContainer>::value,
657 "RawContainer type must not be const");
658 return container;
659 }
660 static type Copy(const RawContainer& container) { return container; }
661 };
662
663 // This specialization is used when RawContainer is a native array type.
664 template <typename Element, size_t N>
665 class StlContainerView<Element[N]> {
666 public:
667 typedef typename std::remove_const<Element>::type RawElement;
668 typedef internal::NativeArray<RawElement> type;
669 // NativeArray<T> can represent a native array either by value or by
670 // reference (selected by a constructor argument), so 'const type'
671 // can be used to reference a const native array. We cannot
672 // 'typedef const type& const_reference' here, as that would mean
673 // ConstReference() has to return a reference to a local variable.
674 typedef const type const_reference;
675
676 static const_reference ConstReference(const Element (&array)[N]) {
677 static_assert(std::is_same<Element, RawElement>::value,
678 "Element type must not be const");
679 return type(array, N, RelationToSourceReference());
680 }
681 static type Copy(const Element (&array)[N]) {
682 return type(array, N, RelationToSourceCopy());
683 }
684 };
685
686 // This specialization is used when RawContainer is a native array
687 // represented as a (pointer, size) tuple.
688 template <typename ElementPointer, typename Size>
689 class StlContainerView< ::std::tuple<ElementPointer, Size> > {
690 public:
691 typedef typename std::remove_const<
692 typename std::pointer_traits<ElementPointer>::element_type>::type
693 RawElement;
694 typedef internal::NativeArray<RawElement> type;
695 typedef const type const_reference;
696
697 static const_reference ConstReference(
698 const ::std::tuple<ElementPointer, Size>& array) {
699 return type(std::get<0>(array), std::get<1>(array),
700 RelationToSourceReference());
701 }
702 static type Copy(const ::std::tuple<ElementPointer, Size>& array) {
703 return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());
704 }
705 };
706
707 // The following specialization prevents the user from instantiating
708 // StlContainer with a reference type.
709 template <typename T> class StlContainerView<T&>;
710
711 // A type transform to remove constness from the first part of a pair.
712 // Pairs like that are used as the value_type of associative containers,
713 // and this transform produces a similar but assignable pair.
714 template <typename T>
715 struct RemoveConstFromKey {
716 typedef T type;
717 };
718
719 // Partially specialized to remove constness from std::pair<const K, V>.
720 template <typename K, typename V>
721 struct RemoveConstFromKey<std::pair<const K, V> > {
722 typedef std::pair<K, V> type;
723 };
724
725 // Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
726 // reduce code size.
727 GTEST_API_ void IllegalDoDefault(const char* file, int line);
728
729 template <typename F, typename Tuple, size_t... Idx>
730 auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(
731 std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
732 return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
733 }
734
735 // Apply the function to a tuple of arguments.
736 template <typename F, typename Tuple>
737 auto Apply(F&& f, Tuple&& args) -> decltype(
738 ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
739 MakeIndexSequence<std::tuple_size<
740 typename std::remove_reference<Tuple>::type>::value>())) {
741 return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
742 MakeIndexSequence<std::tuple_size<
743 typename std::remove_reference<Tuple>::type>::value>());
744 }
745
746 // Template struct Function<F>, where F must be a function type, contains
747 // the following typedefs:
748 //
749 // Result: the function's return type.
750 // Arg<N>: the type of the N-th argument, where N starts with 0.
751 // ArgumentTuple: the tuple type consisting of all parameters of F.
752 // ArgumentMatcherTuple: the tuple type consisting of Matchers for all
753 // parameters of F.
754 // MakeResultVoid: the function type obtained by substituting void
755 // for the return type of F.
756 // MakeResultIgnoredValue:
757 // the function type obtained by substituting Something
758 // for the return type of F.
759 template <typename T>
760 struct Function;
761
762 template <typename R, typename... Args>
763 struct Function<R(Args...)> {
764 using Result = R;
765 static constexpr size_t ArgumentCount = sizeof...(Args);
766 template <size_t I>
767 using Arg = ElemFromList<I, Args...>;
768 using ArgumentTuple = std::tuple<Args...>;
769 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
770 using MakeResultVoid = void(Args...);
771 using MakeResultIgnoredValue = IgnoredValue(Args...);
772 };
773
774 template <typename R, typename... Args>
775 constexpr size_t Function<R(Args...)>::ArgumentCount;
776
777 #ifdef _MSC_VER
778 # pragma warning(pop)
779 #endif
780
781 } // namespace internal
782 } // namespace testing
783
784 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
785 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
786 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
787
788 // Expands and concatenates the arguments. Constructed macros reevaluate.
789 #define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2)
790
791 // Expands and stringifies the only argument.
792 #define GMOCK_PP_STRINGIZE(...) GMOCK_PP_INTERNAL_STRINGIZE(__VA_ARGS__)
793
794 // Returns empty. Given a variadic number of arguments.
795 #define GMOCK_PP_EMPTY(...)
796
797 // Returns a comma. Given a variadic number of arguments.
798 #define GMOCK_PP_COMMA(...) ,
799
800 // Returns the only argument.
801 #define GMOCK_PP_IDENTITY(_1) _1
802
803 // Evaluates to the number of arguments after expansion.
804 //
805 // #define PAIR x, y
806 //
807 // GMOCK_PP_NARG() => 1
808 // GMOCK_PP_NARG(x) => 1
809 // GMOCK_PP_NARG(x, y) => 2
810 // GMOCK_PP_NARG(PAIR) => 2
811 //
812 // Requires: the number of arguments after expansion is at most 15.
813 #define GMOCK_PP_NARG(...) \
814 GMOCK_PP_INTERNAL_16TH( \
815 (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
816
817 // Returns 1 if the expansion of arguments has an unprotected comma. Otherwise
818 // returns 0. Requires no more than 15 unprotected commas.
819 #define GMOCK_PP_HAS_COMMA(...) \
820 GMOCK_PP_INTERNAL_16TH( \
821 (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0))
822
823 // Returns the first argument.
824 #define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__, unusedArg))
825
826 // Returns the tail. A variadic list of all arguments minus the first. Requires
827 // at least one argument.
828 #define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL((__VA_ARGS__))
829
830 // Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__)
831 #define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \
832 GMOCK_PP_IDENTITY( \
833 GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__))
834
835 // If the arguments after expansion have no tokens, evaluates to `1`. Otherwise
836 // evaluates to `0`.
837 //
838 // Requires: * the number of arguments after expansion is at most 15.
839 // * If the argument is a macro, it must be able to be called with one
840 // argument.
841 //
842 // Implementation details:
843 //
844 // There is one case when it generates a compile error: if the argument is macro
845 // that cannot be called with one argument.
846 //
847 // #define M(a, b) // it doesn't matter what it expands to
848 //
849 // // Expected: expands to `0`.
850 // // Actual: compile error.
851 // GMOCK_PP_IS_EMPTY(M)
852 //
853 // There are 4 cases tested:
854 //
855 // * __VA_ARGS__ possible expansion has no unparen'd commas. Expected 0.
856 // * __VA_ARGS__ possible expansion is not enclosed in parenthesis. Expected 0.
857 // * __VA_ARGS__ possible expansion is not a macro that ()-evaluates to a comma.
858 // Expected 0
859 // * __VA_ARGS__ is empty, or has unparen'd commas, or is enclosed in
860 // parenthesis, or is a macro that ()-evaluates to comma. Expected 1.
861 //
862 // We trigger detection on '0001', i.e. on empty.
863 #define GMOCK_PP_IS_EMPTY(...) \
864 GMOCK_PP_INTERNAL_IS_EMPTY(GMOCK_PP_HAS_COMMA(__VA_ARGS__), \
865 GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__), \
866 GMOCK_PP_HAS_COMMA(__VA_ARGS__()), \
867 GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__()))
868
869 // Evaluates to _Then if _Cond is 1 and _Else if _Cond is 0.
870 #define GMOCK_PP_IF(_Cond, _Then, _Else) \
871 GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else)
872
873 // Similar to GMOCK_PP_IF but takes _Then and _Else in parentheses.
874 //
875 // GMOCK_PP_GENERIC_IF(1, (a, b, c), (d, e, f)) => a, b, c
876 // GMOCK_PP_GENERIC_IF(0, (a, b, c), (d, e, f)) => d, e, f
877 //
878 #define GMOCK_PP_GENERIC_IF(_Cond, _Then, _Else) \
879 GMOCK_PP_REMOVE_PARENS(GMOCK_PP_IF(_Cond, _Then, _Else))
880
881 // Evaluates to the number of arguments after expansion. Identifies 'empty' as
882 // 0.
883 //
884 // #define PAIR x, y
885 //
886 // GMOCK_PP_NARG0() => 0
887 // GMOCK_PP_NARG0(x) => 1
888 // GMOCK_PP_NARG0(x, y) => 2
889 // GMOCK_PP_NARG0(PAIR) => 2
890 //
891 // Requires: * the number of arguments after expansion is at most 15.
892 // * If the argument is a macro, it must be able to be called with one
893 // argument.
894 #define GMOCK_PP_NARG0(...) \
895 GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(__VA_ARGS__), 0, GMOCK_PP_NARG(__VA_ARGS__))
896
897 // Expands to 1 if the first argument starts with something in parentheses,
898 // otherwise to 0.
899 #define GMOCK_PP_IS_BEGIN_PARENS(...) \
900 GMOCK_PP_HEAD(GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \
901 GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__))
902
903 // Expands to 1 is there is only one argument and it is enclosed in parentheses.
904 #define GMOCK_PP_IS_ENCLOSED_PARENS(...) \
905 GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(__VA_ARGS__), \
906 GMOCK_PP_IS_EMPTY(GMOCK_PP_EMPTY __VA_ARGS__), 0)
907
908 // Remove the parens, requires GMOCK_PP_IS_ENCLOSED_PARENS(args) => 1.
909 #define GMOCK_PP_REMOVE_PARENS(...) GMOCK_PP_INTERNAL_REMOVE_PARENS __VA_ARGS__
910
911 // Expands to _Macro(0, _Data, e1) _Macro(1, _Data, e2) ... _Macro(K -1, _Data,
912 // eK) as many of GMOCK_INTERNAL_NARG0 _Tuple.
913 // Requires: * |_Macro| can be called with 3 arguments.
914 // * |_Tuple| expansion has no more than 15 elements.
915 #define GMOCK_PP_FOR_EACH(_Macro, _Data, _Tuple) \
916 GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, GMOCK_PP_NARG0 _Tuple) \
917 (0, _Macro, _Data, _Tuple)
918
919 // Expands to _Macro(0, _Data, ) _Macro(1, _Data, ) ... _Macro(K - 1, _Data, )
920 // Empty if _K = 0.
921 // Requires: * |_Macro| can be called with 3 arguments.
922 // * |_K| literal between 0 and 15
923 #define GMOCK_PP_REPEAT(_Macro, _Data, _N) \
924 GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, _N) \
925 (0, _Macro, _Data, GMOCK_PP_INTENRAL_EMPTY_TUPLE)
926
927 // Increments the argument, requires the argument to be between 0 and 15.
928 #define GMOCK_PP_INC(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_INC_, _i)
929
930 // Returns comma if _i != 0. Requires _i to be between 0 and 15.
931 #define GMOCK_PP_COMMA_IF(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_COMMA_IF_, _i)
932
933 // Internal details follow. Do not use any of these symbols outside of this
934 // file or we will break your code.
935 #define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , )
936 #define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2
937 #define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__
938 #define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5
939 #define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4) \
940 GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \
941 _1, _2, _3, _4))
942 #define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 ,
943 #define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then
944 #define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else
945
946 // Because of MSVC treating a token with a comma in it as a single token when
947 // passed to another macro, we need to force it to evaluate it as multiple
948 // tokens. We do that by using a "IDENTITY(MACRO PARENTHESIZED_ARGS)" macro. We
949 // define one per possible macro that relies on this behavior. Note "_Args" must
950 // be parenthesized.
951 #define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \
952 _10, _11, _12, _13, _14, _15, _16, \
953 ...) \
954 _16
955 #define GMOCK_PP_INTERNAL_16TH(_Args) \
956 GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_16TH _Args)
957 #define GMOCK_PP_INTERNAL_INTERNAL_HEAD(_1, ...) _1
958 #define GMOCK_PP_INTERNAL_HEAD(_Args) \
959 GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_HEAD _Args)
960 #define GMOCK_PP_INTERNAL_INTERNAL_TAIL(_1, ...) __VA_ARGS__
961 #define GMOCK_PP_INTERNAL_TAIL(_Args) \
962 GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_TAIL _Args)
963
964 #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _
965 #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1,
966 #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C \
967 0,
968 #define GMOCK_PP_INTERNAL_REMOVE_PARENS(...) __VA_ARGS__
969 #define GMOCK_PP_INTERNAL_INC_0 1
970 #define GMOCK_PP_INTERNAL_INC_1 2
971 #define GMOCK_PP_INTERNAL_INC_2 3
972 #define GMOCK_PP_INTERNAL_INC_3 4
973 #define GMOCK_PP_INTERNAL_INC_4 5
974 #define GMOCK_PP_INTERNAL_INC_5 6
975 #define GMOCK_PP_INTERNAL_INC_6 7
976 #define GMOCK_PP_INTERNAL_INC_7 8
977 #define GMOCK_PP_INTERNAL_INC_8 9
978 #define GMOCK_PP_INTERNAL_INC_9 10
979 #define GMOCK_PP_INTERNAL_INC_10 11
980 #define GMOCK_PP_INTERNAL_INC_11 12
981 #define GMOCK_PP_INTERNAL_INC_12 13
982 #define GMOCK_PP_INTERNAL_INC_13 14
983 #define GMOCK_PP_INTERNAL_INC_14 15
984 #define GMOCK_PP_INTERNAL_INC_15 16
985 #define GMOCK_PP_INTERNAL_COMMA_IF_0
986 #define GMOCK_PP_INTERNAL_COMMA_IF_1 ,
987 #define GMOCK_PP_INTERNAL_COMMA_IF_2 ,
988 #define GMOCK_PP_INTERNAL_COMMA_IF_3 ,
989 #define GMOCK_PP_INTERNAL_COMMA_IF_4 ,
990 #define GMOCK_PP_INTERNAL_COMMA_IF_5 ,
991 #define GMOCK_PP_INTERNAL_COMMA_IF_6 ,
992 #define GMOCK_PP_INTERNAL_COMMA_IF_7 ,
993 #define GMOCK_PP_INTERNAL_COMMA_IF_8 ,
994 #define GMOCK_PP_INTERNAL_COMMA_IF_9 ,
995 #define GMOCK_PP_INTERNAL_COMMA_IF_10 ,
996 #define GMOCK_PP_INTERNAL_COMMA_IF_11 ,
997 #define GMOCK_PP_INTERNAL_COMMA_IF_12 ,
998 #define GMOCK_PP_INTERNAL_COMMA_IF_13 ,
999 #define GMOCK_PP_INTERNAL_COMMA_IF_14 ,
1000 #define GMOCK_PP_INTERNAL_COMMA_IF_15 ,
1001 #define GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, _element) \
1002 _Macro(_i, _Data, _element)
1003 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_0(_i, _Macro, _Data, _Tuple)
1004 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(_i, _Macro, _Data, _Tuple) \
1005 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple)
1006 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(_i, _Macro, _Data, _Tuple) \
1007 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1008 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(GMOCK_PP_INC(_i), _Macro, _Data, \
1009 (GMOCK_PP_TAIL _Tuple))
1010 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(_i, _Macro, _Data, _Tuple) \
1011 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1012 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(GMOCK_PP_INC(_i), _Macro, _Data, \
1013 (GMOCK_PP_TAIL _Tuple))
1014 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(_i, _Macro, _Data, _Tuple) \
1015 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1016 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(GMOCK_PP_INC(_i), _Macro, _Data, \
1017 (GMOCK_PP_TAIL _Tuple))
1018 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(_i, _Macro, _Data, _Tuple) \
1019 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1020 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(GMOCK_PP_INC(_i), _Macro, _Data, \
1021 (GMOCK_PP_TAIL _Tuple))
1022 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(_i, _Macro, _Data, _Tuple) \
1023 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1024 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(GMOCK_PP_INC(_i), _Macro, _Data, \
1025 (GMOCK_PP_TAIL _Tuple))
1026 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(_i, _Macro, _Data, _Tuple) \
1027 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1028 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(GMOCK_PP_INC(_i), _Macro, _Data, \
1029 (GMOCK_PP_TAIL _Tuple))
1030 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(_i, _Macro, _Data, _Tuple) \
1031 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1032 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(GMOCK_PP_INC(_i), _Macro, _Data, \
1033 (GMOCK_PP_TAIL _Tuple))
1034 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(_i, _Macro, _Data, _Tuple) \
1035 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1036 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(GMOCK_PP_INC(_i), _Macro, _Data, \
1037 (GMOCK_PP_TAIL _Tuple))
1038 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(_i, _Macro, _Data, _Tuple) \
1039 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1040 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(GMOCK_PP_INC(_i), _Macro, _Data, \
1041 (GMOCK_PP_TAIL _Tuple))
1042 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(_i, _Macro, _Data, _Tuple) \
1043 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1044 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(GMOCK_PP_INC(_i), _Macro, _Data, \
1045 (GMOCK_PP_TAIL _Tuple))
1046 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(_i, _Macro, _Data, _Tuple) \
1047 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1048 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(GMOCK_PP_INC(_i), _Macro, _Data, \
1049 (GMOCK_PP_TAIL _Tuple))
1050 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(_i, _Macro, _Data, _Tuple) \
1051 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1052 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(GMOCK_PP_INC(_i), _Macro, _Data, \
1053 (GMOCK_PP_TAIL _Tuple))
1054 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(_i, _Macro, _Data, _Tuple) \
1055 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1056 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(GMOCK_PP_INC(_i), _Macro, _Data, \
1057 (GMOCK_PP_TAIL _Tuple))
1058 #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_15(_i, _Macro, _Data, _Tuple) \
1059 GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
1060 GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data, \
1061 (GMOCK_PP_TAIL _Tuple))
1062
1063 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
1064
1065 #ifdef _MSC_VER
1066 # pragma warning(push)
1067 # pragma warning(disable:4100)
1068 #endif
1069
1070 namespace testing {
1071
1072 // To implement an action Foo, define:
1073 // 1. a class FooAction that implements the ActionInterface interface, and
1074 // 2. a factory function that creates an Action object from a
1075 // const FooAction*.
1076 //
1077 // The two-level delegation design follows that of Matcher, providing
1078 // consistency for extension developers. It also eases ownership
1079 // management as Action objects can now be copied like plain values.
1080
1081 namespace internal {
1082
1083 // BuiltInDefaultValueGetter<T, true>::Get() returns a
1084 // default-constructed T value. BuiltInDefaultValueGetter<T,
1085 // false>::Get() crashes with an error.
1086 //
1087 // This primary template is used when kDefaultConstructible is true.
1088 template <typename T, bool kDefaultConstructible>
1089 struct BuiltInDefaultValueGetter {
1090 static T Get() { return T(); }
1091 };
1092 template <typename T>
1093 struct BuiltInDefaultValueGetter<T, false> {
1094 static T Get() {
1095 Assert(false, __FILE__, __LINE__,
1096 "Default action undefined for the function return type.");
1097 return internal::Invalid<T>();
1098 // The above statement will never be reached, but is required in
1099 // order for this function to compile.
1100 }
1101 };
1102
1103 // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
1104 // for type T, which is NULL when T is a raw pointer type, 0 when T is
1105 // a numeric type, false when T is bool, or "" when T is string or
1106 // std::string. In addition, in C++11 and above, it turns a
1107 // default-constructed T value if T is default constructible. For any
1108 // other type T, the built-in default T value is undefined, and the
1109 // function will abort the process.
1110 template <typename T>
1111 class BuiltInDefaultValue {
1112 public:
1113 // This function returns true if and only if type T has a built-in default
1114 // value.
1115 static bool Exists() {
1116 return ::std::is_default_constructible<T>::value;
1117 }
1118
1119 static T Get() {
1120 return BuiltInDefaultValueGetter<
1121 T, ::std::is_default_constructible<T>::value>::Get();
1122 }
1123 };
1124
1125 // This partial specialization says that we use the same built-in
1126 // default value for T and const T.
1127 template <typename T>
1128 class BuiltInDefaultValue<const T> {
1129 public:
1130 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
1131 static T Get() { return BuiltInDefaultValue<T>::Get(); }
1132 };
1133
1134 // This partial specialization defines the default values for pointer
1135 // types.
1136 template <typename T>
1137 class BuiltInDefaultValue<T*> {
1138 public:
1139 static bool Exists() { return true; }
1140 static T* Get() { return nullptr; }
1141 };
1142
1143 // The following specializations define the default values for
1144 // specific types we care about.
1145 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
1146 template <> \
1147 class BuiltInDefaultValue<type> { \
1148 public: \
1149 static bool Exists() { return true; } \
1150 static type Get() { return value; } \
1151 }
1152
1153 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
1154 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
1155 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
1156 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
1157 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
1158 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
1159
1160 // There's no need for a default action for signed wchar_t, as that
1161 // type is the same as wchar_t for gcc, and invalid for MSVC.
1162 //
1163 // There's also no need for a default action for unsigned wchar_t, as
1164 // that type is the same as unsigned int for gcc, and invalid for
1165 // MSVC.
1166 #if GMOCK_WCHAR_T_IS_NATIVE_
1167 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
1168 #endif
1169
1170 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
1171 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
1172 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
1173 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
1174 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
1175 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
1176 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT
1177 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT
1178 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
1179 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
1180
1181 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
1182
1183 // Simple two-arg form of std::disjunction.
1184 template <typename P, typename Q>
1185 using disjunction = typename ::std::conditional<P::value, P, Q>::type;
1186
1187 } // namespace internal
1188
1189 // When an unexpected function call is encountered, Google Mock will
1190 // let it return a default value if the user has specified one for its
1191 // return type, or if the return type has a built-in default value;
1192 // otherwise Google Mock won't know what value to return and will have
1193 // to abort the process.
1194 //
1195 // The DefaultValue<T> class allows a user to specify the
1196 // default value for a type T that is both copyable and publicly
1197 // destructible (i.e. anything that can be used as a function return
1198 // type). The usage is:
1199 //
1200 // // Sets the default value for type T to be foo.
1201 // DefaultValue<T>::Set(foo);
1202 template <typename T>
1203 class DefaultValue {
1204 public:
1205 // Sets the default value for type T; requires T to be
1206 // copy-constructable and have a public destructor.
1207 static void Set(T x) {
1208 delete producer_;
1209 producer_ = new FixedValueProducer(x);
1210 }
1211
1212 // Provides a factory function to be called to generate the default value.
1213 // This method can be used even if T is only move-constructible, but it is not
1214 // limited to that case.
1215 typedef T (*FactoryFunction)();
1216 static void SetFactory(FactoryFunction factory) {
1217 delete producer_;
1218 producer_ = new FactoryValueProducer(factory);
1219 }
1220
1221 // Unsets the default value for type T.
1222 static void Clear() {
1223 delete producer_;
1224 producer_ = nullptr;
1225 }
1226
1227 // Returns true if and only if the user has set the default value for type T.
1228 static bool IsSet() { return producer_ != nullptr; }
1229
1230 // Returns true if T has a default return value set by the user or there
1231 // exists a built-in default value.
1232 static bool Exists() {
1233 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
1234 }
1235
1236 // Returns the default value for type T if the user has set one;
1237 // otherwise returns the built-in default value. Requires that Exists()
1238 // is true, which ensures that the return value is well-defined.
1239 static T Get() {
1240 return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
1241 : producer_->Produce();
1242 }
1243
1244 private:
1245 class ValueProducer {
1246 public:
1247 virtual ~ValueProducer() {}
1248 virtual T Produce() = 0;
1249 };
1250
1251 class FixedValueProducer : public ValueProducer {
1252 public:
1253 explicit FixedValueProducer(T value) : value_(value) {}
1254 T Produce() override { return value_; }
1255
1256 private:
1257 const T value_;
1258 GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
1259 };
1260
1261 class FactoryValueProducer : public ValueProducer {
1262 public:
1263 explicit FactoryValueProducer(FactoryFunction factory)
1264 : factory_(factory) {}
1265 T Produce() override { return factory_(); }
1266
1267 private:
1268 const FactoryFunction factory_;
1269 GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
1270 };
1271
1272 static ValueProducer* producer_;
1273 };
1274
1275 // This partial specialization allows a user to set default values for
1276 // reference types.
1277 template <typename T>
1278 class DefaultValue<T&> {
1279 public:
1280 // Sets the default value for type T&.
1281 static void Set(T& x) { // NOLINT
1282 address_ = &x;
1283 }
1284
1285 // Unsets the default value for type T&.
1286 static void Clear() { address_ = nullptr; }
1287
1288 // Returns true if and only if the user has set the default value for type T&.
1289 static bool IsSet() { return address_ != nullptr; }
1290
1291 // Returns true if T has a default return value set by the user or there
1292 // exists a built-in default value.
1293 static bool Exists() {
1294 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
1295 }
1296
1297 // Returns the default value for type T& if the user has set one;
1298 // otherwise returns the built-in default value if there is one;
1299 // otherwise aborts the process.
1300 static T& Get() {
1301 return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
1302 : *address_;
1303 }
1304
1305 private:
1306 static T* address_;
1307 };
1308
1309 // This specialization allows DefaultValue<void>::Get() to
1310 // compile.
1311 template <>
1312 class DefaultValue<void> {
1313 public:
1314 static bool Exists() { return true; }
1315 static void Get() {}
1316 };
1317
1318 // Points to the user-set default value for type T.
1319 template <typename T>
1320 typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
1321
1322 // Points to the user-set default value for type T&.
1323 template <typename T>
1324 T* DefaultValue<T&>::address_ = nullptr;
1325
1326 // Implement this interface to define an action for function type F.
1327 template <typename F>
1328 class ActionInterface {
1329 public:
1330 typedef typename internal::Function<F>::Result Result;
1331 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1332
1333 ActionInterface() {}
1334 virtual ~ActionInterface() {}
1335
1336 // Performs the action. This method is not const, as in general an
1337 // action can have side effects and be stateful. For example, a
1338 // get-the-next-element-from-the-collection action will need to
1339 // remember the current element.
1340 virtual Result Perform(const ArgumentTuple& args) = 0;
1341
1342 private:
1343 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
1344 };
1345
1346 // An Action<F> is a copyable and IMMUTABLE (except by assignment)
1347 // object that represents an action to be taken when a mock function
1348 // of type F is called. The implementation of Action<T> is just a
1349 // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
1350 // You can view an object implementing ActionInterface<F> as a
1351 // concrete action (including its current state), and an Action<F>
1352 // object as a handle to it.
1353 template <typename F>
1354 class Action {
1355 // Adapter class to allow constructing Action from a legacy ActionInterface.
1356 // New code should create Actions from functors instead.
1357 struct ActionAdapter {
1358 // Adapter must be copyable to satisfy std::function requirements.
1359 ::std::shared_ptr<ActionInterface<F>> impl_;
1360
1361 template <typename... Args>
1362 typename internal::Function<F>::Result operator()(Args&&... args) {
1363 return impl_->Perform(
1364 ::std::forward_as_tuple(::std::forward<Args>(args)...));
1365 }
1366 };
1367
1368 template <typename G>
1369 using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;
1370
1371 public:
1372 typedef typename internal::Function<F>::Result Result;
1373 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1374
1375 // Constructs a null Action. Needed for storing Action objects in
1376 // STL containers.
1377 Action() {}
1378
1379 // Construct an Action from a specified callable.
1380 // This cannot take std::function directly, because then Action would not be
1381 // directly constructible from lambda (it would require two conversions).
1382 template <
1383 typename G,
1384 typename = typename std::enable_if<internal::disjunction<
1385 IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,
1386 G>>::value>::type>
1387 Action(G&& fun) { // NOLINT
1388 Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());
1389 }
1390
1391 // Constructs an Action from its implementation.
1392 explicit Action(ActionInterface<F>* impl)
1393 : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
1394
1395 // This constructor allows us to turn an Action<Func> object into an
1396 // Action<F>, as long as F's arguments can be implicitly converted
1397 // to Func's and Func's return type can be implicitly converted to F's.
1398 template <typename Func>
1399 explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
1400
1401 // Returns true if and only if this is the DoDefault() action.
1402 bool IsDoDefault() const { return fun_ == nullptr; }
1403
1404 // Performs the action. Note that this method is const even though
1405 // the corresponding method in ActionInterface is not. The reason
1406 // is that a const Action<F> means that it cannot be re-bound to
1407 // another concrete action, not that the concrete action it binds to
1408 // cannot change state. (Think of the difference between a const
1409 // pointer and a pointer to const.)
1410 Result Perform(ArgumentTuple args) const {
1411 if (IsDoDefault()) {
1412 internal::IllegalDoDefault(__FILE__, __LINE__);
1413 }
1414 return internal::Apply(fun_, ::std::move(args));
1415 }
1416
1417 private:
1418 template <typename G>
1419 friend class Action;
1420
1421 template <typename G>
1422 void Init(G&& g, ::std::true_type) {
1423 fun_ = ::std::forward<G>(g);
1424 }
1425
1426 template <typename G>
1427 void Init(G&& g, ::std::false_type) {
1428 fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};
1429 }
1430
1431 template <typename FunctionImpl>
1432 struct IgnoreArgs {
1433 template <typename... Args>
1434 Result operator()(const Args&...) const {
1435 return function_impl();
1436 }
1437
1438 FunctionImpl function_impl;
1439 };
1440
1441 // fun_ is an empty function if and only if this is the DoDefault() action.
1442 ::std::function<F> fun_;
1443 };
1444
1445 // The PolymorphicAction class template makes it easy to implement a
1446 // polymorphic action (i.e. an action that can be used in mock
1447 // functions of than one type, e.g. Return()).
1448 //
1449 // To define a polymorphic action, a user first provides a COPYABLE
1450 // implementation class that has a Perform() method template:
1451 //
1452 // class FooAction {
1453 // public:
1454 // template <typename Result, typename ArgumentTuple>
1455 // Result Perform(const ArgumentTuple& args) const {
1456 // // Processes the arguments and returns a result, using
1457 // // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
1458 // }
1459 // ...
1460 // };
1461 //
1462 // Then the user creates the polymorphic action using
1463 // MakePolymorphicAction(object) where object has type FooAction. See
1464 // the definition of Return(void) and SetArgumentPointee<N>(value) for
1465 // complete examples.
1466 template <typename Impl>
1467 class PolymorphicAction {
1468 public:
1469 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
1470
1471 template <typename F>
1472 operator Action<F>() const {
1473 return Action<F>(new MonomorphicImpl<F>(impl_));
1474 }
1475
1476 private:
1477 template <typename F>
1478 class MonomorphicImpl : public ActionInterface<F> {
1479 public:
1480 typedef typename internal::Function<F>::Result Result;
1481 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1482
1483 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
1484
1485 Result Perform(const ArgumentTuple& args) override {
1486 return impl_.template Perform<Result>(args);
1487 }
1488
1489 private:
1490 Impl impl_;
1491 };
1492
1493 Impl impl_;
1494 };
1495
1496 // Creates an Action from its implementation and returns it. The
1497 // created Action object owns the implementation.
1498 template <typename F>
1499 Action<F> MakeAction(ActionInterface<F>* impl) {
1500 return Action<F>(impl);
1501 }
1502
1503 // Creates a polymorphic action from its implementation. This is
1504 // easier to use than the PolymorphicAction<Impl> constructor as it
1505 // doesn't require you to explicitly write the template argument, e.g.
1506 //
1507 // MakePolymorphicAction(foo);
1508 // vs
1509 // PolymorphicAction<TypeOfFoo>(foo);
1510 template <typename Impl>
1511 inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
1512 return PolymorphicAction<Impl>(impl);
1513 }
1514
1515 namespace internal {
1516
1517 // Helper struct to specialize ReturnAction to execute a move instead of a copy
1518 // on return. Useful for move-only types, but could be used on any type.
1519 template <typename T>
1520 struct ByMoveWrapper {
1521 explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
1522 T payload;
1523 };
1524
1525 // Implements the polymorphic Return(x) action, which can be used in
1526 // any function that returns the type of x, regardless of the argument
1527 // types.
1528 //
1529 // Note: The value passed into Return must be converted into
1530 // Function<F>::Result when this action is cast to Action<F> rather than
1531 // when that action is performed. This is important in scenarios like
1532 //
1533 // MOCK_METHOD1(Method, T(U));
1534 // ...
1535 // {
1536 // Foo foo;
1537 // X x(&foo);
1538 // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
1539 // }
1540 //
1541 // In the example above the variable x holds reference to foo which leaves
1542 // scope and gets destroyed. If copying X just copies a reference to foo,
1543 // that copy will be left with a hanging reference. If conversion to T
1544 // makes a copy of foo, the above code is safe. To support that scenario, we
1545 // need to make sure that the type conversion happens inside the EXPECT_CALL
1546 // statement, and conversion of the result of Return to Action<T(U)> is a
1547 // good place for that.
1548 //
1549 // The real life example of the above scenario happens when an invocation
1550 // of gtl::Container() is passed into Return.
1551 //
1552 template <typename R>
1553 class ReturnAction {
1554 public:
1555 // Constructs a ReturnAction object from the value to be returned.
1556 // 'value' is passed by value instead of by const reference in order
1557 // to allow Return("string literal") to compile.
1558 explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
1559
1560 // This template type conversion operator allows Return(x) to be
1561 // used in ANY function that returns x's type.
1562 template <typename F>
1563 operator Action<F>() const { // NOLINT
1564 // Assert statement belongs here because this is the best place to verify
1565 // conditions on F. It produces the clearest error messages
1566 // in most compilers.
1567 // Impl really belongs in this scope as a local class but can't
1568 // because MSVC produces duplicate symbols in different translation units
1569 // in this case. Until MS fixes that bug we put Impl into the class scope
1570 // and put the typedef both here (for use in assert statement) and
1571 // in the Impl class. But both definitions must be the same.
1572 typedef typename Function<F>::Result Result;
1573 GTEST_COMPILE_ASSERT_(
1574 !std::is_reference<Result>::value,
1575 use_ReturnRef_instead_of_Return_to_return_a_reference);
1576 static_assert(!std::is_void<Result>::value,
1577 "Can't use Return() on an action expected to return `void`.");
1578 return Action<F>(new Impl<R, F>(value_));
1579 }
1580
1581 private:
1582 // Implements the Return(x) action for a particular function type F.
1583 template <typename R_, typename F>
1584 class Impl : public ActionInterface<F> {
1585 public:
1586 typedef typename Function<F>::Result Result;
1587 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1588
1589 // The implicit cast is necessary when Result has more than one
1590 // single-argument constructor (e.g. Result is std::vector<int>) and R
1591 // has a type conversion operator template. In that case, value_(value)
1592 // won't compile as the compiler doesn't known which constructor of
1593 // Result to call. ImplicitCast_ forces the compiler to convert R to
1594 // Result without considering explicit constructors, thus resolving the
1595 // ambiguity. value_ is then initialized using its copy constructor.
1596 explicit Impl(const std::shared_ptr<R>& value)
1597 : value_before_cast_(*value),
1598 value_(ImplicitCast_<Result>(value_before_cast_)) {}
1599
1600 Result Perform(const ArgumentTuple&) override { return value_; }
1601
1602 private:
1603 GTEST_COMPILE_ASSERT_(!std::is_reference<Result>::value,
1604 Result_cannot_be_a_reference_type);
1605 // We save the value before casting just in case it is being cast to a
1606 // wrapper type.
1607 R value_before_cast_;
1608 Result value_;
1609
1610 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
1611 };
1612
1613 // Partially specialize for ByMoveWrapper. This version of ReturnAction will
1614 // move its contents instead.
1615 template <typename R_, typename F>
1616 class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
1617 public:
1618 typedef typename Function<F>::Result Result;
1619 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1620
1621 explicit Impl(const std::shared_ptr<R>& wrapper)
1622 : performed_(false), wrapper_(wrapper) {}
1623
1624 Result Perform(const ArgumentTuple&) override {
1625 GTEST_CHECK_(!performed_)
1626 << "A ByMove() action should only be performed once.";
1627 performed_ = true;
1628 return std::move(wrapper_->payload);
1629 }
1630
1631 private:
1632 bool performed_;
1633 const std::shared_ptr<R> wrapper_;
1634 };
1635
1636 const std::shared_ptr<R> value_;
1637 };
1638
1639 // Implements the ReturnNull() action.
1640 class ReturnNullAction {
1641 public:
1642 // Allows ReturnNull() to be used in any pointer-returning function. In C++11
1643 // this is enforced by returning nullptr, and in non-C++11 by asserting a
1644 // pointer type on compile time.
1645 template <typename Result, typename ArgumentTuple>
1646 static Result Perform(const ArgumentTuple&) {
1647 return nullptr;
1648 }
1649 };
1650
1651 // Implements the Return() action.
1652 class ReturnVoidAction {
1653 public:
1654 // Allows Return() to be used in any void-returning function.
1655 template <typename Result, typename ArgumentTuple>
1656 static void Perform(const ArgumentTuple&) {
1657 static_assert(std::is_void<Result>::value, "Result should be void.");
1658 }
1659 };
1660
1661 // Implements the polymorphic ReturnRef(x) action, which can be used
1662 // in any function that returns a reference to the type of x,
1663 // regardless of the argument types.
1664 template <typename T>
1665 class ReturnRefAction {
1666 public:
1667 // Constructs a ReturnRefAction object from the reference to be returned.
1668 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
1669
1670 // This template type conversion operator allows ReturnRef(x) to be
1671 // used in ANY function that returns a reference to x's type.
1672 template <typename F>
1673 operator Action<F>() const {
1674 typedef typename Function<F>::Result Result;
1675 // Asserts that the function return type is a reference. This
1676 // catches the user error of using ReturnRef(x) when Return(x)
1677 // should be used, and generates some helpful error message.
1678 GTEST_COMPILE_ASSERT_(std::is_reference<Result>::value,
1679 use_Return_instead_of_ReturnRef_to_return_a_value);
1680 return Action<F>(new Impl<F>(ref_));
1681 }
1682
1683 private:
1684 // Implements the ReturnRef(x) action for a particular function type F.
1685 template <typename F>
1686 class Impl : public ActionInterface<F> {
1687 public:
1688 typedef typename Function<F>::Result Result;
1689 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1690
1691 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
1692
1693 Result Perform(const ArgumentTuple&) override { return ref_; }
1694
1695 private:
1696 T& ref_;
1697 };
1698
1699 T& ref_;
1700 };
1701
1702 // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
1703 // used in any function that returns a reference to the type of x,
1704 // regardless of the argument types.
1705 template <typename T>
1706 class ReturnRefOfCopyAction {
1707 public:
1708 // Constructs a ReturnRefOfCopyAction object from the reference to
1709 // be returned.
1710 explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
1711
1712 // This template type conversion operator allows ReturnRefOfCopy(x) to be
1713 // used in ANY function that returns a reference to x's type.
1714 template <typename F>
1715 operator Action<F>() const {
1716 typedef typename Function<F>::Result Result;
1717 // Asserts that the function return type is a reference. This
1718 // catches the user error of using ReturnRefOfCopy(x) when Return(x)
1719 // should be used, and generates some helpful error message.
1720 GTEST_COMPILE_ASSERT_(
1721 std::is_reference<Result>::value,
1722 use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
1723 return Action<F>(new Impl<F>(value_));
1724 }
1725
1726 private:
1727 // Implements the ReturnRefOfCopy(x) action for a particular function type F.
1728 template <typename F>
1729 class Impl : public ActionInterface<F> {
1730 public:
1731 typedef typename Function<F>::Result Result;
1732 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1733
1734 explicit Impl(const T& value) : value_(value) {} // NOLINT
1735
1736 Result Perform(const ArgumentTuple&) override { return value_; }
1737
1738 private:
1739 T value_;
1740 };
1741
1742 const T value_;
1743 };
1744
1745 // Implements the polymorphic ReturnRoundRobin(v) action, which can be
1746 // used in any function that returns the element_type of v.
1747 template <typename T>
1748 class ReturnRoundRobinAction {
1749 public:
1750 explicit ReturnRoundRobinAction(std::vector<T> values) {
1751 GTEST_CHECK_(!values.empty())
1752 << "ReturnRoundRobin requires at least one element.";
1753 state_->values = std::move(values);
1754 }
1755
1756 template <typename... Args>
1757 T operator()(Args&&...) const {
1758 return state_->Next();
1759 }
1760
1761 private:
1762 struct State {
1763 T Next() {
1764 T ret_val = values[i++];
1765 if (i == values.size()) i = 0;
1766 return ret_val;
1767 }
1768
1769 std::vector<T> values;
1770 size_t i = 0;
1771 };
1772 std::shared_ptr<State> state_ = std::make_shared<State>();
1773 };
1774
1775 // Implements the polymorphic DoDefault() action.
1776 class DoDefaultAction {
1777 public:
1778 // This template type conversion operator allows DoDefault() to be
1779 // used in any function.
1780 template <typename F>
1781 operator Action<F>() const { return Action<F>(); } // NOLINT
1782 };
1783
1784 // Implements the Assign action to set a given pointer referent to a
1785 // particular value.
1786 template <typename T1, typename T2>
1787 class AssignAction {
1788 public:
1789 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
1790
1791 template <typename Result, typename ArgumentTuple>
1792 void Perform(const ArgumentTuple& /* args */) const {
1793 *ptr_ = value_;
1794 }
1795
1796 private:
1797 T1* const ptr_;
1798 const T2 value_;
1799 };
1800
1801 #if !GTEST_OS_WINDOWS_MOBILE
1802
1803 // Implements the SetErrnoAndReturn action to simulate return from
1804 // various system calls and libc functions.
1805 template <typename T>
1806 class SetErrnoAndReturnAction {
1807 public:
1808 SetErrnoAndReturnAction(int errno_value, T result)
1809 : errno_(errno_value),
1810 result_(result) {}
1811 template <typename Result, typename ArgumentTuple>
1812 Result Perform(const ArgumentTuple& /* args */) const {
1813 errno = errno_;
1814 return result_;
1815 }
1816
1817 private:
1818 const int errno_;
1819 const T result_;
1820 };
1821
1822 #endif // !GTEST_OS_WINDOWS_MOBILE
1823
1824 // Implements the SetArgumentPointee<N>(x) action for any function
1825 // whose N-th argument (0-based) is a pointer to x's type.
1826 template <size_t N, typename A, typename = void>
1827 struct SetArgumentPointeeAction {
1828 A value;
1829
1830 template <typename... Args>
1831 void operator()(const Args&... args) const {
1832 *::std::get<N>(std::tie(args...)) = value;
1833 }
1834 };
1835
1836 // Implements the Invoke(object_ptr, &Class::Method) action.
1837 template <class Class, typename MethodPtr>
1838 struct InvokeMethodAction {
1839 Class* const obj_ptr;
1840 const MethodPtr method_ptr;
1841
1842 template <typename... Args>
1843 auto operator()(Args&&... args) const
1844 -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
1845 return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
1846 }
1847 };
1848
1849 // Implements the InvokeWithoutArgs(f) action. The template argument
1850 // FunctionImpl is the implementation type of f, which can be either a
1851 // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
1852 // Action<F> as long as f's type is compatible with F.
1853 template <typename FunctionImpl>
1854 struct InvokeWithoutArgsAction {
1855 FunctionImpl function_impl;
1856
1857 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
1858 // compatible with f.
1859 template <typename... Args>
1860 auto operator()(const Args&...) -> decltype(function_impl()) {
1861 return function_impl();
1862 }
1863 };
1864
1865 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
1866 template <class Class, typename MethodPtr>
1867 struct InvokeMethodWithoutArgsAction {
1868 Class* const obj_ptr;
1869 const MethodPtr method_ptr;
1870
1871 using ReturnType =
1872 decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());
1873
1874 template <typename... Args>
1875 ReturnType operator()(const Args&...) const {
1876 return (obj_ptr->*method_ptr)();
1877 }
1878 };
1879
1880 // Implements the IgnoreResult(action) action.
1881 template <typename A>
1882 class IgnoreResultAction {
1883 public:
1884 explicit IgnoreResultAction(const A& action) : action_(action) {}
1885
1886 template <typename F>
1887 operator Action<F>() const {
1888 // Assert statement belongs here because this is the best place to verify
1889 // conditions on F. It produces the clearest error messages
1890 // in most compilers.
1891 // Impl really belongs in this scope as a local class but can't
1892 // because MSVC produces duplicate symbols in different translation units
1893 // in this case. Until MS fixes that bug we put Impl into the class scope
1894 // and put the typedef both here (for use in assert statement) and
1895 // in the Impl class. But both definitions must be the same.
1896 typedef typename internal::Function<F>::Result Result;
1897
1898 // Asserts at compile time that F returns void.
1899 static_assert(std::is_void<Result>::value, "Result type should be void.");
1900
1901 return Action<F>(new Impl<F>(action_));
1902 }
1903
1904 private:
1905 template <typename F>
1906 class Impl : public ActionInterface<F> {
1907 public:
1908 typedef typename internal::Function<F>::Result Result;
1909 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1910
1911 explicit Impl(const A& action) : action_(action) {}
1912
1913 void Perform(const ArgumentTuple& args) override {
1914 // Performs the action and ignores its result.
1915 action_.Perform(args);
1916 }
1917
1918 private:
1919 // Type OriginalFunction is the same as F except that its return
1920 // type is IgnoredValue.
1921 typedef typename internal::Function<F>::MakeResultIgnoredValue
1922 OriginalFunction;
1923
1924 const Action<OriginalFunction> action_;
1925 };
1926
1927 const A action_;
1928 };
1929
1930 template <typename InnerAction, size_t... I>
1931 struct WithArgsAction {
1932 InnerAction action;
1933
1934 // The inner action could be anything convertible to Action<X>.
1935 // We use the conversion operator to detect the signature of the inner Action.
1936 template <typename R, typename... Args>
1937 operator Action<R(Args...)>() const { // NOLINT
1938 using TupleType = std::tuple<Args...>;
1939 Action<R(typename std::tuple_element<I, TupleType>::type...)>
1940 converted(action);
1941
1942 return [converted](Args... args) -> R {
1943 return converted.Perform(std::forward_as_tuple(
1944 std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
1945 };
1946 }
1947 };
1948
1949 template <typename... Actions>
1950 struct DoAllAction {
1951 private:
1952 template <typename T>
1953 using NonFinalType =
1954 typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;
1955
1956 template <typename ActionT, size_t... I>
1957 std::vector<ActionT> Convert(IndexSequence<I...>) const {
1958 return {ActionT(std::get<I>(actions))...};
1959 }
1960
1961 public:
1962 std::tuple<Actions...> actions;
1963
1964 template <typename R, typename... Args>
1965 operator Action<R(Args...)>() const { // NOLINT
1966 struct Op {
1967 std::vector<Action<void(NonFinalType<Args>...)>> converted;
1968 Action<R(Args...)> last;
1969 R operator()(Args... args) const {
1970 auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
1971 for (auto& a : converted) {
1972 a.Perform(tuple_args);
1973 }
1974 return last.Perform(std::move(tuple_args));
1975 }
1976 };
1977 return Op{Convert<Action<void(NonFinalType<Args>...)>>(
1978 MakeIndexSequence<sizeof...(Actions) - 1>()),
1979 std::get<sizeof...(Actions) - 1>(actions)};
1980 }
1981 };
1982
1983 template <typename T, typename... Params>
1984 struct ReturnNewAction {
1985 T* operator()() const {
1986 return internal::Apply(
1987 [](const Params&... unpacked_params) {
1988 return new T(unpacked_params...);
1989 },
1990 params);
1991 }
1992 std::tuple<Params...> params;
1993 };
1994
1995 template <size_t k>
1996 struct ReturnArgAction {
1997 template <typename... Args>
1998 auto operator()(const Args&... args) const ->
1999 typename std::tuple_element<k, std::tuple<Args...>>::type {
2000 return std::get<k>(std::tie(args...));
2001 }
2002 };
2003
2004 template <size_t k, typename Ptr>
2005 struct SaveArgAction {
2006 Ptr pointer;
2007
2008 template <typename... Args>
2009 void operator()(const Args&... args) const {
2010 *pointer = std::get<k>(std::tie(args...));
2011 }
2012 };
2013
2014 template <size_t k, typename Ptr>
2015 struct SaveArgPointeeAction {
2016 Ptr pointer;
2017
2018 template <typename... Args>
2019 void operator()(const Args&... args) const {
2020 *pointer = *std::get<k>(std::tie(args...));
2021 }
2022 };
2023
2024 template <size_t k, typename T>
2025 struct SetArgRefereeAction {
2026 T value;
2027
2028 template <typename... Args>
2029 void operator()(Args&&... args) const {
2030 using argk_type =
2031 typename ::std::tuple_element<k, std::tuple<Args...>>::type;
2032 static_assert(std::is_lvalue_reference<argk_type>::value,
2033 "Argument must be a reference type.");
2034 std::get<k>(std::tie(args...)) = value;
2035 }
2036 };
2037
2038 template <size_t k, typename I1, typename I2>
2039 struct SetArrayArgumentAction {
2040 I1 first;
2041 I2 last;
2042
2043 template <typename... Args>
2044 void operator()(const Args&... args) const {
2045 auto value = std::get<k>(std::tie(args...));
2046 for (auto it = first; it != last; ++it, (void)++value) {
2047 *value = *it;
2048 }
2049 }
2050 };
2051
2052 template <size_t k>
2053 struct DeleteArgAction {
2054 template <typename... Args>
2055 void operator()(const Args&... args) const {
2056 delete std::get<k>(std::tie(args...));
2057 }
2058 };
2059
2060 template <typename Ptr>
2061 struct ReturnPointeeAction {
2062 Ptr pointer;
2063 template <typename... Args>
2064 auto operator()(const Args&...) const -> decltype(*pointer) {
2065 return *pointer;
2066 }
2067 };
2068
2069 #if GTEST_HAS_EXCEPTIONS
2070 template <typename T>
2071 struct ThrowAction {
2072 T exception;
2073 // We use a conversion operator to adapt to any return type.
2074 template <typename R, typename... Args>
2075 operator Action<R(Args...)>() const { // NOLINT
2076 T copy = exception;
2077 return [copy](Args...) -> R { throw copy; };
2078 }
2079 };
2080 #endif // GTEST_HAS_EXCEPTIONS
2081
2082 } // namespace internal
2083
2084 // An Unused object can be implicitly constructed from ANY value.
2085 // This is handy when defining actions that ignore some or all of the
2086 // mock function arguments. For example, given
2087 //
2088 // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
2089 // MOCK_METHOD3(Bar, double(int index, double x, double y));
2090 //
2091 // instead of
2092 //
2093 // double DistanceToOriginWithLabel(const string& label, double x, double y) {
2094 // return sqrt(x*x + y*y);
2095 // }
2096 // double DistanceToOriginWithIndex(int index, double x, double y) {
2097 // return sqrt(x*x + y*y);
2098 // }
2099 // ...
2100 // EXPECT_CALL(mock, Foo("abc", _, _))
2101 // .WillOnce(Invoke(DistanceToOriginWithLabel));
2102 // EXPECT_CALL(mock, Bar(5, _, _))
2103 // .WillOnce(Invoke(DistanceToOriginWithIndex));
2104 //
2105 // you could write
2106 //
2107 // // We can declare any uninteresting argument as Unused.
2108 // double DistanceToOrigin(Unused, double x, double y) {
2109 // return sqrt(x*x + y*y);
2110 // }
2111 // ...
2112 // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
2113 // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
2114 typedef internal::IgnoredValue Unused;
2115
2116 // Creates an action that does actions a1, a2, ..., sequentially in
2117 // each invocation. All but the last action will have a readonly view of the
2118 // arguments.
2119 template <typename... Action>
2120 internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
2121 Action&&... action) {
2122 return {std::forward_as_tuple(std::forward<Action>(action)...)};
2123 }
2124
2125 // WithArg<k>(an_action) creates an action that passes the k-th
2126 // (0-based) argument of the mock function to an_action and performs
2127 // it. It adapts an action accepting one argument to one that accepts
2128 // multiple arguments. For convenience, we also provide
2129 // WithArgs<k>(an_action) (defined below) as a synonym.
2130 template <size_t k, typename InnerAction>
2131 internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
2132 WithArg(InnerAction&& action) {
2133 return {std::forward<InnerAction>(action)};
2134 }
2135
2136 // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
2137 // the selected arguments of the mock function to an_action and
2138 // performs it. It serves as an adaptor between actions with
2139 // different argument lists.
2140 template <size_t k, size_t... ks, typename InnerAction>
2141 internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
2142 WithArgs(InnerAction&& action) {
2143 return {std::forward<InnerAction>(action)};
2144 }
2145
2146 // WithoutArgs(inner_action) can be used in a mock function with a
2147 // non-empty argument list to perform inner_action, which takes no
2148 // argument. In other words, it adapts an action accepting no
2149 // argument to one that accepts (and ignores) arguments.
2150 template <typename InnerAction>
2151 internal::WithArgsAction<typename std::decay<InnerAction>::type>
2152 WithoutArgs(InnerAction&& action) {
2153 return {std::forward<InnerAction>(action)};
2154 }
2155
2156 // Creates an action that returns 'value'. 'value' is passed by value
2157 // instead of const reference - otherwise Return("string literal")
2158 // will trigger a compiler error about using array as initializer.
2159 template <typename R>
2160 internal::ReturnAction<R> Return(R value) {
2161 return internal::ReturnAction<R>(std::move(value));
2162 }
2163
2164 // Creates an action that returns NULL.
2165 inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
2166 return MakePolymorphicAction(internal::ReturnNullAction());
2167 }
2168
2169 // Creates an action that returns from a void function.
2170 inline PolymorphicAction<internal::ReturnVoidAction> Return() {
2171 return MakePolymorphicAction(internal::ReturnVoidAction());
2172 }
2173
2174 // Creates an action that returns the reference to a variable.
2175 template <typename R>
2176 inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
2177 return internal::ReturnRefAction<R>(x);
2178 }
2179
2180 // Prevent using ReturnRef on reference to temporary.
2181 template <typename R, R* = nullptr>
2182 internal::ReturnRefAction<R> ReturnRef(R&&) = delete;
2183
2184 // Creates an action that returns the reference to a copy of the
2185 // argument. The copy is created when the action is constructed and
2186 // lives as long as the action.
2187 template <typename R>
2188 inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
2189 return internal::ReturnRefOfCopyAction<R>(x);
2190 }
2191
2192 // Modifies the parent action (a Return() action) to perform a move of the
2193 // argument instead of a copy.
2194 // Return(ByMove()) actions can only be executed once and will assert this
2195 // invariant.
2196 template <typename R>
2197 internal::ByMoveWrapper<R> ByMove(R x) {
2198 return internal::ByMoveWrapper<R>(std::move(x));
2199 }
2200
2201 // Creates an action that returns an element of `vals`. Calling this action will
2202 // repeatedly return the next value from `vals` until it reaches the end and
2203 // will restart from the beginning.
2204 template <typename T>
2205 internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {
2206 return internal::ReturnRoundRobinAction<T>(std::move(vals));
2207 }
2208
2209 // Creates an action that returns an element of `vals`. Calling this action will
2210 // repeatedly return the next value from `vals` until it reaches the end and
2211 // will restart from the beginning.
2212 template <typename T>
2213 internal::ReturnRoundRobinAction<T> ReturnRoundRobin(
2214 std::initializer_list<T> vals) {
2215 return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));
2216 }
2217
2218 // Creates an action that does the default action for the give mock function.
2219 inline internal::DoDefaultAction DoDefault() {
2220 return internal::DoDefaultAction();
2221 }
2222
2223 // Creates an action that sets the variable pointed by the N-th
2224 // (0-based) function argument to 'value'.
2225 template <size_t N, typename T>
2226 internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {
2227 return {std::move(value)};
2228 }
2229
2230 // The following version is DEPRECATED.
2231 template <size_t N, typename T>
2232 internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {
2233 return {std::move(value)};
2234 }
2235
2236 // Creates an action that sets a pointer referent to a given value.
2237 template <typename T1, typename T2>
2238 PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
2239 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
2240 }
2241
2242 #if !GTEST_OS_WINDOWS_MOBILE
2243
2244 // Creates an action that sets errno and returns the appropriate error.
2245 template <typename T>
2246 PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
2247 SetErrnoAndReturn(int errval, T result) {
2248 return MakePolymorphicAction(
2249 internal::SetErrnoAndReturnAction<T>(errval, result));
2250 }
2251
2252 #endif // !GTEST_OS_WINDOWS_MOBILE
2253
2254 // Various overloads for Invoke().
2255
2256 // Legacy function.
2257 // Actions can now be implicitly constructed from callables. No need to create
2258 // wrapper objects.
2259 // This function exists for backwards compatibility.
2260 template <typename FunctionImpl>
2261 typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
2262 return std::forward<FunctionImpl>(function_impl);
2263 }
2264
2265 // Creates an action that invokes the given method on the given object
2266 // with the mock function's arguments.
2267 template <class Class, typename MethodPtr>
2268 internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
2269 MethodPtr method_ptr) {
2270 return {obj_ptr, method_ptr};
2271 }
2272
2273 // Creates an action that invokes 'function_impl' with no argument.
2274 template <typename FunctionImpl>
2275 internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
2276 InvokeWithoutArgs(FunctionImpl function_impl) {
2277 return {std::move(function_impl)};
2278 }
2279
2280 // Creates an action that invokes the given method on the given object
2281 // with no argument.
2282 template <class Class, typename MethodPtr>
2283 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
2284 Class* obj_ptr, MethodPtr method_ptr) {
2285 return {obj_ptr, method_ptr};
2286 }
2287
2288 // Creates an action that performs an_action and throws away its
2289 // result. In other words, it changes the return type of an_action to
2290 // void. an_action MUST NOT return void, or the code won't compile.
2291 template <typename A>
2292 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
2293 return internal::IgnoreResultAction<A>(an_action);
2294 }
2295
2296 // Creates a reference wrapper for the given L-value. If necessary,
2297 // you can explicitly specify the type of the reference. For example,
2298 // suppose 'derived' is an object of type Derived, ByRef(derived)
2299 // would wrap a Derived&. If you want to wrap a const Base& instead,
2300 // where Base is a base class of Derived, just write:
2301 //
2302 // ByRef<const Base>(derived)
2303 //
2304 // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
2305 // However, it may still be used for consistency with ByMove().
2306 template <typename T>
2307 inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
2308 return ::std::reference_wrapper<T>(l_value);
2309 }
2310
2311 // The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
2312 // instance of type T, constructed on the heap with constructor arguments
2313 // a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
2314 template <typename T, typename... Params>
2315 internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
2316 Params&&... params) {
2317 return {std::forward_as_tuple(std::forward<Params>(params)...)};
2318 }
2319
2320 // Action ReturnArg<k>() returns the k-th argument of the mock function.
2321 template <size_t k>
2322 internal::ReturnArgAction<k> ReturnArg() {
2323 return {};
2324 }
2325
2326 // Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
2327 // mock function to *pointer.
2328 template <size_t k, typename Ptr>
2329 internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
2330 return {pointer};
2331 }
2332
2333 // Action SaveArgPointee<k>(pointer) saves the value pointed to
2334 // by the k-th (0-based) argument of the mock function to *pointer.
2335 template <size_t k, typename Ptr>
2336 internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {
2337 return {pointer};
2338 }
2339
2340 // Action SetArgReferee<k>(value) assigns 'value' to the variable
2341 // referenced by the k-th (0-based) argument of the mock function.
2342 template <size_t k, typename T>
2343 internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(
2344 T&& value) {
2345 return {std::forward<T>(value)};
2346 }
2347
2348 // Action SetArrayArgument<k>(first, last) copies the elements in
2349 // source range [first, last) to the array pointed to by the k-th
2350 // (0-based) argument, which can be either a pointer or an
2351 // iterator. The action does not take ownership of the elements in the
2352 // source range.
2353 template <size_t k, typename I1, typename I2>
2354 internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,
2355 I2 last) {
2356 return {first, last};
2357 }
2358
2359 // Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
2360 // function.
2361 template <size_t k>
2362 internal::DeleteArgAction<k> DeleteArg() {
2363 return {};
2364 }
2365
2366 // This action returns the value pointed to by 'pointer'.
2367 template <typename Ptr>
2368 internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
2369 return {pointer};
2370 }
2371
2372 // Action Throw(exception) can be used in a mock function of any type
2373 // to throw the given exception. Any copyable value can be thrown.
2374 #if GTEST_HAS_EXCEPTIONS
2375 template <typename T>
2376 internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {
2377 return {std::forward<T>(exception)};
2378 }
2379 #endif // GTEST_HAS_EXCEPTIONS
2380
2381 namespace internal {
2382
2383 // A macro from the ACTION* family (defined later in gmock-generated-actions.h)
2384 // defines an action that can be used in a mock function. Typically,
2385 // these actions only care about a subset of the arguments of the mock
2386 // function. For example, if such an action only uses the second
2387 // argument, it can be used in any mock function that takes >= 2
2388 // arguments where the type of the second argument is compatible.
2389 //
2390 // Therefore, the action implementation must be prepared to take more
2391 // arguments than it needs. The ExcessiveArg type is used to
2392 // represent those excessive arguments. In order to keep the compiler
2393 // error messages tractable, we define it in the testing namespace
2394 // instead of testing::internal. However, this is an INTERNAL TYPE
2395 // and subject to change without notice, so a user MUST NOT USE THIS
2396 // TYPE DIRECTLY.
2397 struct ExcessiveArg {};
2398
2399 // Builds an implementation of an Action<> for some particular signature, using
2400 // a class defined by an ACTION* macro.
2401 template <typename F, typename Impl> struct ActionImpl;
2402
2403 template <typename Impl>
2404 struct ImplBase {
2405 struct Holder {
2406 // Allows each copy of the Action<> to get to the Impl.
2407 explicit operator const Impl&() const { return *ptr; }
2408 std::shared_ptr<Impl> ptr;
2409 };
2410 using type = typename std::conditional<std::is_constructible<Impl>::value,
2411 Impl, Holder>::type;
2412 };
2413
2414 template <typename R, typename... Args, typename Impl>
2415 struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
2416 using Base = typename ImplBase<Impl>::type;
2417 using function_type = R(Args...);
2418 using args_type = std::tuple<Args...>;
2419
2420 ActionImpl() = default; // Only defined if appropriate for Base.
2421 explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} { }
2422
2423 R operator()(Args&&... arg) const {
2424 static constexpr size_t kMaxArgs =
2425 sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
2426 return Apply(MakeIndexSequence<kMaxArgs>{},
2427 MakeIndexSequence<10 - kMaxArgs>{},
2428 args_type{std::forward<Args>(arg)...});
2429 }
2430
2431 template <std::size_t... arg_id, std::size_t... excess_id>
2432 R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,
2433 const args_type& args) const {
2434 // Impl need not be specific to the signature of action being implemented;
2435 // only the implementing function body needs to have all of the specific
2436 // types instantiated. Up to 10 of the args that are provided by the
2437 // args_type get passed, followed by a dummy of unspecified type for the
2438 // remainder up to 10 explicit args.
2439 static constexpr ExcessiveArg kExcessArg{};
2440 return static_cast<const Impl&>(*this).template gmock_PerformImpl<
2441 /*function_type=*/function_type, /*return_type=*/R,
2442 /*args_type=*/args_type,
2443 /*argN_type=*/typename std::tuple_element<arg_id, args_type>::type...>(
2444 /*args=*/args, std::get<arg_id>(args)...,
2445 ((void)excess_id, kExcessArg)...);
2446 }
2447 };
2448
2449 // Stores a default-constructed Impl as part of the Action<>'s
2450 // std::function<>. The Impl should be trivial to copy.
2451 template <typename F, typename Impl>
2452 ::testing::Action<F> MakeAction() {
2453 return ::testing::Action<F>(ActionImpl<F, Impl>());
2454 }
2455
2456 // Stores just the one given instance of Impl.
2457 template <typename F, typename Impl>
2458 ::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {
2459 return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));
2460 }
2461
2462 #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
2463 , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
2464 #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
2465 const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
2466 GMOCK_INTERNAL_ARG_UNUSED, , 10)
2467
2468 #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
2469 #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
2470 const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
2471
2472 #define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
2473 #define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
2474 GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
2475
2476 #define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
2477 #define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
2478 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
2479
2480 #define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
2481 #define GMOCK_ACTION_TYPE_PARAMS_(params) \
2482 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
2483
2484 #define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
2485 , param##_type gmock_p##i
2486 #define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
2487 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
2488
2489 #define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
2490 , std::forward<param##_type>(gmock_p##i)
2491 #define GMOCK_ACTION_GVALUE_PARAMS_(params) \
2492 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
2493
2494 #define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
2495 , param(::std::forward<param##_type>(gmock_p##i))
2496 #define GMOCK_ACTION_INIT_PARAMS_(params) \
2497 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
2498
2499 #define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
2500 #define GMOCK_ACTION_FIELD_PARAMS_(params) \
2501 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
2502
2503 #define GMOCK_INTERNAL_ACTION(name, full_name, params) \
2504 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
2505 class full_name { \
2506 public: \
2507 explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
2508 : impl_(std::make_shared<gmock_Impl>( \
2509 GMOCK_ACTION_GVALUE_PARAMS_(params))) { } \
2510 full_name(const full_name&) = default; \
2511 full_name(full_name&&) noexcept = default; \
2512 template <typename F> \
2513 operator ::testing::Action<F>() const { \
2514 return ::testing::internal::MakeAction<F>(impl_); \
2515 } \
2516 private: \
2517 class gmock_Impl { \
2518 public: \
2519 explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
2520 : GMOCK_ACTION_INIT_PARAMS_(params) {} \
2521 template <typename function_type, typename return_type, \
2522 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2523 return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
2524 GMOCK_ACTION_FIELD_PARAMS_(params) \
2525 }; \
2526 std::shared_ptr<const gmock_Impl> impl_; \
2527 }; \
2528 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
2529 inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
2530 GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
2531 return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \
2532 GMOCK_ACTION_GVALUE_PARAMS_(params)); \
2533 } \
2534 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
2535 template <typename function_type, typename return_type, typename args_type, \
2536 GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2537 return_type full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl:: \
2538 gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
2539
2540 } // namespace internal
2541
2542 // Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.
2543 #define ACTION(name) \
2544 class name##Action { \
2545 public: \
2546 explicit name##Action() noexcept {} \
2547 name##Action(const name##Action&) noexcept {} \
2548 template <typename F> \
2549 operator ::testing::Action<F>() const { \
2550 return ::testing::internal::MakeAction<F, gmock_Impl>(); \
2551 } \
2552 private: \
2553 class gmock_Impl { \
2554 public: \
2555 template <typename function_type, typename return_type, \
2556 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2557 return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
2558 }; \
2559 }; \
2560 inline name##Action name() GTEST_MUST_USE_RESULT_; \
2561 inline name##Action name() { return name##Action(); } \
2562 template <typename function_type, typename return_type, typename args_type, \
2563 GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2564 return_type name##Action::gmock_Impl::gmock_PerformImpl( \
2565 GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
2566
2567 #define ACTION_P(name, ...) \
2568 GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
2569
2570 #define ACTION_P2(name, ...) \
2571 GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
2572
2573 #define ACTION_P3(name, ...) \
2574 GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
2575
2576 #define ACTION_P4(name, ...) \
2577 GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
2578
2579 #define ACTION_P5(name, ...) \
2580 GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
2581
2582 #define ACTION_P6(name, ...) \
2583 GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
2584
2585 #define ACTION_P7(name, ...) \
2586 GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
2587
2588 #define ACTION_P8(name, ...) \
2589 GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
2590
2591 #define ACTION_P9(name, ...) \
2592 GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
2593
2594 #define ACTION_P10(name, ...) \
2595 GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
2596
2597 } // namespace testing
2598
2599 #ifdef _MSC_VER
2600 # pragma warning(pop)
2601 #endif
2602
2603 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
2604 // Copyright 2007, Google Inc.
2605 // All rights reserved.
2606 //
2607 // Redistribution and use in source and binary forms, with or without
2608 // modification, are permitted provided that the following conditions are
2609 // met:
2610 //
2611 // * Redistributions of source code must retain the above copyright
2612 // notice, this list of conditions and the following disclaimer.
2613 // * Redistributions in binary form must reproduce the above
2614 // copyright notice, this list of conditions and the following disclaimer
2615 // in the documentation and/or other materials provided with the
2616 // distribution.
2617 // * Neither the name of Google Inc. nor the names of its
2618 // contributors may be used to endorse or promote products derived from
2619 // this software without specific prior written permission.
2620 //
2621 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2622 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2623 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2624 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2625 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2626 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2627 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2628 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2629 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2630 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2631 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2632
2633
2634 // Google Mock - a framework for writing C++ mock classes.
2635 //
2636 // This file implements some commonly used cardinalities. More
2637 // cardinalities can be defined by the user implementing the
2638 // CardinalityInterface interface if necessary.
2639
2640 // GOOGLETEST_CM0002 DO NOT DELETE
2641
2642 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
2643 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
2644
2645 #include <limits.h>
2646 #include <memory>
2647 #include <ostream> // NOLINT
2648
2649 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
2650 /* class A needs to have dll-interface to be used by clients of class B */)
2651
2652 namespace testing {
2653
2654 // To implement a cardinality Foo, define:
2655 // 1. a class FooCardinality that implements the
2656 // CardinalityInterface interface, and
2657 // 2. a factory function that creates a Cardinality object from a
2658 // const FooCardinality*.
2659 //
2660 // The two-level delegation design follows that of Matcher, providing
2661 // consistency for extension developers. It also eases ownership
2662 // management as Cardinality objects can now be copied like plain values.
2663
2664 // The implementation of a cardinality.
2665 class CardinalityInterface {
2666 public:
2667 virtual ~CardinalityInterface() {}
2668
2669 // Conservative estimate on the lower/upper bound of the number of
2670 // calls allowed.
2671 virtual int ConservativeLowerBound() const { return 0; }
2672 virtual int ConservativeUpperBound() const { return INT_MAX; }
2673
2674 // Returns true if and only if call_count calls will satisfy this
2675 // cardinality.
2676 virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
2677
2678 // Returns true if and only if call_count calls will saturate this
2679 // cardinality.
2680 virtual bool IsSaturatedByCallCount(int call_count) const = 0;
2681
2682 // Describes self to an ostream.
2683 virtual void DescribeTo(::std::ostream* os) const = 0;
2684 };
2685
2686 // A Cardinality is a copyable and IMMUTABLE (except by assignment)
2687 // object that specifies how many times a mock function is expected to
2688 // be called. The implementation of Cardinality is just a std::shared_ptr
2689 // to const CardinalityInterface. Don't inherit from Cardinality!
2690 class GTEST_API_ Cardinality {
2691 public:
2692 // Constructs a null cardinality. Needed for storing Cardinality
2693 // objects in STL containers.
2694 Cardinality() {}
2695
2696 // Constructs a Cardinality from its implementation.
2697 explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}
2698
2699 // Conservative estimate on the lower/upper bound of the number of
2700 // calls allowed.
2701 int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); }
2702 int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); }
2703
2704 // Returns true if and only if call_count calls will satisfy this
2705 // cardinality.
2706 bool IsSatisfiedByCallCount(int call_count) const {
2707 return impl_->IsSatisfiedByCallCount(call_count);
2708 }
2709
2710 // Returns true if and only if call_count calls will saturate this
2711 // cardinality.
2712 bool IsSaturatedByCallCount(int call_count) const {
2713 return impl_->IsSaturatedByCallCount(call_count);
2714 }
2715
2716 // Returns true if and only if call_count calls will over-saturate this
2717 // cardinality, i.e. exceed the maximum number of allowed calls.
2718 bool IsOverSaturatedByCallCount(int call_count) const {
2719 return impl_->IsSaturatedByCallCount(call_count) &&
2720 !impl_->IsSatisfiedByCallCount(call_count);
2721 }
2722
2723 // Describes self to an ostream
2724 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
2725
2726 // Describes the given actual call count to an ostream.
2727 static void DescribeActualCallCountTo(int actual_call_count,
2728 ::std::ostream* os);
2729
2730 private:
2731 std::shared_ptr<const CardinalityInterface> impl_;
2732 };
2733
2734 // Creates a cardinality that allows at least n calls.
2735 GTEST_API_ Cardinality AtLeast(int n);
2736
2737 // Creates a cardinality that allows at most n calls.
2738 GTEST_API_ Cardinality AtMost(int n);
2739
2740 // Creates a cardinality that allows any number of calls.
2741 GTEST_API_ Cardinality AnyNumber();
2742
2743 // Creates a cardinality that allows between min and max calls.
2744 GTEST_API_ Cardinality Between(int min, int max);
2745
2746 // Creates a cardinality that allows exactly n calls.
2747 GTEST_API_ Cardinality Exactly(int n);
2748
2749 // Creates a cardinality from its implementation.
2750 inline Cardinality MakeCardinality(const CardinalityInterface* c) {
2751 return Cardinality(c);
2752 }
2753
2754 } // namespace testing
2755
2756 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
2757
2758 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
2759 // Copyright 2007, Google Inc.
2760 // All rights reserved.
2761 //
2762 // Redistribution and use in source and binary forms, with or without
2763 // modification, are permitted provided that the following conditions are
2764 // met:
2765 //
2766 // * Redistributions of source code must retain the above copyright
2767 // notice, this list of conditions and the following disclaimer.
2768 // * Redistributions in binary form must reproduce the above
2769 // copyright notice, this list of conditions and the following disclaimer
2770 // in the documentation and/or other materials provided with the
2771 // distribution.
2772 // * Neither the name of Google Inc. nor the names of its
2773 // contributors may be used to endorse or promote products derived from
2774 // this software without specific prior written permission.
2775 //
2776 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2777 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2778 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2779 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2780 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2781 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2782 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2783 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2784 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2785 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2786 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2787
2788 // Google Mock - a framework for writing C++ mock classes.
2789 //
2790 // This file implements MOCK_METHOD.
2791
2792 // GOOGLETEST_CM0002 DO NOT DELETE
2793
2794 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
2795 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
2796
2797 #include <type_traits> // IWYU pragma: keep
2798 #include <utility> // IWYU pragma: keep
2799
2800 // Copyright 2007, Google Inc.
2801 // All rights reserved.
2802 //
2803 // Redistribution and use in source and binary forms, with or without
2804 // modification, are permitted provided that the following conditions are
2805 // met:
2806 //
2807 // * Redistributions of source code must retain the above copyright
2808 // notice, this list of conditions and the following disclaimer.
2809 // * Redistributions in binary form must reproduce the above
2810 // copyright notice, this list of conditions and the following disclaimer
2811 // in the documentation and/or other materials provided with the
2812 // distribution.
2813 // * Neither the name of Google Inc. nor the names of its
2814 // contributors may be used to endorse or promote products derived from
2815 // this software without specific prior written permission.
2816 //
2817 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2818 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2819 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2820 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2821 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2822 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2823 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2824 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2825 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2826 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2827 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
2829
2830 // Google Mock - a framework for writing C++ mock classes.
2831 //
2832 // This file implements the ON_CALL() and EXPECT_CALL() macros.
2833 //
2834 // A user can use the ON_CALL() macro to specify the default action of
2835 // a mock method. The syntax is:
2836 //
2837 // ON_CALL(mock_object, Method(argument-matchers))
2838 // .With(multi-argument-matcher)
2839 // .WillByDefault(action);
2840 //
2841 // where the .With() clause is optional.
2842 //
2843 // A user can use the EXPECT_CALL() macro to specify an expectation on
2844 // a mock method. The syntax is:
2845 //
2846 // EXPECT_CALL(mock_object, Method(argument-matchers))
2847 // .With(multi-argument-matchers)
2848 // .Times(cardinality)
2849 // .InSequence(sequences)
2850 // .After(expectations)
2851 // .WillOnce(action)
2852 // .WillRepeatedly(action)
2853 // .RetiresOnSaturation();
2854 //
2855 // where all clauses are optional, and .InSequence()/.After()/
2856 // .WillOnce() can appear any number of times.
2857
2858 // GOOGLETEST_CM0002 DO NOT DELETE
2859
2860 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
2861 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
2862
2863 #include <functional>
2864 #include <map>
2865 #include <memory>
2866 #include <set>
2867 #include <sstream>
2868 #include <string>
2869 #include <type_traits>
2870 #include <utility>
2871 #include <vector>
2872 // Copyright 2007, Google Inc.
2873 // All rights reserved.
2874 //
2875 // Redistribution and use in source and binary forms, with or without
2876 // modification, are permitted provided that the following conditions are
2877 // met:
2878 //
2879 // * Redistributions of source code must retain the above copyright
2880 // notice, this list of conditions and the following disclaimer.
2881 // * Redistributions in binary form must reproduce the above
2882 // copyright notice, this list of conditions and the following disclaimer
2883 // in the documentation and/or other materials provided with the
2884 // distribution.
2885 // * Neither the name of Google Inc. nor the names of its
2886 // contributors may be used to endorse or promote products derived from
2887 // this software without specific prior written permission.
2888 //
2889 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2890 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2891 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2892 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2893 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2894 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2895 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2896 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2897 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2898 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2899 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2900
2901
2902 // Google Mock - a framework for writing C++ mock classes.
2903 //
2904 // The MATCHER* family of macros can be used in a namespace scope to
2905 // define custom matchers easily.
2906 //
2907 // Basic Usage
2908 // ===========
2909 //
2910 // The syntax
2911 //
2912 // MATCHER(name, description_string) { statements; }
2913 //
2914 // defines a matcher with the given name that executes the statements,
2915 // which must return a bool to indicate if the match succeeds. Inside
2916 // the statements, you can refer to the value being matched by 'arg',
2917 // and refer to its type by 'arg_type'.
2918 //
2919 // The description string documents what the matcher does, and is used
2920 // to generate the failure message when the match fails. Since a
2921 // MATCHER() is usually defined in a header file shared by multiple
2922 // C++ source files, we require the description to be a C-string
2923 // literal to avoid possible side effects. It can be empty, in which
2924 // case we'll use the sequence of words in the matcher name as the
2925 // description.
2926 //
2927 // For example:
2928 //
2929 // MATCHER(IsEven, "") { return (arg % 2) == 0; }
2930 //
2931 // allows you to write
2932 //
2933 // // Expects mock_foo.Bar(n) to be called where n is even.
2934 // EXPECT_CALL(mock_foo, Bar(IsEven()));
2935 //
2936 // or,
2937 //
2938 // // Verifies that the value of some_expression is even.
2939 // EXPECT_THAT(some_expression, IsEven());
2940 //
2941 // If the above assertion fails, it will print something like:
2942 //
2943 // Value of: some_expression
2944 // Expected: is even
2945 // Actual: 7
2946 //
2947 // where the description "is even" is automatically calculated from the
2948 // matcher name IsEven.
2949 //
2950 // Argument Type
2951 // =============
2952 //
2953 // Note that the type of the value being matched (arg_type) is
2954 // determined by the context in which you use the matcher and is
2955 // supplied to you by the compiler, so you don't need to worry about
2956 // declaring it (nor can you). This allows the matcher to be
2957 // polymorphic. For example, IsEven() can be used to match any type
2958 // where the value of "(arg % 2) == 0" can be implicitly converted to
2959 // a bool. In the "Bar(IsEven())" example above, if method Bar()
2960 // takes an int, 'arg_type' will be int; if it takes an unsigned long,
2961 // 'arg_type' will be unsigned long; and so on.
2962 //
2963 // Parameterizing Matchers
2964 // =======================
2965 //
2966 // Sometimes you'll want to parameterize the matcher. For that you
2967 // can use another macro:
2968 //
2969 // MATCHER_P(name, param_name, description_string) { statements; }
2970 //
2971 // For example:
2972 //
2973 // MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
2974 //
2975 // will allow you to write:
2976 //
2977 // EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
2978 //
2979 // which may lead to this message (assuming n is 10):
2980 //
2981 // Value of: Blah("a")
2982 // Expected: has absolute value 10
2983 // Actual: -9
2984 //
2985 // Note that both the matcher description and its parameter are
2986 // printed, making the message human-friendly.
2987 //
2988 // In the matcher definition body, you can write 'foo_type' to
2989 // reference the type of a parameter named 'foo'. For example, in the
2990 // body of MATCHER_P(HasAbsoluteValue, value) above, you can write
2991 // 'value_type' to refer to the type of 'value'.
2992 //
2993 // We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
2994 // support multi-parameter matchers.
2995 //
2996 // Describing Parameterized Matchers
2997 // =================================
2998 //
2999 // The last argument to MATCHER*() is a string-typed expression. The
3000 // expression can reference all of the matcher's parameters and a
3001 // special bool-typed variable named 'negation'. When 'negation' is
3002 // false, the expression should evaluate to the matcher's description;
3003 // otherwise it should evaluate to the description of the negation of
3004 // the matcher. For example,
3005 //
3006 // using testing::PrintToString;
3007 //
3008 // MATCHER_P2(InClosedRange, low, hi,
3009 // std::string(negation ? "is not" : "is") + " in range [" +
3010 // PrintToString(low) + ", " + PrintToString(hi) + "]") {
3011 // return low <= arg && arg <= hi;
3012 // }
3013 // ...
3014 // EXPECT_THAT(3, InClosedRange(4, 6));
3015 // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
3016 //
3017 // would generate two failures that contain the text:
3018 //
3019 // Expected: is in range [4, 6]
3020 // ...
3021 // Expected: is not in range [2, 4]
3022 //
3023 // If you specify "" as the description, the failure message will
3024 // contain the sequence of words in the matcher name followed by the
3025 // parameter values printed as a tuple. For example,
3026 //
3027 // MATCHER_P2(InClosedRange, low, hi, "") { ... }
3028 // ...
3029 // EXPECT_THAT(3, InClosedRange(4, 6));
3030 // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
3031 //
3032 // would generate two failures that contain the text:
3033 //
3034 // Expected: in closed range (4, 6)
3035 // ...
3036 // Expected: not (in closed range (2, 4))
3037 //
3038 // Types of Matcher Parameters
3039 // ===========================
3040 //
3041 // For the purpose of typing, you can view
3042 //
3043 // MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
3044 //
3045 // as shorthand for
3046 //
3047 // template <typename p1_type, ..., typename pk_type>
3048 // FooMatcherPk<p1_type, ..., pk_type>
3049 // Foo(p1_type p1, ..., pk_type pk) { ... }
3050 //
3051 // When you write Foo(v1, ..., vk), the compiler infers the types of
3052 // the parameters v1, ..., and vk for you. If you are not happy with
3053 // the result of the type inference, you can specify the types by
3054 // explicitly instantiating the template, as in Foo<long, bool>(5,
3055 // false). As said earlier, you don't get to (or need to) specify
3056 // 'arg_type' as that's determined by the context in which the matcher
3057 // is used. You can assign the result of expression Foo(p1, ..., pk)
3058 // to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
3059 // can be useful when composing matchers.
3060 //
3061 // While you can instantiate a matcher template with reference types,
3062 // passing the parameters by pointer usually makes your code more
3063 // readable. If, however, you still want to pass a parameter by
3064 // reference, be aware that in the failure message generated by the
3065 // matcher you will see the value of the referenced object but not its
3066 // address.
3067 //
3068 // Explaining Match Results
3069 // ========================
3070 //
3071 // Sometimes the matcher description alone isn't enough to explain why
3072 // the match has failed or succeeded. For example, when expecting a
3073 // long string, it can be very helpful to also print the diff between
3074 // the expected string and the actual one. To achieve that, you can
3075 // optionally stream additional information to a special variable
3076 // named result_listener, whose type is a pointer to class
3077 // MatchResultListener:
3078 //
3079 // MATCHER_P(EqualsLongString, str, "") {
3080 // if (arg == str) return true;
3081 //
3082 // *result_listener << "the difference: "
3083 /// << DiffStrings(str, arg);
3084 // return false;
3085 // }
3086 //
3087 // Overloading Matchers
3088 // ====================
3089 //
3090 // You can overload matchers with different numbers of parameters:
3091 //
3092 // MATCHER_P(Blah, a, description_string1) { ... }
3093 // MATCHER_P2(Blah, a, b, description_string2) { ... }
3094 //
3095 // Caveats
3096 // =======
3097 //
3098 // When defining a new matcher, you should also consider implementing
3099 // MatcherInterface or using MakePolymorphicMatcher(). These
3100 // approaches require more work than the MATCHER* macros, but also
3101 // give you more control on the types of the value being matched and
3102 // the matcher parameters, which may leads to better compiler error
3103 // messages when the matcher is used wrong. They also allow
3104 // overloading matchers based on parameter types (as opposed to just
3105 // based on the number of parameters).
3106 //
3107 // MATCHER*() can only be used in a namespace scope as templates cannot be
3108 // declared inside of a local class.
3109 //
3110 // More Information
3111 // ================
3112 //
3113 // To learn more about using these macros, please search for 'MATCHER'
3114 // on
3115 // https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
3116 //
3117 // This file also implements some commonly used argument matchers. More
3118 // matchers can be defined by the user implementing the
3119 // MatcherInterface<T> interface if necessary.
3120 //
3121 // See googletest/include/gtest/gtest-matchers.h for the definition of class
3122 // Matcher, class MatcherInterface, and others.
3123
3124 // GOOGLETEST_CM0002 DO NOT DELETE
3125
3126 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
3127 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
3128
3129 #include <algorithm>
3130 #include <cmath>
3131 #include <initializer_list>
3132 #include <iterator>
3133 #include <limits>
3134 #include <memory>
3135 #include <ostream> // NOLINT
3136 #include <sstream>
3137 #include <string>
3138 #include <type_traits>
3139 #include <utility>
3140 #include <vector>
3141
3142
3143 // MSVC warning C5046 is new as of VS2017 version 15.8.
3144 #if defined(_MSC_VER) && _MSC_VER >= 1915
3145 #define GMOCK_MAYBE_5046_ 5046
3146 #else
3147 #define GMOCK_MAYBE_5046_
3148 #endif
3149
3150 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
3151 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by
3152 clients of class B */
3153 /* Symbol involving type with internal linkage not defined */)
3154
3155 namespace testing {
3156
3157 // To implement a matcher Foo for type T, define:
3158 // 1. a class FooMatcherImpl that implements the
3159 // MatcherInterface<T> interface, and
3160 // 2. a factory function that creates a Matcher<T> object from a
3161 // FooMatcherImpl*.
3162 //
3163 // The two-level delegation design makes it possible to allow a user
3164 // to write "v" instead of "Eq(v)" where a Matcher is expected, which
3165 // is impossible if we pass matchers by pointers. It also eases
3166 // ownership management as Matcher objects can now be copied like
3167 // plain values.
3168
3169 // A match result listener that stores the explanation in a string.
3170 class StringMatchResultListener : public MatchResultListener {
3171 public:
3172 StringMatchResultListener() : MatchResultListener(&ss_) {}
3173
3174 // Returns the explanation accumulated so far.
3175 std::string str() const { return ss_.str(); }
3176
3177 // Clears the explanation accumulated so far.
3178 void Clear() { ss_.str(""); }
3179
3180 private:
3181 ::std::stringstream ss_;
3182
3183 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
3184 };
3185
3186 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
3187 // and MUST NOT BE USED IN USER CODE!!!
3188 namespace internal {
3189
3190 // The MatcherCastImpl class template is a helper for implementing
3191 // MatcherCast(). We need this helper in order to partially
3192 // specialize the implementation of MatcherCast() (C++ allows
3193 // class/struct templates to be partially specialized, but not
3194 // function templates.).
3195
3196 // This general version is used when MatcherCast()'s argument is a
3197 // polymorphic matcher (i.e. something that can be converted to a
3198 // Matcher but is not one yet; for example, Eq(value)) or a value (for
3199 // example, "hello").
3200 template <typename T, typename M>
3201 class MatcherCastImpl {
3202 public:
3203 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
3204 // M can be a polymorphic matcher, in which case we want to use
3205 // its conversion operator to create Matcher<T>. Or it can be a value
3206 // that should be passed to the Matcher<T>'s constructor.
3207 //
3208 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
3209 // polymorphic matcher because it'll be ambiguous if T has an implicit
3210 // constructor from M (this usually happens when T has an implicit
3211 // constructor from any type).
3212 //
3213 // It won't work to unconditionally implicit_cast
3214 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
3215 // a user-defined conversion from M to T if one exists (assuming M is
3216 // a value).
3217 return CastImpl(polymorphic_matcher_or_value,
3218 std::is_convertible<M, Matcher<T>>{},
3219 std::is_convertible<M, T>{});
3220 }
3221
3222 private:
3223 template <bool Ignore>
3224 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
3225 std::true_type /* convertible_to_matcher */,
3226 std::integral_constant<bool, Ignore>) {
3227 // M is implicitly convertible to Matcher<T>, which means that either
3228 // M is a polymorphic matcher or Matcher<T> has an implicit constructor
3229 // from M. In both cases using the implicit conversion will produce a
3230 // matcher.
3231 //
3232 // Even if T has an implicit constructor from M, it won't be called because
3233 // creating Matcher<T> would require a chain of two user-defined conversions
3234 // (first to create T from M and then to create Matcher<T> from T).
3235 return polymorphic_matcher_or_value;
3236 }
3237
3238 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
3239 // matcher. It's a value of a type implicitly convertible to T. Use direct
3240 // initialization to create a matcher.
3241 static Matcher<T> CastImpl(const M& value,
3242 std::false_type /* convertible_to_matcher */,
3243 std::true_type /* convertible_to_T */) {
3244 return Matcher<T>(ImplicitCast_<T>(value));
3245 }
3246
3247 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
3248 // polymorphic matcher Eq(value) in this case.
3249 //
3250 // Note that we first attempt to perform an implicit cast on the value and
3251 // only fall back to the polymorphic Eq() matcher afterwards because the
3252 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
3253 // which might be undefined even when Rhs is implicitly convertible to Lhs
3254 // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
3255 //
3256 // We don't define this method inline as we need the declaration of Eq().
3257 static Matcher<T> CastImpl(const M& value,
3258 std::false_type /* convertible_to_matcher */,
3259 std::false_type /* convertible_to_T */);
3260 };
3261
3262 // This more specialized version is used when MatcherCast()'s argument
3263 // is already a Matcher. This only compiles when type T can be
3264 // statically converted to type U.
3265 template <typename T, typename U>
3266 class MatcherCastImpl<T, Matcher<U> > {
3267 public:
3268 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
3269 return Matcher<T>(new Impl(source_matcher));
3270 }
3271
3272 private:
3273 class Impl : public MatcherInterface<T> {
3274 public:
3275 explicit Impl(const Matcher<U>& source_matcher)
3276 : source_matcher_(source_matcher) {}
3277
3278 // We delegate the matching logic to the source matcher.
3279 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
3280 using FromType = typename std::remove_cv<typename std::remove_pointer<
3281 typename std::remove_reference<T>::type>::type>::type;
3282 using ToType = typename std::remove_cv<typename std::remove_pointer<
3283 typename std::remove_reference<U>::type>::type>::type;
3284 // Do not allow implicitly converting base*/& to derived*/&.
3285 static_assert(
3286 // Do not trigger if only one of them is a pointer. That implies a
3287 // regular conversion and not a down_cast.
3288 (std::is_pointer<typename std::remove_reference<T>::type>::value !=
3289 std::is_pointer<typename std::remove_reference<U>::type>::value) ||
3290 std::is_same<FromType, ToType>::value ||
3291 !std::is_base_of<FromType, ToType>::value,
3292 "Can't implicitly convert from <base> to <derived>");
3293
3294 // Do the cast to `U` explicitly if necessary.
3295 // Otherwise, let implicit conversions do the trick.
3296 using CastType =
3297 typename std::conditional<std::is_convertible<T&, const U&>::value,
3298 T&, U>::type;
3299
3300 return source_matcher_.MatchAndExplain(static_cast<CastType>(x),
3301 listener);
3302 }
3303
3304 void DescribeTo(::std::ostream* os) const override {
3305 source_matcher_.DescribeTo(os);
3306 }
3307
3308 void DescribeNegationTo(::std::ostream* os) const override {
3309 source_matcher_.DescribeNegationTo(os);
3310 }
3311
3312 private:
3313 const Matcher<U> source_matcher_;
3314 };
3315 };
3316
3317 // This even more specialized version is used for efficiently casting
3318 // a matcher to its own type.
3319 template <typename T>
3320 class MatcherCastImpl<T, Matcher<T> > {
3321 public:
3322 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
3323 };
3324
3325 // Template specialization for parameterless Matcher.
3326 template <typename Derived>
3327 class MatcherBaseImpl {
3328 public:
3329 MatcherBaseImpl() = default;
3330
3331 template <typename T>
3332 operator ::testing::Matcher<T>() const { // NOLINT(runtime/explicit)
3333 return ::testing::Matcher<T>(new
3334 typename Derived::template gmock_Impl<T>());
3335 }
3336 };
3337
3338 // Template specialization for Matcher with parameters.
3339 template <template <typename...> class Derived, typename... Ts>
3340 class MatcherBaseImpl<Derived<Ts...>> {
3341 public:
3342 // Mark the constructor explicit for single argument T to avoid implicit
3343 // conversions.
3344 template <typename E = std::enable_if<sizeof...(Ts) == 1>,
3345 typename E::type* = nullptr>
3346 explicit MatcherBaseImpl(Ts... params)
3347 : params_(std::forward<Ts>(params)...) {}
3348 template <typename E = std::enable_if<sizeof...(Ts) != 1>,
3349 typename = typename E::type>
3350 MatcherBaseImpl(Ts... params) // NOLINT
3351 : params_(std::forward<Ts>(params)...) {}
3352
3353 template <typename F>
3354 operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit)
3355 return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{});
3356 }
3357
3358 private:
3359 template <typename F, std::size_t... tuple_ids>
3360 ::testing::Matcher<F> Apply(IndexSequence<tuple_ids...>) const {
3361 return ::testing::Matcher<F>(
3362 new typename Derived<Ts...>::template gmock_Impl<F>(
3363 std::get<tuple_ids>(params_)...));
3364 }
3365
3366 const std::tuple<Ts...> params_;
3367 };
3368
3369 } // namespace internal
3370
3371 // In order to be safe and clear, casting between different matcher
3372 // types is done explicitly via MatcherCast<T>(m), which takes a
3373 // matcher m and returns a Matcher<T>. It compiles only when T can be
3374 // statically converted to the argument type of m.
3375 template <typename T, typename M>
3376 inline Matcher<T> MatcherCast(const M& matcher) {
3377 return internal::MatcherCastImpl<T, M>::Cast(matcher);
3378 }
3379
3380 // This overload handles polymorphic matchers and values only since
3381 // monomorphic matchers are handled by the next one.
3382 template <typename T, typename M>
3383 inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {
3384 return MatcherCast<T>(polymorphic_matcher_or_value);
3385 }
3386
3387 // This overload handles monomorphic matchers.
3388 //
3389 // In general, if type T can be implicitly converted to type U, we can
3390 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
3391 // contravariant): just keep a copy of the original Matcher<U>, convert the
3392 // argument from type T to U, and then pass it to the underlying Matcher<U>.
3393 // The only exception is when U is a reference and T is not, as the
3394 // underlying Matcher<U> may be interested in the argument's address, which
3395 // is not preserved in the conversion from T to U.
3396 template <typename T, typename U>
3397 inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
3398 // Enforce that T can be implicitly converted to U.
3399 static_assert(std::is_convertible<const T&, const U&>::value,
3400 "T must be implicitly convertible to U");
3401 // Enforce that we are not converting a non-reference type T to a reference
3402 // type U.
3403 GTEST_COMPILE_ASSERT_(
3404 std::is_reference<T>::value || !std::is_reference<U>::value,
3405 cannot_convert_non_reference_arg_to_reference);
3406 // In case both T and U are arithmetic types, enforce that the
3407 // conversion is not lossy.
3408 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
3409 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
3410 constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
3411 constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
3412 GTEST_COMPILE_ASSERT_(
3413 kTIsOther || kUIsOther ||
3414 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
3415 conversion_of_arithmetic_types_must_be_lossless);
3416 return MatcherCast<T>(matcher);
3417 }
3418
3419 // A<T>() returns a matcher that matches any value of type T.
3420 template <typename T>
3421 Matcher<T> A();
3422
3423 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
3424 // and MUST NOT BE USED IN USER CODE!!!
3425 namespace internal {
3426
3427 // If the explanation is not empty, prints it to the ostream.
3428 inline void PrintIfNotEmpty(const std::string& explanation,
3429 ::std::ostream* os) {
3430 if (explanation != "" && os != nullptr) {
3431 *os << ", " << explanation;
3432 }
3433 }
3434
3435 // Returns true if the given type name is easy to read by a human.
3436 // This is used to decide whether printing the type of a value might
3437 // be helpful.
3438 inline bool IsReadableTypeName(const std::string& type_name) {
3439 // We consider a type name readable if it's short or doesn't contain
3440 // a template or function type.
3441 return (type_name.length() <= 20 ||
3442 type_name.find_first_of("<(") == std::string::npos);
3443 }
3444
3445 // Matches the value against the given matcher, prints the value and explains
3446 // the match result to the listener. Returns the match result.
3447 // 'listener' must not be NULL.
3448 // Value cannot be passed by const reference, because some matchers take a
3449 // non-const argument.
3450 template <typename Value, typename T>
3451 bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
3452 MatchResultListener* listener) {
3453 if (!listener->IsInterested()) {
3454 // If the listener is not interested, we do not need to construct the
3455 // inner explanation.
3456 return matcher.Matches(value);
3457 }
3458
3459 StringMatchResultListener inner_listener;
3460 const bool match = matcher.MatchAndExplain(value, &inner_listener);
3461
3462 UniversalPrint(value, listener->stream());
3463 #if GTEST_HAS_RTTI
3464 const std::string& type_name = GetTypeName<Value>();
3465 if (IsReadableTypeName(type_name))
3466 *listener->stream() << " (of type " << type_name << ")";
3467 #endif
3468 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3469
3470 return match;
3471 }
3472
3473 // An internal helper class for doing compile-time loop on a tuple's
3474 // fields.
3475 template <size_t N>
3476 class TuplePrefix {
3477 public:
3478 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
3479 // if and only if the first N fields of matcher_tuple matches
3480 // the first N fields of value_tuple, respectively.
3481 template <typename MatcherTuple, typename ValueTuple>
3482 static bool Matches(const MatcherTuple& matcher_tuple,
3483 const ValueTuple& value_tuple) {
3484 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) &&
3485 std::get<N - 1>(matcher_tuple).Matches(std::get<N - 1>(value_tuple));
3486 }
3487
3488 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
3489 // describes failures in matching the first N fields of matchers
3490 // against the first N fields of values. If there is no failure,
3491 // nothing will be streamed to os.
3492 template <typename MatcherTuple, typename ValueTuple>
3493 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
3494 const ValueTuple& values,
3495 ::std::ostream* os) {
3496 // First, describes failures in the first N - 1 fields.
3497 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
3498
3499 // Then describes the failure (if any) in the (N - 1)-th (0-based)
3500 // field.
3501 typename std::tuple_element<N - 1, MatcherTuple>::type matcher =
3502 std::get<N - 1>(matchers);
3503 typedef typename std::tuple_element<N - 1, ValueTuple>::type Value;
3504 const Value& value = std::get<N - 1>(values);
3505 StringMatchResultListener listener;
3506 if (!matcher.MatchAndExplain(value, &listener)) {
3507 *os << " Expected arg #" << N - 1 << ": ";
3508 std::get<N - 1>(matchers).DescribeTo(os);
3509 *os << "\n Actual: ";
3510 // We remove the reference in type Value to prevent the
3511 // universal printer from printing the address of value, which
3512 // isn't interesting to the user most of the time. The
3513 // matcher's MatchAndExplain() method handles the case when
3514 // the address is interesting.
3515 internal::UniversalPrint(value, os);
3516 PrintIfNotEmpty(listener.str(), os);
3517 *os << "\n";
3518 }
3519 }
3520 };
3521
3522 // The base case.
3523 template <>
3524 class TuplePrefix<0> {
3525 public:
3526 template <typename MatcherTuple, typename ValueTuple>
3527 static bool Matches(const MatcherTuple& /* matcher_tuple */,
3528 const ValueTuple& /* value_tuple */) {
3529 return true;
3530 }
3531
3532 template <typename MatcherTuple, typename ValueTuple>
3533 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
3534 const ValueTuple& /* values */,
3535 ::std::ostream* /* os */) {}
3536 };
3537
3538 // TupleMatches(matcher_tuple, value_tuple) returns true if and only if
3539 // all matchers in matcher_tuple match the corresponding fields in
3540 // value_tuple. It is a compiler error if matcher_tuple and
3541 // value_tuple have different number of fields or incompatible field
3542 // types.
3543 template <typename MatcherTuple, typename ValueTuple>
3544 bool TupleMatches(const MatcherTuple& matcher_tuple,
3545 const ValueTuple& value_tuple) {
3546 // Makes sure that matcher_tuple and value_tuple have the same
3547 // number of fields.
3548 GTEST_COMPILE_ASSERT_(std::tuple_size<MatcherTuple>::value ==
3549 std::tuple_size<ValueTuple>::value,
3550 matcher_and_value_have_different_numbers_of_fields);
3551 return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple,
3552 value_tuple);
3553 }
3554
3555 // Describes failures in matching matchers against values. If there
3556 // is no failure, nothing will be streamed to os.
3557 template <typename MatcherTuple, typename ValueTuple>
3558 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
3559 const ValueTuple& values,
3560 ::std::ostream* os) {
3561 TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
3562 matchers, values, os);
3563 }
3564
3565 // TransformTupleValues and its helper.
3566 //
3567 // TransformTupleValuesHelper hides the internal machinery that
3568 // TransformTupleValues uses to implement a tuple traversal.
3569 template <typename Tuple, typename Func, typename OutIter>
3570 class TransformTupleValuesHelper {
3571 private:
3572 typedef ::std::tuple_size<Tuple> TupleSize;
3573
3574 public:
3575 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
3576 // Returns the final value of 'out' in case the caller needs it.
3577 static OutIter Run(Func f, const Tuple& t, OutIter out) {
3578 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
3579 }
3580
3581 private:
3582 template <typename Tup, size_t kRemainingSize>
3583 struct IterateOverTuple {
3584 OutIter operator() (Func f, const Tup& t, OutIter out) const {
3585 *out++ = f(::std::get<TupleSize::value - kRemainingSize>(t));
3586 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
3587 }
3588 };
3589 template <typename Tup>
3590 struct IterateOverTuple<Tup, 0> {
3591 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
3592 return out;
3593 }
3594 };
3595 };
3596
3597 // Successively invokes 'f(element)' on each element of the tuple 't',
3598 // appending each result to the 'out' iterator. Returns the final value
3599 // of 'out'.
3600 template <typename Tuple, typename Func, typename OutIter>
3601 OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
3602 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
3603 }
3604
3605 // Implements _, a matcher that matches any value of any
3606 // type. This is a polymorphic matcher, so we need a template type
3607 // conversion operator to make it appearing as a Matcher<T> for any
3608 // type T.
3609 class AnythingMatcher {
3610 public:
3611 using is_gtest_matcher = void;
3612
3613 template <typename T>
3614 bool MatchAndExplain(const T& /* x */, std::ostream* /* listener */) const {
3615 return true;
3616 }
3617 void DescribeTo(std::ostream* os) const { *os << "is anything"; }
3618 void DescribeNegationTo(::std::ostream* os) const {
3619 // This is mostly for completeness' sake, as it's not very useful
3620 // to write Not(A<bool>()). However we cannot completely rule out
3621 // such a possibility, and it doesn't hurt to be prepared.
3622 *os << "never matches";
3623 }
3624 };
3625
3626 // Implements the polymorphic IsNull() matcher, which matches any raw or smart
3627 // pointer that is NULL.
3628 class IsNullMatcher {
3629 public:
3630 template <typename Pointer>
3631 bool MatchAndExplain(const Pointer& p,
3632 MatchResultListener* /* listener */) const {
3633 return p == nullptr;
3634 }
3635
3636 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
3637 void DescribeNegationTo(::std::ostream* os) const {
3638 *os << "isn't NULL";
3639 }
3640 };
3641
3642 // Implements the polymorphic NotNull() matcher, which matches any raw or smart
3643 // pointer that is not NULL.
3644 class NotNullMatcher {
3645 public:
3646 template <typename Pointer>
3647 bool MatchAndExplain(const Pointer& p,
3648 MatchResultListener* /* listener */) const {
3649 return p != nullptr;
3650 }
3651
3652 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
3653 void DescribeNegationTo(::std::ostream* os) const {
3654 *os << "is NULL";
3655 }
3656 };
3657
3658 // Ref(variable) matches any argument that is a reference to
3659 // 'variable'. This matcher is polymorphic as it can match any
3660 // super type of the type of 'variable'.
3661 //
3662 // The RefMatcher template class implements Ref(variable). It can
3663 // only be instantiated with a reference type. This prevents a user
3664 // from mistakenly using Ref(x) to match a non-reference function
3665 // argument. For example, the following will righteously cause a
3666 // compiler error:
3667 //
3668 // int n;
3669 // Matcher<int> m1 = Ref(n); // This won't compile.
3670 // Matcher<int&> m2 = Ref(n); // This will compile.
3671 template <typename T>
3672 class RefMatcher;
3673
3674 template <typename T>
3675 class RefMatcher<T&> {
3676 // Google Mock is a generic framework and thus needs to support
3677 // mocking any function types, including those that take non-const
3678 // reference arguments. Therefore the template parameter T (and
3679 // Super below) can be instantiated to either a const type or a
3680 // non-const type.
3681 public:
3682 // RefMatcher() takes a T& instead of const T&, as we want the
3683 // compiler to catch using Ref(const_value) as a matcher for a
3684 // non-const reference.
3685 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
3686
3687 template <typename Super>
3688 operator Matcher<Super&>() const {
3689 // By passing object_ (type T&) to Impl(), which expects a Super&,
3690 // we make sure that Super is a super type of T. In particular,
3691 // this catches using Ref(const_value) as a matcher for a
3692 // non-const reference, as you cannot implicitly convert a const
3693 // reference to a non-const reference.
3694 return MakeMatcher(new Impl<Super>(object_));
3695 }
3696
3697 private:
3698 template <typename Super>
3699 class Impl : public MatcherInterface<Super&> {
3700 public:
3701 explicit Impl(Super& x) : object_(x) {} // NOLINT
3702
3703 // MatchAndExplain() takes a Super& (as opposed to const Super&)
3704 // in order to match the interface MatcherInterface<Super&>.
3705 bool MatchAndExplain(Super& x,
3706 MatchResultListener* listener) const override {
3707 *listener << "which is located @" << static_cast<const void*>(&x);
3708 return &x == &object_;
3709 }
3710
3711 void DescribeTo(::std::ostream* os) const override {
3712 *os << "references the variable ";
3713 UniversalPrinter<Super&>::Print(object_, os);
3714 }
3715
3716 void DescribeNegationTo(::std::ostream* os) const override {
3717 *os << "does not reference the variable ";
3718 UniversalPrinter<Super&>::Print(object_, os);
3719 }
3720
3721 private:
3722 const Super& object_;
3723 };
3724
3725 T& object_;
3726 };
3727
3728 // Polymorphic helper functions for narrow and wide string matchers.
3729 inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
3730 return String::CaseInsensitiveCStringEquals(lhs, rhs);
3731 }
3732
3733 inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
3734 const wchar_t* rhs) {
3735 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
3736 }
3737
3738 // String comparison for narrow or wide strings that can have embedded NUL
3739 // characters.
3740 template <typename StringType>
3741 bool CaseInsensitiveStringEquals(const StringType& s1,
3742 const StringType& s2) {
3743 // Are the heads equal?
3744 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
3745 return false;
3746 }
3747
3748 // Skip the equal heads.
3749 const typename StringType::value_type nul = 0;
3750 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
3751
3752 // Are we at the end of either s1 or s2?
3753 if (i1 == StringType::npos || i2 == StringType::npos) {
3754 return i1 == i2;
3755 }
3756
3757 // Are the tails equal?
3758 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
3759 }
3760
3761 // String matchers.
3762
3763 // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
3764 template <typename StringType>
3765 class StrEqualityMatcher {
3766 public:
3767 StrEqualityMatcher(StringType str, bool expect_eq, bool case_sensitive)
3768 : string_(std::move(str)),
3769 expect_eq_(expect_eq),
3770 case_sensitive_(case_sensitive) {}
3771
3772 #if GTEST_INTERNAL_HAS_STRING_VIEW
3773 bool MatchAndExplain(const internal::StringView& s,
3774 MatchResultListener* listener) const {
3775 // This should fail to compile if StringView is used with wide
3776 // strings.
3777 const StringType& str = std::string(s);
3778 return MatchAndExplain(str, listener);
3779 }
3780 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3781
3782 // Accepts pointer types, particularly:
3783 // const char*
3784 // char*
3785 // const wchar_t*
3786 // wchar_t*
3787 template <typename CharType>
3788 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3789 if (s == nullptr) {
3790 return !expect_eq_;
3791 }
3792 return MatchAndExplain(StringType(s), listener);
3793 }
3794
3795 // Matches anything that can convert to StringType.
3796 //
3797 // This is a template, not just a plain function with const StringType&,
3798 // because StringView has some interfering non-explicit constructors.
3799 template <typename MatcheeStringType>
3800 bool MatchAndExplain(const MatcheeStringType& s,
3801 MatchResultListener* /* listener */) const {
3802 const StringType s2(s);
3803 const bool eq = case_sensitive_ ? s2 == string_ :
3804 CaseInsensitiveStringEquals(s2, string_);
3805 return expect_eq_ == eq;
3806 }
3807
3808 void DescribeTo(::std::ostream* os) const {
3809 DescribeToHelper(expect_eq_, os);
3810 }
3811
3812 void DescribeNegationTo(::std::ostream* os) const {
3813 DescribeToHelper(!expect_eq_, os);
3814 }
3815
3816 private:
3817 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
3818 *os << (expect_eq ? "is " : "isn't ");
3819 *os << "equal to ";
3820 if (!case_sensitive_) {
3821 *os << "(ignoring case) ";
3822 }
3823 UniversalPrint(string_, os);
3824 }
3825
3826 const StringType string_;
3827 const bool expect_eq_;
3828 const bool case_sensitive_;
3829 };
3830
3831 // Implements the polymorphic HasSubstr(substring) matcher, which
3832 // can be used as a Matcher<T> as long as T can be converted to a
3833 // string.
3834 template <typename StringType>
3835 class HasSubstrMatcher {
3836 public:
3837 explicit HasSubstrMatcher(const StringType& substring)
3838 : substring_(substring) {}
3839
3840 #if GTEST_INTERNAL_HAS_STRING_VIEW
3841 bool MatchAndExplain(const internal::StringView& s,
3842 MatchResultListener* listener) const {
3843 // This should fail to compile if StringView is used with wide
3844 // strings.
3845 const StringType& str = std::string(s);
3846 return MatchAndExplain(str, listener);
3847 }
3848 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3849
3850 // Accepts pointer types, particularly:
3851 // const char*
3852 // char*
3853 // const wchar_t*
3854 // wchar_t*
3855 template <typename CharType>
3856 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3857 return s != nullptr && MatchAndExplain(StringType(s), listener);
3858 }
3859
3860 // Matches anything that can convert to StringType.
3861 //
3862 // This is a template, not just a plain function with const StringType&,
3863 // because StringView has some interfering non-explicit constructors.
3864 template <typename MatcheeStringType>
3865 bool MatchAndExplain(const MatcheeStringType& s,
3866 MatchResultListener* /* listener */) const {
3867 return StringType(s).find(substring_) != StringType::npos;
3868 }
3869
3870 // Describes what this matcher matches.
3871 void DescribeTo(::std::ostream* os) const {
3872 *os << "has substring ";
3873 UniversalPrint(substring_, os);
3874 }
3875
3876 void DescribeNegationTo(::std::ostream* os) const {
3877 *os << "has no substring ";
3878 UniversalPrint(substring_, os);
3879 }
3880
3881 private:
3882 const StringType substring_;
3883 };
3884
3885 // Implements the polymorphic StartsWith(substring) matcher, which
3886 // can be used as a Matcher<T> as long as T can be converted to a
3887 // string.
3888 template <typename StringType>
3889 class StartsWithMatcher {
3890 public:
3891 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
3892 }
3893
3894 #if GTEST_INTERNAL_HAS_STRING_VIEW
3895 bool MatchAndExplain(const internal::StringView& s,
3896 MatchResultListener* listener) const {
3897 // This should fail to compile if StringView is used with wide
3898 // strings.
3899 const StringType& str = std::string(s);
3900 return MatchAndExplain(str, listener);
3901 }
3902 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3903
3904 // Accepts pointer types, particularly:
3905 // const char*
3906 // char*
3907 // const wchar_t*
3908 // wchar_t*
3909 template <typename CharType>
3910 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3911 return s != nullptr && MatchAndExplain(StringType(s), listener);
3912 }
3913
3914 // Matches anything that can convert to StringType.
3915 //
3916 // This is a template, not just a plain function with const StringType&,
3917 // because StringView has some interfering non-explicit constructors.
3918 template <typename MatcheeStringType>
3919 bool MatchAndExplain(const MatcheeStringType& s,
3920 MatchResultListener* /* listener */) const {
3921 const StringType& s2(s);
3922 return s2.length() >= prefix_.length() &&
3923 s2.substr(0, prefix_.length()) == prefix_;
3924 }
3925
3926 void DescribeTo(::std::ostream* os) const {
3927 *os << "starts with ";
3928 UniversalPrint(prefix_, os);
3929 }
3930
3931 void DescribeNegationTo(::std::ostream* os) const {
3932 *os << "doesn't start with ";
3933 UniversalPrint(prefix_, os);
3934 }
3935
3936 private:
3937 const StringType prefix_;
3938 };
3939
3940 // Implements the polymorphic EndsWith(substring) matcher, which
3941 // can be used as a Matcher<T> as long as T can be converted to a
3942 // string.
3943 template <typename StringType>
3944 class EndsWithMatcher {
3945 public:
3946 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
3947
3948 #if GTEST_INTERNAL_HAS_STRING_VIEW
3949 bool MatchAndExplain(const internal::StringView& s,
3950 MatchResultListener* listener) const {
3951 // This should fail to compile if StringView is used with wide
3952 // strings.
3953 const StringType& str = std::string(s);
3954 return MatchAndExplain(str, listener);
3955 }
3956 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3957
3958 // Accepts pointer types, particularly:
3959 // const char*
3960 // char*
3961 // const wchar_t*
3962 // wchar_t*
3963 template <typename CharType>
3964 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3965 return s != nullptr && MatchAndExplain(StringType(s), listener);
3966 }
3967
3968 // Matches anything that can convert to StringType.
3969 //
3970 // This is a template, not just a plain function with const StringType&,
3971 // because StringView has some interfering non-explicit constructors.
3972 template <typename MatcheeStringType>
3973 bool MatchAndExplain(const MatcheeStringType& s,
3974 MatchResultListener* /* listener */) const {
3975 const StringType& s2(s);
3976 return s2.length() >= suffix_.length() &&
3977 s2.substr(s2.length() - suffix_.length()) == suffix_;
3978 }
3979
3980 void DescribeTo(::std::ostream* os) const {
3981 *os << "ends with ";
3982 UniversalPrint(suffix_, os);
3983 }
3984
3985 void DescribeNegationTo(::std::ostream* os) const {
3986 *os << "doesn't end with ";
3987 UniversalPrint(suffix_, os);
3988 }
3989
3990 private:
3991 const StringType suffix_;
3992 };
3993
3994 // Implements a matcher that compares the two fields of a 2-tuple
3995 // using one of the ==, <=, <, etc, operators. The two fields being
3996 // compared don't have to have the same type.
3997 //
3998 // The matcher defined here is polymorphic (for example, Eq() can be
3999 // used to match a std::tuple<int, short>, a std::tuple<const long&, double>,
4000 // etc). Therefore we use a template type conversion operator in the
4001 // implementation.
4002 template <typename D, typename Op>
4003 class PairMatchBase {
4004 public:
4005 template <typename T1, typename T2>
4006 operator Matcher<::std::tuple<T1, T2>>() const {
4007 return Matcher<::std::tuple<T1, T2>>(new Impl<const ::std::tuple<T1, T2>&>);
4008 }
4009 template <typename T1, typename T2>
4010 operator Matcher<const ::std::tuple<T1, T2>&>() const {
4011 return MakeMatcher(new Impl<const ::std::tuple<T1, T2>&>);
4012 }
4013
4014 private:
4015 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
4016 return os << D::Desc();
4017 }
4018
4019 template <typename Tuple>
4020 class Impl : public MatcherInterface<Tuple> {
4021 public:
4022 bool MatchAndExplain(Tuple args,
4023 MatchResultListener* /* listener */) const override {
4024 return Op()(::std::get<0>(args), ::std::get<1>(args));
4025 }
4026 void DescribeTo(::std::ostream* os) const override {
4027 *os << "are " << GetDesc;
4028 }
4029 void DescribeNegationTo(::std::ostream* os) const override {
4030 *os << "aren't " << GetDesc;
4031 }
4032 };
4033 };
4034
4035 class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
4036 public:
4037 static const char* Desc() { return "an equal pair"; }
4038 };
4039 class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
4040 public:
4041 static const char* Desc() { return "an unequal pair"; }
4042 };
4043 class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
4044 public:
4045 static const char* Desc() { return "a pair where the first < the second"; }
4046 };
4047 class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
4048 public:
4049 static const char* Desc() { return "a pair where the first > the second"; }
4050 };
4051 class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
4052 public:
4053 static const char* Desc() { return "a pair where the first <= the second"; }
4054 };
4055 class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
4056 public:
4057 static const char* Desc() { return "a pair where the first >= the second"; }
4058 };
4059
4060 // Implements the Not(...) matcher for a particular argument type T.
4061 // We do not nest it inside the NotMatcher class template, as that
4062 // will prevent different instantiations of NotMatcher from sharing
4063 // the same NotMatcherImpl<T> class.
4064 template <typename T>
4065 class NotMatcherImpl : public MatcherInterface<const T&> {
4066 public:
4067 explicit NotMatcherImpl(const Matcher<T>& matcher)
4068 : matcher_(matcher) {}
4069
4070 bool MatchAndExplain(const T& x,
4071 MatchResultListener* listener) const override {
4072 return !matcher_.MatchAndExplain(x, listener);
4073 }
4074
4075 void DescribeTo(::std::ostream* os) const override {
4076 matcher_.DescribeNegationTo(os);
4077 }
4078
4079 void DescribeNegationTo(::std::ostream* os) const override {
4080 matcher_.DescribeTo(os);
4081 }
4082
4083 private:
4084 const Matcher<T> matcher_;
4085 };
4086
4087 // Implements the Not(m) matcher, which matches a value that doesn't
4088 // match matcher m.
4089 template <typename InnerMatcher>
4090 class NotMatcher {
4091 public:
4092 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
4093
4094 // This template type conversion operator allows Not(m) to be used
4095 // to match any type m can match.
4096 template <typename T>
4097 operator Matcher<T>() const {
4098 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
4099 }
4100
4101 private:
4102 InnerMatcher matcher_;
4103 };
4104
4105 // Implements the AllOf(m1, m2) matcher for a particular argument type
4106 // T. We do not nest it inside the BothOfMatcher class template, as
4107 // that will prevent different instantiations of BothOfMatcher from
4108 // sharing the same BothOfMatcherImpl<T> class.
4109 template <typename T>
4110 class AllOfMatcherImpl : public MatcherInterface<const T&> {
4111 public:
4112 explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers)
4113 : matchers_(std::move(matchers)) {}
4114
4115 void DescribeTo(::std::ostream* os) const override {
4116 *os << "(";
4117 for (size_t i = 0; i < matchers_.size(); ++i) {
4118 if (i != 0) *os << ") and (";
4119 matchers_[i].DescribeTo(os);
4120 }
4121 *os << ")";
4122 }
4123
4124 void DescribeNegationTo(::std::ostream* os) const override {
4125 *os << "(";
4126 for (size_t i = 0; i < matchers_.size(); ++i) {
4127 if (i != 0) *os << ") or (";
4128 matchers_[i].DescribeNegationTo(os);
4129 }
4130 *os << ")";
4131 }
4132
4133 bool MatchAndExplain(const T& x,
4134 MatchResultListener* listener) const override {
4135 // If either matcher1_ or matcher2_ doesn't match x, we only need
4136 // to explain why one of them fails.
4137 std::string all_match_result;
4138
4139 for (size_t i = 0; i < matchers_.size(); ++i) {
4140 StringMatchResultListener slistener;
4141 if (matchers_[i].MatchAndExplain(x, &slistener)) {
4142 if (all_match_result.empty()) {
4143 all_match_result = slistener.str();
4144 } else {
4145 std::string result = slistener.str();
4146 if (!result.empty()) {
4147 all_match_result += ", and ";
4148 all_match_result += result;
4149 }
4150 }
4151 } else {
4152 *listener << slistener.str();
4153 return false;
4154 }
4155 }
4156
4157 // Otherwise we need to explain why *both* of them match.
4158 *listener << all_match_result;
4159 return true;
4160 }
4161
4162 private:
4163 const std::vector<Matcher<T> > matchers_;
4164 };
4165
4166 // VariadicMatcher is used for the variadic implementation of
4167 // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
4168 // CombiningMatcher<T> is used to recursively combine the provided matchers
4169 // (of type Args...).
4170 template <template <typename T> class CombiningMatcher, typename... Args>
4171 class VariadicMatcher {
4172 public:
4173 VariadicMatcher(const Args&... matchers) // NOLINT
4174 : matchers_(matchers...) {
4175 static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
4176 }
4177
4178 VariadicMatcher(const VariadicMatcher&) = default;
4179 VariadicMatcher& operator=(const VariadicMatcher&) = delete;
4180
4181 // This template type conversion operator allows an
4182 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
4183 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
4184 template <typename T>
4185 operator Matcher<T>() const {
4186 std::vector<Matcher<T> > values;
4187 CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
4188 return Matcher<T>(new CombiningMatcher<T>(std::move(values)));
4189 }
4190
4191 private:
4192 template <typename T, size_t I>
4193 void CreateVariadicMatcher(std::vector<Matcher<T> >* values,
4194 std::integral_constant<size_t, I>) const {
4195 values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
4196 CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
4197 }
4198
4199 template <typename T>
4200 void CreateVariadicMatcher(
4201 std::vector<Matcher<T> >*,
4202 std::integral_constant<size_t, sizeof...(Args)>) const {}
4203
4204 std::tuple<Args...> matchers_;
4205 };
4206
4207 template <typename... Args>
4208 using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
4209
4210 // Implements the AnyOf(m1, m2) matcher for a particular argument type
4211 // T. We do not nest it inside the AnyOfMatcher class template, as
4212 // that will prevent different instantiations of AnyOfMatcher from
4213 // sharing the same EitherOfMatcherImpl<T> class.
4214 template <typename T>
4215 class AnyOfMatcherImpl : public MatcherInterface<const T&> {
4216 public:
4217 explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers)
4218 : matchers_(std::move(matchers)) {}
4219
4220 void DescribeTo(::std::ostream* os) const override {
4221 *os << "(";
4222 for (size_t i = 0; i < matchers_.size(); ++i) {
4223 if (i != 0) *os << ") or (";
4224 matchers_[i].DescribeTo(os);
4225 }
4226 *os << ")";
4227 }
4228
4229 void DescribeNegationTo(::std::ostream* os) const override {
4230 *os << "(";
4231 for (size_t i = 0; i < matchers_.size(); ++i) {
4232 if (i != 0) *os << ") and (";
4233 matchers_[i].DescribeNegationTo(os);
4234 }
4235 *os << ")";
4236 }
4237
4238 bool MatchAndExplain(const T& x,
4239 MatchResultListener* listener) const override {
4240 std::string no_match_result;
4241
4242 // If either matcher1_ or matcher2_ matches x, we just need to
4243 // explain why *one* of them matches.
4244 for (size_t i = 0; i < matchers_.size(); ++i) {
4245 StringMatchResultListener slistener;
4246 if (matchers_[i].MatchAndExplain(x, &slistener)) {
4247 *listener << slistener.str();
4248 return true;
4249 } else {
4250 if (no_match_result.empty()) {
4251 no_match_result = slistener.str();
4252 } else {
4253 std::string result = slistener.str();
4254 if (!result.empty()) {
4255 no_match_result += ", and ";
4256 no_match_result += result;
4257 }
4258 }
4259 }
4260 }
4261
4262 // Otherwise we need to explain why *both* of them fail.
4263 *listener << no_match_result;
4264 return false;
4265 }
4266
4267 private:
4268 const std::vector<Matcher<T> > matchers_;
4269 };
4270
4271 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
4272 template <typename... Args>
4273 using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
4274
4275 // Wrapper for implementation of Any/AllOfArray().
4276 template <template <class> class MatcherImpl, typename T>
4277 class SomeOfArrayMatcher {
4278 public:
4279 // Constructs the matcher from a sequence of element values or
4280 // element matchers.
4281 template <typename Iter>
4282 SomeOfArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
4283
4284 template <typename U>
4285 operator Matcher<U>() const { // NOLINT
4286 using RawU = typename std::decay<U>::type;
4287 std::vector<Matcher<RawU>> matchers;
4288 for (const auto& matcher : matchers_) {
4289 matchers.push_back(MatcherCast<RawU>(matcher));
4290 }
4291 return Matcher<U>(new MatcherImpl<RawU>(std::move(matchers)));
4292 }
4293
4294 private:
4295 const ::std::vector<T> matchers_;
4296 };
4297
4298 template <typename T>
4299 using AllOfArrayMatcher = SomeOfArrayMatcher<AllOfMatcherImpl, T>;
4300
4301 template <typename T>
4302 using AnyOfArrayMatcher = SomeOfArrayMatcher<AnyOfMatcherImpl, T>;
4303
4304 // Used for implementing Truly(pred), which turns a predicate into a
4305 // matcher.
4306 template <typename Predicate>
4307 class TrulyMatcher {
4308 public:
4309 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
4310
4311 // This method template allows Truly(pred) to be used as a matcher
4312 // for type T where T is the argument type of predicate 'pred'. The
4313 // argument is passed by reference as the predicate may be
4314 // interested in the address of the argument.
4315 template <typename T>
4316 bool MatchAndExplain(T& x, // NOLINT
4317 MatchResultListener* listener) const {
4318 // Without the if-statement, MSVC sometimes warns about converting
4319 // a value to bool (warning 4800).
4320 //
4321 // We cannot write 'return !!predicate_(x);' as that doesn't work
4322 // when predicate_(x) returns a class convertible to bool but
4323 // having no operator!().
4324 if (predicate_(x))
4325 return true;
4326 *listener << "didn't satisfy the given predicate";
4327 return false;
4328 }
4329
4330 void DescribeTo(::std::ostream* os) const {
4331 *os << "satisfies the given predicate";
4332 }
4333
4334 void DescribeNegationTo(::std::ostream* os) const {
4335 *os << "doesn't satisfy the given predicate";
4336 }
4337
4338 private:
4339 Predicate predicate_;
4340 };
4341
4342 // Used for implementing Matches(matcher), which turns a matcher into
4343 // a predicate.
4344 template <typename M>
4345 class MatcherAsPredicate {
4346 public:
4347 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
4348
4349 // This template operator() allows Matches(m) to be used as a
4350 // predicate on type T where m is a matcher on type T.
4351 //
4352 // The argument x is passed by reference instead of by value, as
4353 // some matcher may be interested in its address (e.g. as in
4354 // Matches(Ref(n))(x)).
4355 template <typename T>
4356 bool operator()(const T& x) const {
4357 // We let matcher_ commit to a particular type here instead of
4358 // when the MatcherAsPredicate object was constructed. This
4359 // allows us to write Matches(m) where m is a polymorphic matcher
4360 // (e.g. Eq(5)).
4361 //
4362 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
4363 // compile when matcher_ has type Matcher<const T&>; if we write
4364 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
4365 // when matcher_ has type Matcher<T>; if we just write
4366 // matcher_.Matches(x), it won't compile when matcher_ is
4367 // polymorphic, e.g. Eq(5).
4368 //
4369 // MatcherCast<const T&>() is necessary for making the code work
4370 // in all of the above situations.
4371 return MatcherCast<const T&>(matcher_).Matches(x);
4372 }
4373
4374 private:
4375 M matcher_;
4376 };
4377
4378 // For implementing ASSERT_THAT() and EXPECT_THAT(). The template
4379 // argument M must be a type that can be converted to a matcher.
4380 template <typename M>
4381 class PredicateFormatterFromMatcher {
4382 public:
4383 explicit PredicateFormatterFromMatcher(M m) : matcher_(std::move(m)) {}
4384
4385 // This template () operator allows a PredicateFormatterFromMatcher
4386 // object to act as a predicate-formatter suitable for using with
4387 // Google Test's EXPECT_PRED_FORMAT1() macro.
4388 template <typename T>
4389 AssertionResult operator()(const char* value_text, const T& x) const {
4390 // We convert matcher_ to a Matcher<const T&> *now* instead of
4391 // when the PredicateFormatterFromMatcher object was constructed,
4392 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
4393 // know which type to instantiate it to until we actually see the
4394 // type of x here.
4395 //
4396 // We write SafeMatcherCast<const T&>(matcher_) instead of
4397 // Matcher<const T&>(matcher_), as the latter won't compile when
4398 // matcher_ has type Matcher<T> (e.g. An<int>()).
4399 // We don't write MatcherCast<const T&> either, as that allows
4400 // potentially unsafe downcasting of the matcher argument.
4401 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
4402
4403 // The expected path here is that the matcher should match (i.e. that most
4404 // tests pass) so optimize for this case.
4405 if (matcher.Matches(x)) {
4406 return AssertionSuccess();
4407 }
4408
4409 ::std::stringstream ss;
4410 ss << "Value of: " << value_text << "\n"
4411 << "Expected: ";
4412 matcher.DescribeTo(&ss);
4413
4414 // Rerun the matcher to "PrintAndExplain" the failure.
4415 StringMatchResultListener listener;
4416 if (MatchPrintAndExplain(x, matcher, &listener)) {
4417 ss << "\n The matcher failed on the initial attempt; but passed when "
4418 "rerun to generate the explanation.";
4419 }
4420 ss << "\n Actual: " << listener.str();
4421 return AssertionFailure() << ss.str();
4422 }
4423
4424 private:
4425 const M matcher_;
4426 };
4427
4428 // A helper function for converting a matcher to a predicate-formatter
4429 // without the user needing to explicitly write the type. This is
4430 // used for implementing ASSERT_THAT() and EXPECT_THAT().
4431 // Implementation detail: 'matcher' is received by-value to force decaying.
4432 template <typename M>
4433 inline PredicateFormatterFromMatcher<M>
4434 MakePredicateFormatterFromMatcher(M matcher) {
4435 return PredicateFormatterFromMatcher<M>(std::move(matcher));
4436 }
4437
4438 // Implements the polymorphic IsNan() matcher, which matches any floating type
4439 // value that is Nan.
4440 class IsNanMatcher {
4441 public:
4442 template <typename FloatType>
4443 bool MatchAndExplain(const FloatType& f,
4444 MatchResultListener* /* listener */) const {
4445 return (::std::isnan)(f);
4446 }
4447
4448 void DescribeTo(::std::ostream* os) const { *os << "is NaN"; }
4449 void DescribeNegationTo(::std::ostream* os) const {
4450 *os << "isn't NaN";
4451 }
4452 };
4453
4454 // Implements the polymorphic floating point equality matcher, which matches
4455 // two float values using ULP-based approximation or, optionally, a
4456 // user-specified epsilon. The template is meant to be instantiated with
4457 // FloatType being either float or double.
4458 template <typename FloatType>
4459 class FloatingEqMatcher {
4460 public:
4461 // Constructor for FloatingEqMatcher.
4462 // The matcher's input will be compared with expected. The matcher treats two
4463 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
4464 // equality comparisons between NANs will always return false. We specify a
4465 // negative max_abs_error_ term to indicate that ULP-based approximation will
4466 // be used for comparison.
4467 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
4468 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
4469 }
4470
4471 // Constructor that supports a user-specified max_abs_error that will be used
4472 // for comparison instead of ULP-based approximation. The max absolute
4473 // should be non-negative.
4474 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
4475 FloatType max_abs_error)
4476 : expected_(expected),
4477 nan_eq_nan_(nan_eq_nan),
4478 max_abs_error_(max_abs_error) {
4479 GTEST_CHECK_(max_abs_error >= 0)
4480 << ", where max_abs_error is" << max_abs_error;
4481 }
4482
4483 // Implements floating point equality matcher as a Matcher<T>.
4484 template <typename T>
4485 class Impl : public MatcherInterface<T> {
4486 public:
4487 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
4488 : expected_(expected),
4489 nan_eq_nan_(nan_eq_nan),
4490 max_abs_error_(max_abs_error) {}
4491
4492 bool MatchAndExplain(T value,
4493 MatchResultListener* listener) const override {
4494 const FloatingPoint<FloatType> actual(value), expected(expected_);
4495
4496 // Compares NaNs first, if nan_eq_nan_ is true.
4497 if (actual.is_nan() || expected.is_nan()) {
4498 if (actual.is_nan() && expected.is_nan()) {
4499 return nan_eq_nan_;
4500 }
4501 // One is nan; the other is not nan.
4502 return false;
4503 }
4504 if (HasMaxAbsError()) {
4505 // We perform an equality check so that inf will match inf, regardless
4506 // of error bounds. If the result of value - expected_ would result in
4507 // overflow or if either value is inf, the default result is infinity,
4508 // which should only match if max_abs_error_ is also infinity.
4509 if (value == expected_) {
4510 return true;
4511 }
4512
4513 const FloatType diff = value - expected_;
4514 if (::std::fabs(diff) <= max_abs_error_) {
4515 return true;
4516 }
4517
4518 if (listener->IsInterested()) {
4519 *listener << "which is " << diff << " from " << expected_;
4520 }
4521 return false;
4522 } else {
4523 return actual.AlmostEquals(expected);
4524 }
4525 }
4526
4527 void DescribeTo(::std::ostream* os) const override {
4528 // os->precision() returns the previously set precision, which we
4529 // store to restore the ostream to its original configuration
4530 // after outputting.
4531 const ::std::streamsize old_precision = os->precision(
4532 ::std::numeric_limits<FloatType>::digits10 + 2);
4533 if (FloatingPoint<FloatType>(expected_).is_nan()) {
4534 if (nan_eq_nan_) {
4535 *os << "is NaN";
4536 } else {
4537 *os << "never matches";
4538 }
4539 } else {
4540 *os << "is approximately " << expected_;
4541 if (HasMaxAbsError()) {
4542 *os << " (absolute error <= " << max_abs_error_ << ")";
4543 }
4544 }
4545 os->precision(old_precision);
4546 }
4547
4548 void DescribeNegationTo(::std::ostream* os) const override {
4549 // As before, get original precision.
4550 const ::std::streamsize old_precision = os->precision(
4551 ::std::numeric_limits<FloatType>::digits10 + 2);
4552 if (FloatingPoint<FloatType>(expected_).is_nan()) {
4553 if (nan_eq_nan_) {
4554 *os << "isn't NaN";
4555 } else {
4556 *os << "is anything";
4557 }
4558 } else {
4559 *os << "isn't approximately " << expected_;
4560 if (HasMaxAbsError()) {
4561 *os << " (absolute error > " << max_abs_error_ << ")";
4562 }
4563 }
4564 // Restore original precision.
4565 os->precision(old_precision);
4566 }
4567
4568 private:
4569 bool HasMaxAbsError() const {
4570 return max_abs_error_ >= 0;
4571 }
4572
4573 const FloatType expected_;
4574 const bool nan_eq_nan_;
4575 // max_abs_error will be used for value comparison when >= 0.
4576 const FloatType max_abs_error_;
4577 };
4578
4579 // The following 3 type conversion operators allow FloatEq(expected) and
4580 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
4581 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
4582 operator Matcher<FloatType>() const {
4583 return MakeMatcher(
4584 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
4585 }
4586
4587 operator Matcher<const FloatType&>() const {
4588 return MakeMatcher(
4589 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
4590 }
4591
4592 operator Matcher<FloatType&>() const {
4593 return MakeMatcher(
4594 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
4595 }
4596
4597 private:
4598 const FloatType expected_;
4599 const bool nan_eq_nan_;
4600 // max_abs_error will be used for value comparison when >= 0.
4601 const FloatType max_abs_error_;
4602 };
4603
4604 // A 2-tuple ("binary") wrapper around FloatingEqMatcher:
4605 // FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
4606 // against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
4607 // against y. The former implements "Eq", the latter "Near". At present, there
4608 // is no version that compares NaNs as equal.
4609 template <typename FloatType>
4610 class FloatingEq2Matcher {
4611 public:
4612 FloatingEq2Matcher() { Init(-1, false); }
4613
4614 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
4615
4616 explicit FloatingEq2Matcher(FloatType max_abs_error) {
4617 Init(max_abs_error, false);
4618 }
4619
4620 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
4621 Init(max_abs_error, nan_eq_nan);
4622 }
4623
4624 template <typename T1, typename T2>
4625 operator Matcher<::std::tuple<T1, T2>>() const {
4626 return MakeMatcher(
4627 new Impl<::std::tuple<T1, T2>>(max_abs_error_, nan_eq_nan_));
4628 }
4629 template <typename T1, typename T2>
4630 operator Matcher<const ::std::tuple<T1, T2>&>() const {
4631 return MakeMatcher(
4632 new Impl<const ::std::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
4633 }
4634
4635 private:
4636 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
4637 return os << "an almost-equal pair";
4638 }
4639
4640 template <typename Tuple>
4641 class Impl : public MatcherInterface<Tuple> {
4642 public:
4643 Impl(FloatType max_abs_error, bool nan_eq_nan) :
4644 max_abs_error_(max_abs_error),
4645 nan_eq_nan_(nan_eq_nan) {}
4646
4647 bool MatchAndExplain(Tuple args,
4648 MatchResultListener* listener) const override {
4649 if (max_abs_error_ == -1) {
4650 FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_);
4651 return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(
4652 ::std::get<1>(args), listener);
4653 } else {
4654 FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_,
4655 max_abs_error_);
4656 return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(
4657 ::std::get<1>(args), listener);
4658 }
4659 }
4660 void DescribeTo(::std::ostream* os) const override {
4661 *os << "are " << GetDesc;
4662 }
4663 void DescribeNegationTo(::std::ostream* os) const override {
4664 *os << "aren't " << GetDesc;
4665 }
4666
4667 private:
4668 FloatType max_abs_error_;
4669 const bool nan_eq_nan_;
4670 };
4671
4672 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
4673 max_abs_error_ = max_abs_error_val;
4674 nan_eq_nan_ = nan_eq_nan_val;
4675 }
4676 FloatType max_abs_error_;
4677 bool nan_eq_nan_;
4678 };
4679
4680 // Implements the Pointee(m) matcher for matching a pointer whose
4681 // pointee matches matcher m. The pointer can be either raw or smart.
4682 template <typename InnerMatcher>
4683 class PointeeMatcher {
4684 public:
4685 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
4686
4687 // This type conversion operator template allows Pointee(m) to be
4688 // used as a matcher for any pointer type whose pointee type is
4689 // compatible with the inner matcher, where type Pointer can be
4690 // either a raw pointer or a smart pointer.
4691 //
4692 // The reason we do this instead of relying on
4693 // MakePolymorphicMatcher() is that the latter is not flexible
4694 // enough for implementing the DescribeTo() method of Pointee().
4695 template <typename Pointer>
4696 operator Matcher<Pointer>() const {
4697 return Matcher<Pointer>(new Impl<const Pointer&>(matcher_));
4698 }
4699
4700 private:
4701 // The monomorphic implementation that works for a particular pointer type.
4702 template <typename Pointer>
4703 class Impl : public MatcherInterface<Pointer> {
4704 public:
4705 using Pointee =
4706 typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
4707 Pointer)>::element_type;
4708
4709 explicit Impl(const InnerMatcher& matcher)
4710 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
4711
4712 void DescribeTo(::std::ostream* os) const override {
4713 *os << "points to a value that ";
4714 matcher_.DescribeTo(os);
4715 }
4716
4717 void DescribeNegationTo(::std::ostream* os) const override {
4718 *os << "does not point to a value that ";
4719 matcher_.DescribeTo(os);
4720 }
4721
4722 bool MatchAndExplain(Pointer pointer,
4723 MatchResultListener* listener) const override {
4724 if (GetRawPointer(pointer) == nullptr) return false;
4725
4726 *listener << "which points to ";
4727 return MatchPrintAndExplain(*pointer, matcher_, listener);
4728 }
4729
4730 private:
4731 const Matcher<const Pointee&> matcher_;
4732 };
4733
4734 const InnerMatcher matcher_;
4735 };
4736
4737 // Implements the Pointer(m) matcher
4738 // Implements the Pointer(m) matcher for matching a pointer that matches matcher
4739 // m. The pointer can be either raw or smart, and will match `m` against the
4740 // raw pointer.
4741 template <typename InnerMatcher>
4742 class PointerMatcher {
4743 public:
4744 explicit PointerMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
4745
4746 // This type conversion operator template allows Pointer(m) to be
4747 // used as a matcher for any pointer type whose pointer type is
4748 // compatible with the inner matcher, where type PointerType can be
4749 // either a raw pointer or a smart pointer.
4750 //
4751 // The reason we do this instead of relying on
4752 // MakePolymorphicMatcher() is that the latter is not flexible
4753 // enough for implementing the DescribeTo() method of Pointer().
4754 template <typename PointerType>
4755 operator Matcher<PointerType>() const { // NOLINT
4756 return Matcher<PointerType>(new Impl<const PointerType&>(matcher_));
4757 }
4758
4759 private:
4760 // The monomorphic implementation that works for a particular pointer type.
4761 template <typename PointerType>
4762 class Impl : public MatcherInterface<PointerType> {
4763 public:
4764 using Pointer =
4765 const typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
4766 PointerType)>::element_type*;
4767
4768 explicit Impl(const InnerMatcher& matcher)
4769 : matcher_(MatcherCast<Pointer>(matcher)) {}
4770
4771 void DescribeTo(::std::ostream* os) const override {
4772 *os << "is a pointer that ";
4773 matcher_.DescribeTo(os);
4774 }
4775
4776 void DescribeNegationTo(::std::ostream* os) const override {
4777 *os << "is not a pointer that ";
4778 matcher_.DescribeTo(os);
4779 }
4780
4781 bool MatchAndExplain(PointerType pointer,
4782 MatchResultListener* listener) const override {
4783 *listener << "which is a pointer that ";
4784 Pointer p = GetRawPointer(pointer);
4785 return MatchPrintAndExplain(p, matcher_, listener);
4786 }
4787
4788 private:
4789 Matcher<Pointer> matcher_;
4790 };
4791
4792 const InnerMatcher matcher_;
4793 };
4794
4795 #if GTEST_HAS_RTTI
4796 // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
4797 // reference that matches inner_matcher when dynamic_cast<T> is applied.
4798 // The result of dynamic_cast<To> is forwarded to the inner matcher.
4799 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
4800 // If To is a reference and the cast fails, this matcher returns false
4801 // immediately.
4802 template <typename To>
4803 class WhenDynamicCastToMatcherBase {
4804 public:
4805 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
4806 : matcher_(matcher) {}
4807
4808 void DescribeTo(::std::ostream* os) const {
4809 GetCastTypeDescription(os);
4810 matcher_.DescribeTo(os);
4811 }
4812
4813 void DescribeNegationTo(::std::ostream* os) const {
4814 GetCastTypeDescription(os);
4815 matcher_.DescribeNegationTo(os);
4816 }
4817
4818 protected:
4819 const Matcher<To> matcher_;
4820
4821 static std::string GetToName() {
4822 return GetTypeName<To>();
4823 }
4824
4825 private:
4826 static void GetCastTypeDescription(::std::ostream* os) {
4827 *os << "when dynamic_cast to " << GetToName() << ", ";
4828 }
4829 };
4830
4831 // Primary template.
4832 // To is a pointer. Cast and forward the result.
4833 template <typename To>
4834 class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
4835 public:
4836 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
4837 : WhenDynamicCastToMatcherBase<To>(matcher) {}
4838
4839 template <typename From>
4840 bool MatchAndExplain(From from, MatchResultListener* listener) const {
4841 To to = dynamic_cast<To>(from);
4842 return MatchPrintAndExplain(to, this->matcher_, listener);
4843 }
4844 };
4845
4846 // Specialize for references.
4847 // In this case we return false if the dynamic_cast fails.
4848 template <typename To>
4849 class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
4850 public:
4851 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
4852 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
4853
4854 template <typename From>
4855 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
4856 // We don't want an std::bad_cast here, so do the cast with pointers.
4857 To* to = dynamic_cast<To*>(&from);
4858 if (to == nullptr) {
4859 *listener << "which cannot be dynamic_cast to " << this->GetToName();
4860 return false;
4861 }
4862 return MatchPrintAndExplain(*to, this->matcher_, listener);
4863 }
4864 };
4865 #endif // GTEST_HAS_RTTI
4866
4867 // Implements the Field() matcher for matching a field (i.e. member
4868 // variable) of an object.
4869 template <typename Class, typename FieldType>
4870 class FieldMatcher {
4871 public:
4872 FieldMatcher(FieldType Class::*field,
4873 const Matcher<const FieldType&>& matcher)
4874 : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
4875
4876 FieldMatcher(const std::string& field_name, FieldType Class::*field,
4877 const Matcher<const FieldType&>& matcher)
4878 : field_(field),
4879 matcher_(matcher),
4880 whose_field_("whose field `" + field_name + "` ") {}
4881
4882 void DescribeTo(::std::ostream* os) const {
4883 *os << "is an object " << whose_field_;
4884 matcher_.DescribeTo(os);
4885 }
4886
4887 void DescribeNegationTo(::std::ostream* os) const {
4888 *os << "is an object " << whose_field_;
4889 matcher_.DescribeNegationTo(os);
4890 }
4891
4892 template <typename T>
4893 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
4894 // FIXME: The dispatch on std::is_pointer was introduced as a workaround for
4895 // a compiler bug, and can now be removed.
4896 return MatchAndExplainImpl(
4897 typename std::is_pointer<typename std::remove_const<T>::type>::type(),
4898 value, listener);
4899 }
4900
4901 private:
4902 bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,
4903 const Class& obj,
4904 MatchResultListener* listener) const {
4905 *listener << whose_field_ << "is ";
4906 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
4907 }
4908
4909 bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,
4910 MatchResultListener* listener) const {
4911 if (p == nullptr) return false;
4912
4913 *listener << "which points to an object ";
4914 // Since *p has a field, it must be a class/struct/union type and
4915 // thus cannot be a pointer. Therefore we pass false_type() as
4916 // the first argument.
4917 return MatchAndExplainImpl(std::false_type(), *p, listener);
4918 }
4919
4920 const FieldType Class::*field_;
4921 const Matcher<const FieldType&> matcher_;
4922
4923 // Contains either "whose given field " if the name of the field is unknown
4924 // or "whose field `name_of_field` " if the name is known.
4925 const std::string whose_field_;
4926 };
4927
4928 // Implements the Property() matcher for matching a property
4929 // (i.e. return value of a getter method) of an object.
4930 //
4931 // Property is a const-qualified member function of Class returning
4932 // PropertyType.
4933 template <typename Class, typename PropertyType, typename Property>
4934 class PropertyMatcher {
4935 public:
4936 typedef const PropertyType& RefToConstProperty;
4937
4938 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
4939 : property_(property),
4940 matcher_(matcher),
4941 whose_property_("whose given property ") {}
4942
4943 PropertyMatcher(const std::string& property_name, Property property,
4944 const Matcher<RefToConstProperty>& matcher)
4945 : property_(property),
4946 matcher_(matcher),
4947 whose_property_("whose property `" + property_name + "` ") {}
4948
4949 void DescribeTo(::std::ostream* os) const {
4950 *os << "is an object " << whose_property_;
4951 matcher_.DescribeTo(os);
4952 }
4953
4954 void DescribeNegationTo(::std::ostream* os) const {
4955 *os << "is an object " << whose_property_;
4956 matcher_.DescribeNegationTo(os);
4957 }
4958
4959 template <typename T>
4960 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
4961 return MatchAndExplainImpl(
4962 typename std::is_pointer<typename std::remove_const<T>::type>::type(),
4963 value, listener);
4964 }
4965
4966 private:
4967 bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,
4968 const Class& obj,
4969 MatchResultListener* listener) const {
4970 *listener << whose_property_ << "is ";
4971 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
4972 // which takes a non-const reference as argument.
4973 RefToConstProperty result = (obj.*property_)();
4974 return MatchPrintAndExplain(result, matcher_, listener);
4975 }
4976
4977 bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,
4978 MatchResultListener* listener) const {
4979 if (p == nullptr) return false;
4980
4981 *listener << "which points to an object ";
4982 // Since *p has a property method, it must be a class/struct/union
4983 // type and thus cannot be a pointer. Therefore we pass
4984 // false_type() as the first argument.
4985 return MatchAndExplainImpl(std::false_type(), *p, listener);
4986 }
4987
4988 Property property_;
4989 const Matcher<RefToConstProperty> matcher_;
4990
4991 // Contains either "whose given property " if the name of the property is
4992 // unknown or "whose property `name_of_property` " if the name is known.
4993 const std::string whose_property_;
4994 };
4995
4996 // Type traits specifying various features of different functors for ResultOf.
4997 // The default template specifies features for functor objects.
4998 template <typename Functor>
4999 struct CallableTraits {
5000 typedef Functor StorageType;
5001
5002 static void CheckIsValid(Functor /* functor */) {}
5003
5004 template <typename T>
5005 static auto Invoke(Functor f, const T& arg) -> decltype(f(arg)) {
5006 return f(arg);
5007 }
5008 };
5009
5010 // Specialization for function pointers.
5011 template <typename ArgType, typename ResType>
5012 struct CallableTraits<ResType(*)(ArgType)> {
5013 typedef ResType ResultType;
5014 typedef ResType(*StorageType)(ArgType);
5015
5016 static void CheckIsValid(ResType(*f)(ArgType)) {
5017 GTEST_CHECK_(f != nullptr)
5018 << "NULL function pointer is passed into ResultOf().";
5019 }
5020 template <typename T>
5021 static ResType Invoke(ResType(*f)(ArgType), T arg) {
5022 return (*f)(arg);
5023 }
5024 };
5025
5026 // Implements the ResultOf() matcher for matching a return value of a
5027 // unary function of an object.
5028 template <typename Callable, typename InnerMatcher>
5029 class ResultOfMatcher {
5030 public:
5031 ResultOfMatcher(Callable callable, InnerMatcher matcher)
5032 : callable_(std::move(callable)), matcher_(std::move(matcher)) {
5033 CallableTraits<Callable>::CheckIsValid(callable_);
5034 }
5035
5036 template <typename T>
5037 operator Matcher<T>() const {
5038 return Matcher<T>(new Impl<const T&>(callable_, matcher_));
5039 }
5040
5041 private:
5042 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
5043
5044 template <typename T>
5045 class Impl : public MatcherInterface<T> {
5046 using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(
5047 std::declval<CallableStorageType>(), std::declval<T>()));
5048
5049 public:
5050 template <typename M>
5051 Impl(const CallableStorageType& callable, const M& matcher)
5052 : callable_(callable), matcher_(MatcherCast<ResultType>(matcher)) {}
5053
5054 void DescribeTo(::std::ostream* os) const override {
5055 *os << "is mapped by the given callable to a value that ";
5056 matcher_.DescribeTo(os);
5057 }
5058
5059 void DescribeNegationTo(::std::ostream* os) const override {
5060 *os << "is mapped by the given callable to a value that ";
5061 matcher_.DescribeNegationTo(os);
5062 }
5063
5064 bool MatchAndExplain(T obj, MatchResultListener* listener) const override {
5065 *listener << "which is mapped by the given callable to ";
5066 // Cannot pass the return value directly to MatchPrintAndExplain, which
5067 // takes a non-const reference as argument.
5068 // Also, specifying template argument explicitly is needed because T could
5069 // be a non-const reference (e.g. Matcher<Uncopyable&>).
5070 ResultType result =
5071 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
5072 return MatchPrintAndExplain(result, matcher_, listener);
5073 }
5074
5075 private:
5076 // Functors often define operator() as non-const method even though
5077 // they are actually stateless. But we need to use them even when
5078 // 'this' is a const pointer. It's the user's responsibility not to
5079 // use stateful callables with ResultOf(), which doesn't guarantee
5080 // how many times the callable will be invoked.
5081 mutable CallableStorageType callable_;
5082 const Matcher<ResultType> matcher_;
5083 }; // class Impl
5084
5085 const CallableStorageType callable_;
5086 const InnerMatcher matcher_;
5087 };
5088
5089 // Implements a matcher that checks the size of an STL-style container.
5090 template <typename SizeMatcher>
5091 class SizeIsMatcher {
5092 public:
5093 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
5094 : size_matcher_(size_matcher) {
5095 }
5096
5097 template <typename Container>
5098 operator Matcher<Container>() const {
5099 return Matcher<Container>(new Impl<const Container&>(size_matcher_));
5100 }
5101
5102 template <typename Container>
5103 class Impl : public MatcherInterface<Container> {
5104 public:
5105 using SizeType = decltype(std::declval<Container>().size());
5106 explicit Impl(const SizeMatcher& size_matcher)
5107 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
5108
5109 void DescribeTo(::std::ostream* os) const override {
5110 *os << "size ";
5111 size_matcher_.DescribeTo(os);
5112 }
5113 void DescribeNegationTo(::std::ostream* os) const override {
5114 *os << "size ";
5115 size_matcher_.DescribeNegationTo(os);
5116 }
5117
5118 bool MatchAndExplain(Container container,
5119 MatchResultListener* listener) const override {
5120 SizeType size = container.size();
5121 StringMatchResultListener size_listener;
5122 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
5123 *listener
5124 << "whose size " << size << (result ? " matches" : " doesn't match");
5125 PrintIfNotEmpty(size_listener.str(), listener->stream());
5126 return result;
5127 }
5128
5129 private:
5130 const Matcher<SizeType> size_matcher_;
5131 };
5132
5133 private:
5134 const SizeMatcher size_matcher_;
5135 };
5136
5137 // Implements a matcher that checks the begin()..end() distance of an STL-style
5138 // container.
5139 template <typename DistanceMatcher>
5140 class BeginEndDistanceIsMatcher {
5141 public:
5142 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
5143 : distance_matcher_(distance_matcher) {}
5144
5145 template <typename Container>
5146 operator Matcher<Container>() const {
5147 return Matcher<Container>(new Impl<const Container&>(distance_matcher_));
5148 }
5149
5150 template <typename Container>
5151 class Impl : public MatcherInterface<Container> {
5152 public:
5153 typedef internal::StlContainerView<
5154 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
5155 typedef typename std::iterator_traits<
5156 typename ContainerView::type::const_iterator>::difference_type
5157 DistanceType;
5158 explicit Impl(const DistanceMatcher& distance_matcher)
5159 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
5160
5161 void DescribeTo(::std::ostream* os) const override {
5162 *os << "distance between begin() and end() ";
5163 distance_matcher_.DescribeTo(os);
5164 }
5165 void DescribeNegationTo(::std::ostream* os) const override {
5166 *os << "distance between begin() and end() ";
5167 distance_matcher_.DescribeNegationTo(os);
5168 }
5169
5170 bool MatchAndExplain(Container container,
5171 MatchResultListener* listener) const override {
5172 using std::begin;
5173 using std::end;
5174 DistanceType distance = std::distance(begin(container), end(container));
5175 StringMatchResultListener distance_listener;
5176 const bool result =
5177 distance_matcher_.MatchAndExplain(distance, &distance_listener);
5178 *listener << "whose distance between begin() and end() " << distance
5179 << (result ? " matches" : " doesn't match");
5180 PrintIfNotEmpty(distance_listener.str(), listener->stream());
5181 return result;
5182 }
5183
5184 private:
5185 const Matcher<DistanceType> distance_matcher_;
5186 };
5187
5188 private:
5189 const DistanceMatcher distance_matcher_;
5190 };
5191
5192 // Implements an equality matcher for any STL-style container whose elements
5193 // support ==. This matcher is like Eq(), but its failure explanations provide
5194 // more detailed information that is useful when the container is used as a set.
5195 // The failure message reports elements that are in one of the operands but not
5196 // the other. The failure messages do not report duplicate or out-of-order
5197 // elements in the containers (which don't properly matter to sets, but can
5198 // occur if the containers are vectors or lists, for example).
5199 //
5200 // Uses the container's const_iterator, value_type, operator ==,
5201 // begin(), and end().
5202 template <typename Container>
5203 class ContainerEqMatcher {
5204 public:
5205 typedef internal::StlContainerView<Container> View;
5206 typedef typename View::type StlContainer;
5207 typedef typename View::const_reference StlContainerReference;
5208
5209 static_assert(!std::is_const<Container>::value,
5210 "Container type must not be const");
5211 static_assert(!std::is_reference<Container>::value,
5212 "Container type must not be a reference");
5213
5214 // We make a copy of expected in case the elements in it are modified
5215 // after this matcher is created.
5216 explicit ContainerEqMatcher(const Container& expected)
5217 : expected_(View::Copy(expected)) {}
5218
5219 void DescribeTo(::std::ostream* os) const {
5220 *os << "equals ";
5221 UniversalPrint(expected_, os);
5222 }
5223 void DescribeNegationTo(::std::ostream* os) const {
5224 *os << "does not equal ";
5225 UniversalPrint(expected_, os);
5226 }
5227
5228 template <typename LhsContainer>
5229 bool MatchAndExplain(const LhsContainer& lhs,
5230 MatchResultListener* listener) const {
5231 typedef internal::StlContainerView<
5232 typename std::remove_const<LhsContainer>::type>
5233 LhsView;
5234 typedef typename LhsView::type LhsStlContainer;
5235 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
5236 if (lhs_stl_container == expected_)
5237 return true;
5238
5239 ::std::ostream* const os = listener->stream();
5240 if (os != nullptr) {
5241 // Something is different. Check for extra values first.
5242 bool printed_header = false;
5243 for (typename LhsStlContainer::const_iterator it =
5244 lhs_stl_container.begin();
5245 it != lhs_stl_container.end(); ++it) {
5246 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
5247 expected_.end()) {
5248 if (printed_header) {
5249 *os << ", ";
5250 } else {
5251 *os << "which has these unexpected elements: ";
5252 printed_header = true;
5253 }
5254 UniversalPrint(*it, os);
5255 }
5256 }
5257
5258 // Now check for missing values.
5259 bool printed_header2 = false;
5260 for (typename StlContainer::const_iterator it = expected_.begin();
5261 it != expected_.end(); ++it) {
5262 if (internal::ArrayAwareFind(
5263 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
5264 lhs_stl_container.end()) {
5265 if (printed_header2) {
5266 *os << ", ";
5267 } else {
5268 *os << (printed_header ? ",\nand" : "which")
5269 << " doesn't have these expected elements: ";
5270 printed_header2 = true;
5271 }
5272 UniversalPrint(*it, os);
5273 }
5274 }
5275 }
5276
5277 return false;
5278 }
5279
5280 private:
5281 const StlContainer expected_;
5282 };
5283
5284 // A comparator functor that uses the < operator to compare two values.
5285 struct LessComparator {
5286 template <typename T, typename U>
5287 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
5288 };
5289
5290 // Implements WhenSortedBy(comparator, container_matcher).
5291 template <typename Comparator, typename ContainerMatcher>
5292 class WhenSortedByMatcher {
5293 public:
5294 WhenSortedByMatcher(const Comparator& comparator,
5295 const ContainerMatcher& matcher)
5296 : comparator_(comparator), matcher_(matcher) {}
5297
5298 template <typename LhsContainer>
5299 operator Matcher<LhsContainer>() const {
5300 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
5301 }
5302
5303 template <typename LhsContainer>
5304 class Impl : public MatcherInterface<LhsContainer> {
5305 public:
5306 typedef internal::StlContainerView<
5307 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
5308 typedef typename LhsView::type LhsStlContainer;
5309 typedef typename LhsView::const_reference LhsStlContainerReference;
5310 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
5311 // so that we can match associative containers.
5312 typedef typename RemoveConstFromKey<
5313 typename LhsStlContainer::value_type>::type LhsValue;
5314
5315 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
5316 : comparator_(comparator), matcher_(matcher) {}
5317
5318 void DescribeTo(::std::ostream* os) const override {
5319 *os << "(when sorted) ";
5320 matcher_.DescribeTo(os);
5321 }
5322
5323 void DescribeNegationTo(::std::ostream* os) const override {
5324 *os << "(when sorted) ";
5325 matcher_.DescribeNegationTo(os);
5326 }
5327
5328 bool MatchAndExplain(LhsContainer lhs,
5329 MatchResultListener* listener) const override {
5330 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
5331 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
5332 lhs_stl_container.end());
5333 ::std::sort(
5334 sorted_container.begin(), sorted_container.end(), comparator_);
5335
5336 if (!listener->IsInterested()) {
5337 // If the listener is not interested, we do not need to
5338 // construct the inner explanation.
5339 return matcher_.Matches(sorted_container);
5340 }
5341
5342 *listener << "which is ";
5343 UniversalPrint(sorted_container, listener->stream());
5344 *listener << " when sorted";
5345
5346 StringMatchResultListener inner_listener;
5347 const bool match = matcher_.MatchAndExplain(sorted_container,
5348 &inner_listener);
5349 PrintIfNotEmpty(inner_listener.str(), listener->stream());
5350 return match;
5351 }
5352
5353 private:
5354 const Comparator comparator_;
5355 const Matcher<const ::std::vector<LhsValue>&> matcher_;
5356
5357 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
5358 };
5359
5360 private:
5361 const Comparator comparator_;
5362 const ContainerMatcher matcher_;
5363 };
5364
5365 // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
5366 // must be able to be safely cast to Matcher<std::tuple<const T1&, const
5367 // T2&> >, where T1 and T2 are the types of elements in the LHS
5368 // container and the RHS container respectively.
5369 template <typename TupleMatcher, typename RhsContainer>
5370 class PointwiseMatcher {
5371 GTEST_COMPILE_ASSERT_(
5372 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
5373 use_UnorderedPointwise_with_hash_tables);
5374
5375 public:
5376 typedef internal::StlContainerView<RhsContainer> RhsView;
5377 typedef typename RhsView::type RhsStlContainer;
5378 typedef typename RhsStlContainer::value_type RhsValue;
5379
5380 static_assert(!std::is_const<RhsContainer>::value,
5381 "RhsContainer type must not be const");
5382 static_assert(!std::is_reference<RhsContainer>::value,
5383 "RhsContainer type must not be a reference");
5384
5385 // Like ContainerEq, we make a copy of rhs in case the elements in
5386 // it are modified after this matcher is created.
5387 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
5388 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {}
5389
5390 template <typename LhsContainer>
5391 operator Matcher<LhsContainer>() const {
5392 GTEST_COMPILE_ASSERT_(
5393 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
5394 use_UnorderedPointwise_with_hash_tables);
5395
5396 return Matcher<LhsContainer>(
5397 new Impl<const LhsContainer&>(tuple_matcher_, rhs_));
5398 }
5399
5400 template <typename LhsContainer>
5401 class Impl : public MatcherInterface<LhsContainer> {
5402 public:
5403 typedef internal::StlContainerView<
5404 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
5405 typedef typename LhsView::type LhsStlContainer;
5406 typedef typename LhsView::const_reference LhsStlContainerReference;
5407 typedef typename LhsStlContainer::value_type LhsValue;
5408 // We pass the LHS value and the RHS value to the inner matcher by
5409 // reference, as they may be expensive to copy. We must use tuple
5410 // instead of pair here, as a pair cannot hold references (C++ 98,
5411 // 20.2.2 [lib.pairs]).
5412 typedef ::std::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
5413
5414 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
5415 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
5416 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
5417 rhs_(rhs) {}
5418
5419 void DescribeTo(::std::ostream* os) const override {
5420 *os << "contains " << rhs_.size()
5421 << " values, where each value and its corresponding value in ";
5422 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
5423 *os << " ";
5424 mono_tuple_matcher_.DescribeTo(os);
5425 }
5426 void DescribeNegationTo(::std::ostream* os) const override {
5427 *os << "doesn't contain exactly " << rhs_.size()
5428 << " values, or contains a value x at some index i"
5429 << " where x and the i-th value of ";
5430 UniversalPrint(rhs_, os);
5431 *os << " ";
5432 mono_tuple_matcher_.DescribeNegationTo(os);
5433 }
5434
5435 bool MatchAndExplain(LhsContainer lhs,
5436 MatchResultListener* listener) const override {
5437 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
5438 const size_t actual_size = lhs_stl_container.size();
5439 if (actual_size != rhs_.size()) {
5440 *listener << "which contains " << actual_size << " values";
5441 return false;
5442 }
5443
5444 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
5445 typename RhsStlContainer::const_iterator right = rhs_.begin();
5446 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
5447 if (listener->IsInterested()) {
5448 StringMatchResultListener inner_listener;
5449 // Create InnerMatcherArg as a temporarily object to avoid it outlives
5450 // *left and *right. Dereference or the conversion to `const T&` may
5451 // return temp objects, e.g for vector<bool>.
5452 if (!mono_tuple_matcher_.MatchAndExplain(
5453 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
5454 ImplicitCast_<const RhsValue&>(*right)),
5455 &inner_listener)) {
5456 *listener << "where the value pair (";
5457 UniversalPrint(*left, listener->stream());
5458 *listener << ", ";
5459 UniversalPrint(*right, listener->stream());
5460 *listener << ") at index #" << i << " don't match";
5461 PrintIfNotEmpty(inner_listener.str(), listener->stream());
5462 return false;
5463 }
5464 } else {
5465 if (!mono_tuple_matcher_.Matches(
5466 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
5467 ImplicitCast_<const RhsValue&>(*right))))
5468 return false;
5469 }
5470 }
5471
5472 return true;
5473 }
5474
5475 private:
5476 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
5477 const RhsStlContainer rhs_;
5478 };
5479
5480 private:
5481 const TupleMatcher tuple_matcher_;
5482 const RhsStlContainer rhs_;
5483 };
5484
5485 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
5486 template <typename Container>
5487 class QuantifierMatcherImpl : public MatcherInterface<Container> {
5488 public:
5489 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
5490 typedef StlContainerView<RawContainer> View;
5491 typedef typename View::type StlContainer;
5492 typedef typename View::const_reference StlContainerReference;
5493 typedef typename StlContainer::value_type Element;
5494
5495 template <typename InnerMatcher>
5496 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
5497 : inner_matcher_(
5498 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
5499
5500 // Checks whether:
5501 // * All elements in the container match, if all_elements_should_match.
5502 // * Any element in the container matches, if !all_elements_should_match.
5503 bool MatchAndExplainImpl(bool all_elements_should_match,
5504 Container container,
5505 MatchResultListener* listener) const {
5506 StlContainerReference stl_container = View::ConstReference(container);
5507 size_t i = 0;
5508 for (typename StlContainer::const_iterator it = stl_container.begin();
5509 it != stl_container.end(); ++it, ++i) {
5510 StringMatchResultListener inner_listener;
5511 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
5512
5513 if (matches != all_elements_should_match) {
5514 *listener << "whose element #" << i
5515 << (matches ? " matches" : " doesn't match");
5516 PrintIfNotEmpty(inner_listener.str(), listener->stream());
5517 return !all_elements_should_match;
5518 }
5519 }
5520 return all_elements_should_match;
5521 }
5522
5523 protected:
5524 const Matcher<const Element&> inner_matcher_;
5525 };
5526
5527 // Implements Contains(element_matcher) for the given argument type Container.
5528 // Symmetric to EachMatcherImpl.
5529 template <typename Container>
5530 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
5531 public:
5532 template <typename InnerMatcher>
5533 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
5534 : QuantifierMatcherImpl<Container>(inner_matcher) {}
5535
5536 // Describes what this matcher does.
5537 void DescribeTo(::std::ostream* os) const override {
5538 *os << "contains at least one element that ";
5539 this->inner_matcher_.DescribeTo(os);
5540 }
5541
5542 void DescribeNegationTo(::std::ostream* os) const override {
5543 *os << "doesn't contain any element that ";
5544 this->inner_matcher_.DescribeTo(os);
5545 }
5546
5547 bool MatchAndExplain(Container container,
5548 MatchResultListener* listener) const override {
5549 return this->MatchAndExplainImpl(false, container, listener);
5550 }
5551 };
5552
5553 // Implements Each(element_matcher) for the given argument type Container.
5554 // Symmetric to ContainsMatcherImpl.
5555 template <typename Container>
5556 class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
5557 public:
5558 template <typename InnerMatcher>
5559 explicit EachMatcherImpl(InnerMatcher inner_matcher)
5560 : QuantifierMatcherImpl<Container>(inner_matcher) {}
5561
5562 // Describes what this matcher does.
5563 void DescribeTo(::std::ostream* os) const override {
5564 *os << "only contains elements that ";
5565 this->inner_matcher_.DescribeTo(os);
5566 }
5567
5568 void DescribeNegationTo(::std::ostream* os) const override {
5569 *os << "contains some element that ";
5570 this->inner_matcher_.DescribeNegationTo(os);
5571 }
5572
5573 bool MatchAndExplain(Container container,
5574 MatchResultListener* listener) const override {
5575 return this->MatchAndExplainImpl(true, container, listener);
5576 }
5577 };
5578
5579 // Implements polymorphic Contains(element_matcher).
5580 template <typename M>
5581 class ContainsMatcher {
5582 public:
5583 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
5584
5585 template <typename Container>
5586 operator Matcher<Container>() const {
5587 return Matcher<Container>(
5588 new ContainsMatcherImpl<const Container&>(inner_matcher_));
5589 }
5590
5591 private:
5592 const M inner_matcher_;
5593 };
5594
5595 // Implements polymorphic Each(element_matcher).
5596 template <typename M>
5597 class EachMatcher {
5598 public:
5599 explicit EachMatcher(M m) : inner_matcher_(m) {}
5600
5601 template <typename Container>
5602 operator Matcher<Container>() const {
5603 return Matcher<Container>(
5604 new EachMatcherImpl<const Container&>(inner_matcher_));
5605 }
5606
5607 private:
5608 const M inner_matcher_;
5609 };
5610
5611 struct Rank1 {};
5612 struct Rank0 : Rank1 {};
5613
5614 namespace pair_getters {
5615 using std::get;
5616 template <typename T>
5617 auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
5618 return get<0>(x);
5619 }
5620 template <typename T>
5621 auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
5622 return x.first;
5623 }
5624
5625 template <typename T>
5626 auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
5627 return get<1>(x);
5628 }
5629 template <typename T>
5630 auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
5631 return x.second;
5632 }
5633 } // namespace pair_getters
5634
5635 // Implements Key(inner_matcher) for the given argument pair type.
5636 // Key(inner_matcher) matches an std::pair whose 'first' field matches
5637 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
5638 // std::map that contains at least one element whose key is >= 5.
5639 template <typename PairType>
5640 class KeyMatcherImpl : public MatcherInterface<PairType> {
5641 public:
5642 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
5643 typedef typename RawPairType::first_type KeyType;
5644
5645 template <typename InnerMatcher>
5646 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
5647 : inner_matcher_(
5648 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
5649 }
5650
5651 // Returns true if and only if 'key_value.first' (the key) matches the inner
5652 // matcher.
5653 bool MatchAndExplain(PairType key_value,
5654 MatchResultListener* listener) const override {
5655 StringMatchResultListener inner_listener;
5656 const bool match = inner_matcher_.MatchAndExplain(
5657 pair_getters::First(key_value, Rank0()), &inner_listener);
5658 const std::string explanation = inner_listener.str();
5659 if (explanation != "") {
5660 *listener << "whose first field is a value " << explanation;
5661 }
5662 return match;
5663 }
5664
5665 // Describes what this matcher does.
5666 void DescribeTo(::std::ostream* os) const override {
5667 *os << "has a key that ";
5668 inner_matcher_.DescribeTo(os);
5669 }
5670
5671 // Describes what the negation of this matcher does.
5672 void DescribeNegationTo(::std::ostream* os) const override {
5673 *os << "doesn't have a key that ";
5674 inner_matcher_.DescribeTo(os);
5675 }
5676
5677 private:
5678 const Matcher<const KeyType&> inner_matcher_;
5679 };
5680
5681 // Implements polymorphic Key(matcher_for_key).
5682 template <typename M>
5683 class KeyMatcher {
5684 public:
5685 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
5686
5687 template <typename PairType>
5688 operator Matcher<PairType>() const {
5689 return Matcher<PairType>(
5690 new KeyMatcherImpl<const PairType&>(matcher_for_key_));
5691 }
5692
5693 private:
5694 const M matcher_for_key_;
5695 };
5696
5697 // Implements polymorphic Address(matcher_for_address).
5698 template <typename InnerMatcher>
5699 class AddressMatcher {
5700 public:
5701 explicit AddressMatcher(InnerMatcher m) : matcher_(m) {}
5702
5703 template <typename Type>
5704 operator Matcher<Type>() const { // NOLINT
5705 return Matcher<Type>(new Impl<const Type&>(matcher_));
5706 }
5707
5708 private:
5709 // The monomorphic implementation that works for a particular object type.
5710 template <typename Type>
5711 class Impl : public MatcherInterface<Type> {
5712 public:
5713 using Address = const GTEST_REMOVE_REFERENCE_AND_CONST_(Type) *;
5714 explicit Impl(const InnerMatcher& matcher)
5715 : matcher_(MatcherCast<Address>(matcher)) {}
5716
5717 void DescribeTo(::std::ostream* os) const override {
5718 *os << "has address that ";
5719 matcher_.DescribeTo(os);
5720 }
5721
5722 void DescribeNegationTo(::std::ostream* os) const override {
5723 *os << "does not have address that ";
5724 matcher_.DescribeTo(os);
5725 }
5726
5727 bool MatchAndExplain(Type object,
5728 MatchResultListener* listener) const override {
5729 *listener << "which has address ";
5730 Address address = std::addressof(object);
5731 return MatchPrintAndExplain(address, matcher_, listener);
5732 }
5733
5734 private:
5735 const Matcher<Address> matcher_;
5736 };
5737 const InnerMatcher matcher_;
5738 };
5739
5740 // Implements Pair(first_matcher, second_matcher) for the given argument pair
5741 // type with its two matchers. See Pair() function below.
5742 template <typename PairType>
5743 class PairMatcherImpl : public MatcherInterface<PairType> {
5744 public:
5745 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
5746 typedef typename RawPairType::first_type FirstType;
5747 typedef typename RawPairType::second_type SecondType;
5748
5749 template <typename FirstMatcher, typename SecondMatcher>
5750 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
5751 : first_matcher_(
5752 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
5753 second_matcher_(
5754 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
5755 }
5756
5757 // Describes what this matcher does.
5758 void DescribeTo(::std::ostream* os) const override {
5759 *os << "has a first field that ";
5760 first_matcher_.DescribeTo(os);
5761 *os << ", and has a second field that ";
5762 second_matcher_.DescribeTo(os);
5763 }
5764
5765 // Describes what the negation of this matcher does.
5766 void DescribeNegationTo(::std::ostream* os) const override {
5767 *os << "has a first field that ";
5768 first_matcher_.DescribeNegationTo(os);
5769 *os << ", or has a second field that ";
5770 second_matcher_.DescribeNegationTo(os);
5771 }
5772
5773 // Returns true if and only if 'a_pair.first' matches first_matcher and
5774 // 'a_pair.second' matches second_matcher.
5775 bool MatchAndExplain(PairType a_pair,
5776 MatchResultListener* listener) const override {
5777 if (!listener->IsInterested()) {
5778 // If the listener is not interested, we don't need to construct the
5779 // explanation.
5780 return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
5781 second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
5782 }
5783 StringMatchResultListener first_inner_listener;
5784 if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
5785 &first_inner_listener)) {
5786 *listener << "whose first field does not match";
5787 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
5788 return false;
5789 }
5790 StringMatchResultListener second_inner_listener;
5791 if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
5792 &second_inner_listener)) {
5793 *listener << "whose second field does not match";
5794 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
5795 return false;
5796 }
5797 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
5798 listener);
5799 return true;
5800 }
5801
5802 private:
5803 void ExplainSuccess(const std::string& first_explanation,
5804 const std::string& second_explanation,
5805 MatchResultListener* listener) const {
5806 *listener << "whose both fields match";
5807 if (first_explanation != "") {
5808 *listener << ", where the first field is a value " << first_explanation;
5809 }
5810 if (second_explanation != "") {
5811 *listener << ", ";
5812 if (first_explanation != "") {
5813 *listener << "and ";
5814 } else {
5815 *listener << "where ";
5816 }
5817 *listener << "the second field is a value " << second_explanation;
5818 }
5819 }
5820
5821 const Matcher<const FirstType&> first_matcher_;
5822 const Matcher<const SecondType&> second_matcher_;
5823 };
5824
5825 // Implements polymorphic Pair(first_matcher, second_matcher).
5826 template <typename FirstMatcher, typename SecondMatcher>
5827 class PairMatcher {
5828 public:
5829 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
5830 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
5831
5832 template <typename PairType>
5833 operator Matcher<PairType> () const {
5834 return Matcher<PairType>(
5835 new PairMatcherImpl<const PairType&>(first_matcher_, second_matcher_));
5836 }
5837
5838 private:
5839 const FirstMatcher first_matcher_;
5840 const SecondMatcher second_matcher_;
5841 };
5842
5843 template <typename T, size_t... I>
5844 auto UnpackStructImpl(const T& t, IndexSequence<I...>, int)
5845 -> decltype(std::tie(get<I>(t)...)) {
5846 static_assert(std::tuple_size<T>::value == sizeof...(I),
5847 "Number of arguments doesn't match the number of fields.");
5848 return std::tie(get<I>(t)...);
5849 }
5850
5851 #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
5852 template <typename T>
5853 auto UnpackStructImpl(const T& t, MakeIndexSequence<1>, char) {
5854 const auto& [a] = t;
5855 return std::tie(a);
5856 }
5857 template <typename T>
5858 auto UnpackStructImpl(const T& t, MakeIndexSequence<2>, char) {
5859 const auto& [a, b] = t;
5860 return std::tie(a, b);
5861 }
5862 template <typename T>
5863 auto UnpackStructImpl(const T& t, MakeIndexSequence<3>, char) {
5864 const auto& [a, b, c] = t;
5865 return std::tie(a, b, c);
5866 }
5867 template <typename T>
5868 auto UnpackStructImpl(const T& t, MakeIndexSequence<4>, char) {
5869 const auto& [a, b, c, d] = t;
5870 return std::tie(a, b, c, d);
5871 }
5872 template <typename T>
5873 auto UnpackStructImpl(const T& t, MakeIndexSequence<5>, char) {
5874 const auto& [a, b, c, d, e] = t;
5875 return std::tie(a, b, c, d, e);
5876 }
5877 template <typename T>
5878 auto UnpackStructImpl(const T& t, MakeIndexSequence<6>, char) {
5879 const auto& [a, b, c, d, e, f] = t;
5880 return std::tie(a, b, c, d, e, f);
5881 }
5882 template <typename T>
5883 auto UnpackStructImpl(const T& t, MakeIndexSequence<7>, char) {
5884 const auto& [a, b, c, d, e, f, g] = t;
5885 return std::tie(a, b, c, d, e, f, g);
5886 }
5887 template <typename T>
5888 auto UnpackStructImpl(const T& t, MakeIndexSequence<8>, char) {
5889 const auto& [a, b, c, d, e, f, g, h] = t;
5890 return std::tie(a, b, c, d, e, f, g, h);
5891 }
5892 template <typename T>
5893 auto UnpackStructImpl(const T& t, MakeIndexSequence<9>, char) {
5894 const auto& [a, b, c, d, e, f, g, h, i] = t;
5895 return std::tie(a, b, c, d, e, f, g, h, i);
5896 }
5897 template <typename T>
5898 auto UnpackStructImpl(const T& t, MakeIndexSequence<10>, char) {
5899 const auto& [a, b, c, d, e, f, g, h, i, j] = t;
5900 return std::tie(a, b, c, d, e, f, g, h, i, j);
5901 }
5902 template <typename T>
5903 auto UnpackStructImpl(const T& t, MakeIndexSequence<11>, char) {
5904 const auto& [a, b, c, d, e, f, g, h, i, j, k] = t;
5905 return std::tie(a, b, c, d, e, f, g, h, i, j, k);
5906 }
5907 template <typename T>
5908 auto UnpackStructImpl(const T& t, MakeIndexSequence<12>, char) {
5909 const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t;
5910 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l);
5911 }
5912 template <typename T>
5913 auto UnpackStructImpl(const T& t, MakeIndexSequence<13>, char) {
5914 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t;
5915 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m);
5916 }
5917 template <typename T>
5918 auto UnpackStructImpl(const T& t, MakeIndexSequence<14>, char) {
5919 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t;
5920 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
5921 }
5922 template <typename T>
5923 auto UnpackStructImpl(const T& t, MakeIndexSequence<15>, char) {
5924 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t;
5925 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);
5926 }
5927 template <typename T>
5928 auto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) {
5929 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;
5930 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);
5931 }
5932 #endif // defined(__cpp_structured_bindings)
5933
5934 template <size_t I, typename T>
5935 auto UnpackStruct(const T& t)
5936 -> decltype((UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0)) {
5937 return (UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0);
5938 }
5939
5940 // Helper function to do comma folding in C++11.
5941 // The array ensures left-to-right order of evaluation.
5942 // Usage: VariadicExpand({expr...});
5943 template <typename T, size_t N>
5944 void VariadicExpand(const T (&)[N]) {}
5945
5946 template <typename Struct, typename StructSize>
5947 class FieldsAreMatcherImpl;
5948
5949 template <typename Struct, size_t... I>
5950 class FieldsAreMatcherImpl<Struct, IndexSequence<I...>>
5951 : public MatcherInterface<Struct> {
5952 using UnpackedType =
5953 decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>()));
5954 using MatchersType = std::tuple<
5955 Matcher<const typename std::tuple_element<I, UnpackedType>::type&>...>;
5956
5957 public:
5958 template <typename Inner>
5959 explicit FieldsAreMatcherImpl(const Inner& matchers)
5960 : matchers_(testing::SafeMatcherCast<
5961 const typename std::tuple_element<I, UnpackedType>::type&>(
5962 std::get<I>(matchers))...) {}
5963
5964 void DescribeTo(::std::ostream* os) const override {
5965 const char* separator = "";
5966 VariadicExpand(
5967 {(*os << separator << "has field #" << I << " that ",
5968 std::get<I>(matchers_).DescribeTo(os), separator = ", and ")...});
5969 }
5970
5971 void DescribeNegationTo(::std::ostream* os) const override {
5972 const char* separator = "";
5973 VariadicExpand({(*os << separator << "has field #" << I << " that ",
5974 std::get<I>(matchers_).DescribeNegationTo(os),
5975 separator = ", or ")...});
5976 }
5977
5978 bool MatchAndExplain(Struct t, MatchResultListener* listener) const override {
5979 return MatchInternal((UnpackStruct<sizeof...(I)>)(t), listener);
5980 }
5981
5982 private:
5983 bool MatchInternal(UnpackedType tuple, MatchResultListener* listener) const {
5984 if (!listener->IsInterested()) {
5985 // If the listener is not interested, we don't need to construct the
5986 // explanation.
5987 bool good = true;
5988 VariadicExpand({good = good && std::get<I>(matchers_).Matches(
5989 std::get<I>(tuple))...});
5990 return good;
5991 }
5992
5993 size_t failed_pos = ~size_t{};
5994
5995 std::vector<StringMatchResultListener> inner_listener(sizeof...(I));
5996
5997 VariadicExpand(
5998 {failed_pos == ~size_t{} && !std::get<I>(matchers_).MatchAndExplain(
5999 std::get<I>(tuple), &inner_listener[I])
6000 ? failed_pos = I
6001 : 0 ...});
6002 if (failed_pos != ~size_t{}) {
6003 *listener << "whose field #" << failed_pos << " does not match";
6004 PrintIfNotEmpty(inner_listener[failed_pos].str(), listener->stream());
6005 return false;
6006 }
6007
6008 *listener << "whose all elements match";
6009 const char* separator = ", where";
6010 for (size_t index = 0; index < sizeof...(I); ++index) {
6011 const std::string str = inner_listener[index].str();
6012 if (!str.empty()) {
6013 *listener << separator << " field #" << index << " is a value " << str;
6014 separator = ", and";
6015 }
6016 }
6017
6018 return true;
6019 }
6020
6021 MatchersType matchers_;
6022 };
6023
6024 template <typename... Inner>
6025 class FieldsAreMatcher {
6026 public:
6027 explicit FieldsAreMatcher(Inner... inner) : matchers_(std::move(inner)...) {}
6028
6029 template <typename Struct>
6030 operator Matcher<Struct>() const { // NOLINT
6031 return Matcher<Struct>(
6032 new FieldsAreMatcherImpl<const Struct&, IndexSequenceFor<Inner...>>(
6033 matchers_));
6034 }
6035
6036 private:
6037 std::tuple<Inner...> matchers_;
6038 };
6039
6040 // Implements ElementsAre() and ElementsAreArray().
6041 template <typename Container>
6042 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
6043 public:
6044 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6045 typedef internal::StlContainerView<RawContainer> View;
6046 typedef typename View::type StlContainer;
6047 typedef typename View::const_reference StlContainerReference;
6048 typedef typename StlContainer::value_type Element;
6049
6050 // Constructs the matcher from a sequence of element values or
6051 // element matchers.
6052 template <typename InputIter>
6053 ElementsAreMatcherImpl(InputIter first, InputIter last) {
6054 while (first != last) {
6055 matchers_.push_back(MatcherCast<const Element&>(*first++));
6056 }
6057 }
6058
6059 // Describes what this matcher does.
6060 void DescribeTo(::std::ostream* os) const override {
6061 if (count() == 0) {
6062 *os << "is empty";
6063 } else if (count() == 1) {
6064 *os << "has 1 element that ";
6065 matchers_[0].DescribeTo(os);
6066 } else {
6067 *os << "has " << Elements(count()) << " where\n";
6068 for (size_t i = 0; i != count(); ++i) {
6069 *os << "element #" << i << " ";
6070 matchers_[i].DescribeTo(os);
6071 if (i + 1 < count()) {
6072 *os << ",\n";
6073 }
6074 }
6075 }
6076 }
6077
6078 // Describes what the negation of this matcher does.
6079 void DescribeNegationTo(::std::ostream* os) const override {
6080 if (count() == 0) {
6081 *os << "isn't empty";
6082 return;
6083 }
6084
6085 *os << "doesn't have " << Elements(count()) << ", or\n";
6086 for (size_t i = 0; i != count(); ++i) {
6087 *os << "element #" << i << " ";
6088 matchers_[i].DescribeNegationTo(os);
6089 if (i + 1 < count()) {
6090 *os << ", or\n";
6091 }
6092 }
6093 }
6094
6095 bool MatchAndExplain(Container container,
6096 MatchResultListener* listener) const override {
6097 // To work with stream-like "containers", we must only walk
6098 // through the elements in one pass.
6099
6100 const bool listener_interested = listener->IsInterested();
6101
6102 // explanations[i] is the explanation of the element at index i.
6103 ::std::vector<std::string> explanations(count());
6104 StlContainerReference stl_container = View::ConstReference(container);
6105 typename StlContainer::const_iterator it = stl_container.begin();
6106 size_t exam_pos = 0;
6107 bool mismatch_found = false; // Have we found a mismatched element yet?
6108
6109 // Go through the elements and matchers in pairs, until we reach
6110 // the end of either the elements or the matchers, or until we find a
6111 // mismatch.
6112 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
6113 bool match; // Does the current element match the current matcher?
6114 if (listener_interested) {
6115 StringMatchResultListener s;
6116 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
6117 explanations[exam_pos] = s.str();
6118 } else {
6119 match = matchers_[exam_pos].Matches(*it);
6120 }
6121
6122 if (!match) {
6123 mismatch_found = true;
6124 break;
6125 }
6126 }
6127 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
6128
6129 // Find how many elements the actual container has. We avoid
6130 // calling size() s.t. this code works for stream-like "containers"
6131 // that don't define size().
6132 size_t actual_count = exam_pos;
6133 for (; it != stl_container.end(); ++it) {
6134 ++actual_count;
6135 }
6136
6137 if (actual_count != count()) {
6138 // The element count doesn't match. If the container is empty,
6139 // there's no need to explain anything as Google Mock already
6140 // prints the empty container. Otherwise we just need to show
6141 // how many elements there actually are.
6142 if (listener_interested && (actual_count != 0)) {
6143 *listener << "which has " << Elements(actual_count);
6144 }
6145 return false;
6146 }
6147
6148 if (mismatch_found) {
6149 // The element count matches, but the exam_pos-th element doesn't match.
6150 if (listener_interested) {
6151 *listener << "whose element #" << exam_pos << " doesn't match";
6152 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
6153 }
6154 return false;
6155 }
6156
6157 // Every element matches its expectation. We need to explain why
6158 // (the obvious ones can be skipped).
6159 if (listener_interested) {
6160 bool reason_printed = false;
6161 for (size_t i = 0; i != count(); ++i) {
6162 const std::string& s = explanations[i];
6163 if (!s.empty()) {
6164 if (reason_printed) {
6165 *listener << ",\nand ";
6166 }
6167 *listener << "whose element #" << i << " matches, " << s;
6168 reason_printed = true;
6169 }
6170 }
6171 }
6172 return true;
6173 }
6174
6175 private:
6176 static Message Elements(size_t count) {
6177 return Message() << count << (count == 1 ? " element" : " elements");
6178 }
6179
6180 size_t count() const { return matchers_.size(); }
6181
6182 ::std::vector<Matcher<const Element&> > matchers_;
6183 };
6184
6185 // Connectivity matrix of (elements X matchers), in element-major order.
6186 // Initially, there are no edges.
6187 // Use NextGraph() to iterate over all possible edge configurations.
6188 // Use Randomize() to generate a random edge configuration.
6189 class GTEST_API_ MatchMatrix {
6190 public:
6191 MatchMatrix(size_t num_elements, size_t num_matchers)
6192 : num_elements_(num_elements),
6193 num_matchers_(num_matchers),
6194 matched_(num_elements_* num_matchers_, 0) {
6195 }
6196
6197 size_t LhsSize() const { return num_elements_; }
6198 size_t RhsSize() const { return num_matchers_; }
6199 bool HasEdge(size_t ilhs, size_t irhs) const {
6200 return matched_[SpaceIndex(ilhs, irhs)] == 1;
6201 }
6202 void SetEdge(size_t ilhs, size_t irhs, bool b) {
6203 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
6204 }
6205
6206 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
6207 // adds 1 to that number; returns false if incrementing the graph left it
6208 // empty.
6209 bool NextGraph();
6210
6211 void Randomize();
6212
6213 std::string DebugString() const;
6214
6215 private:
6216 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
6217 return ilhs * num_matchers_ + irhs;
6218 }
6219
6220 size_t num_elements_;
6221 size_t num_matchers_;
6222
6223 // Each element is a char interpreted as bool. They are stored as a
6224 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
6225 // a (ilhs, irhs) matrix coordinate into an offset.
6226 ::std::vector<char> matched_;
6227 };
6228
6229 typedef ::std::pair<size_t, size_t> ElementMatcherPair;
6230 typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
6231
6232 // Returns a maximum bipartite matching for the specified graph 'g'.
6233 // The matching is represented as a vector of {element, matcher} pairs.
6234 GTEST_API_ ElementMatcherPairs
6235 FindMaxBipartiteMatching(const MatchMatrix& g);
6236
6237 struct UnorderedMatcherRequire {
6238 enum Flags {
6239 Superset = 1 << 0,
6240 Subset = 1 << 1,
6241 ExactMatch = Superset | Subset,
6242 };
6243 };
6244
6245 // Untyped base class for implementing UnorderedElementsAre. By
6246 // putting logic that's not specific to the element type here, we
6247 // reduce binary bloat and increase compilation speed.
6248 class GTEST_API_ UnorderedElementsAreMatcherImplBase {
6249 protected:
6250 explicit UnorderedElementsAreMatcherImplBase(
6251 UnorderedMatcherRequire::Flags matcher_flags)
6252 : match_flags_(matcher_flags) {}
6253
6254 // A vector of matcher describers, one for each element matcher.
6255 // Does not own the describers (and thus can be used only when the
6256 // element matchers are alive).
6257 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
6258
6259 // Describes this UnorderedElementsAre matcher.
6260 void DescribeToImpl(::std::ostream* os) const;
6261
6262 // Describes the negation of this UnorderedElementsAre matcher.
6263 void DescribeNegationToImpl(::std::ostream* os) const;
6264
6265 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
6266 const MatchMatrix& matrix,
6267 MatchResultListener* listener) const;
6268
6269 bool FindPairing(const MatchMatrix& matrix,
6270 MatchResultListener* listener) const;
6271
6272 MatcherDescriberVec& matcher_describers() {
6273 return matcher_describers_;
6274 }
6275
6276 static Message Elements(size_t n) {
6277 return Message() << n << " element" << (n == 1 ? "" : "s");
6278 }
6279
6280 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
6281
6282 private:
6283 UnorderedMatcherRequire::Flags match_flags_;
6284 MatcherDescriberVec matcher_describers_;
6285 };
6286
6287 // Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
6288 // IsSupersetOf.
6289 template <typename Container>
6290 class UnorderedElementsAreMatcherImpl
6291 : public MatcherInterface<Container>,
6292 public UnorderedElementsAreMatcherImplBase {
6293 public:
6294 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6295 typedef internal::StlContainerView<RawContainer> View;
6296 typedef typename View::type StlContainer;
6297 typedef typename View::const_reference StlContainerReference;
6298 typedef typename StlContainer::const_iterator StlContainerConstIterator;
6299 typedef typename StlContainer::value_type Element;
6300
6301 template <typename InputIter>
6302 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
6303 InputIter first, InputIter last)
6304 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
6305 for (; first != last; ++first) {
6306 matchers_.push_back(MatcherCast<const Element&>(*first));
6307 }
6308 for (const auto& m : matchers_) {
6309 matcher_describers().push_back(m.GetDescriber());
6310 }
6311 }
6312
6313 // Describes what this matcher does.
6314 void DescribeTo(::std::ostream* os) const override {
6315 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
6316 }
6317
6318 // Describes what the negation of this matcher does.
6319 void DescribeNegationTo(::std::ostream* os) const override {
6320 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
6321 }
6322
6323 bool MatchAndExplain(Container container,
6324 MatchResultListener* listener) const override {
6325 StlContainerReference stl_container = View::ConstReference(container);
6326 ::std::vector<std::string> element_printouts;
6327 MatchMatrix matrix =
6328 AnalyzeElements(stl_container.begin(), stl_container.end(),
6329 &element_printouts, listener);
6330
6331 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
6332 return true;
6333 }
6334
6335 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
6336 if (matrix.LhsSize() != matrix.RhsSize()) {
6337 // The element count doesn't match. If the container is empty,
6338 // there's no need to explain anything as Google Mock already
6339 // prints the empty container. Otherwise we just need to show
6340 // how many elements there actually are.
6341 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
6342 *listener << "which has " << Elements(matrix.LhsSize());
6343 }
6344 return false;
6345 }
6346 }
6347
6348 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
6349 FindPairing(matrix, listener);
6350 }
6351
6352 private:
6353 template <typename ElementIter>
6354 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
6355 ::std::vector<std::string>* element_printouts,
6356 MatchResultListener* listener) const {
6357 element_printouts->clear();
6358 ::std::vector<char> did_match;
6359 size_t num_elements = 0;
6360 DummyMatchResultListener dummy;
6361 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
6362 if (listener->IsInterested()) {
6363 element_printouts->push_back(PrintToString(*elem_first));
6364 }
6365 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
6366 did_match.push_back(
6367 matchers_[irhs].MatchAndExplain(*elem_first, &dummy));
6368 }
6369 }
6370
6371 MatchMatrix matrix(num_elements, matchers_.size());
6372 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
6373 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
6374 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
6375 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
6376 }
6377 }
6378 return matrix;
6379 }
6380
6381 ::std::vector<Matcher<const Element&> > matchers_;
6382 };
6383
6384 // Functor for use in TransformTuple.
6385 // Performs MatcherCast<Target> on an input argument of any type.
6386 template <typename Target>
6387 struct CastAndAppendTransform {
6388 template <typename Arg>
6389 Matcher<Target> operator()(const Arg& a) const {
6390 return MatcherCast<Target>(a);
6391 }
6392 };
6393
6394 // Implements UnorderedElementsAre.
6395 template <typename MatcherTuple>
6396 class UnorderedElementsAreMatcher {
6397 public:
6398 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
6399 : matchers_(args) {}
6400
6401 template <typename Container>
6402 operator Matcher<Container>() const {
6403 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6404 typedef typename internal::StlContainerView<RawContainer>::type View;
6405 typedef typename View::value_type Element;
6406 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
6407 MatcherVec matchers;
6408 matchers.reserve(::std::tuple_size<MatcherTuple>::value);
6409 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
6410 ::std::back_inserter(matchers));
6411 return Matcher<Container>(
6412 new UnorderedElementsAreMatcherImpl<const Container&>(
6413 UnorderedMatcherRequire::ExactMatch, matchers.begin(),
6414 matchers.end()));
6415 }
6416
6417 private:
6418 const MatcherTuple matchers_;
6419 };
6420
6421 // Implements ElementsAre.
6422 template <typename MatcherTuple>
6423 class ElementsAreMatcher {
6424 public:
6425 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
6426
6427 template <typename Container>
6428 operator Matcher<Container>() const {
6429 GTEST_COMPILE_ASSERT_(
6430 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
6431 ::std::tuple_size<MatcherTuple>::value < 2,
6432 use_UnorderedElementsAre_with_hash_tables);
6433
6434 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6435 typedef typename internal::StlContainerView<RawContainer>::type View;
6436 typedef typename View::value_type Element;
6437 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
6438 MatcherVec matchers;
6439 matchers.reserve(::std::tuple_size<MatcherTuple>::value);
6440 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
6441 ::std::back_inserter(matchers));
6442 return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(
6443 matchers.begin(), matchers.end()));
6444 }
6445
6446 private:
6447 const MatcherTuple matchers_;
6448 };
6449
6450 // Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
6451 template <typename T>
6452 class UnorderedElementsAreArrayMatcher {
6453 public:
6454 template <typename Iter>
6455 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
6456 Iter first, Iter last)
6457 : match_flags_(match_flags), matchers_(first, last) {}
6458
6459 template <typename Container>
6460 operator Matcher<Container>() const {
6461 return Matcher<Container>(
6462 new UnorderedElementsAreMatcherImpl<const Container&>(
6463 match_flags_, matchers_.begin(), matchers_.end()));
6464 }
6465
6466 private:
6467 UnorderedMatcherRequire::Flags match_flags_;
6468 ::std::vector<T> matchers_;
6469 };
6470
6471 // Implements ElementsAreArray().
6472 template <typename T>
6473 class ElementsAreArrayMatcher {
6474 public:
6475 template <typename Iter>
6476 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
6477
6478 template <typename Container>
6479 operator Matcher<Container>() const {
6480 GTEST_COMPILE_ASSERT_(
6481 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
6482 use_UnorderedElementsAreArray_with_hash_tables);
6483
6484 return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(
6485 matchers_.begin(), matchers_.end()));
6486 }
6487
6488 private:
6489 const ::std::vector<T> matchers_;
6490 };
6491
6492 // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
6493 // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
6494 // second) is a polymorphic matcher that matches a value x if and only if
6495 // tm matches tuple (x, second). Useful for implementing
6496 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
6497 //
6498 // BoundSecondMatcher is copyable and assignable, as we need to put
6499 // instances of this class in a vector when implementing
6500 // UnorderedPointwise().
6501 template <typename Tuple2Matcher, typename Second>
6502 class BoundSecondMatcher {
6503 public:
6504 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
6505 : tuple2_matcher_(tm), second_value_(second) {}
6506
6507 BoundSecondMatcher(const BoundSecondMatcher& other) = default;
6508
6509 template <typename T>
6510 operator Matcher<T>() const {
6511 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
6512 }
6513
6514 // We have to define this for UnorderedPointwise() to compile in
6515 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
6516 // which requires the elements to be assignable in C++98. The
6517 // compiler cannot generate the operator= for us, as Tuple2Matcher
6518 // and Second may not be assignable.
6519 //
6520 // However, this should never be called, so the implementation just
6521 // need to assert.
6522 void operator=(const BoundSecondMatcher& /*rhs*/) {
6523 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
6524 }
6525
6526 private:
6527 template <typename T>
6528 class Impl : public MatcherInterface<T> {
6529 public:
6530 typedef ::std::tuple<T, Second> ArgTuple;
6531
6532 Impl(const Tuple2Matcher& tm, const Second& second)
6533 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
6534 second_value_(second) {}
6535
6536 void DescribeTo(::std::ostream* os) const override {
6537 *os << "and ";
6538 UniversalPrint(second_value_, os);
6539 *os << " ";
6540 mono_tuple2_matcher_.DescribeTo(os);
6541 }
6542
6543 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
6544 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
6545 listener);
6546 }
6547
6548 private:
6549 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
6550 const Second second_value_;
6551 };
6552
6553 const Tuple2Matcher tuple2_matcher_;
6554 const Second second_value_;
6555 };
6556
6557 // Given a 2-tuple matcher tm and a value second,
6558 // MatcherBindSecond(tm, second) returns a matcher that matches a
6559 // value x if and only if tm matches tuple (x, second). Useful for
6560 // implementing UnorderedPointwise() in terms of UnorderedElementsAreArray().
6561 template <typename Tuple2Matcher, typename Second>
6562 BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
6563 const Tuple2Matcher& tm, const Second& second) {
6564 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
6565 }
6566
6567 // Returns the description for a matcher defined using the MATCHER*()
6568 // macro where the user-supplied description string is "", if
6569 // 'negation' is false; otherwise returns the description of the
6570 // negation of the matcher. 'param_values' contains a list of strings
6571 // that are the print-out of the matcher's parameters.
6572 GTEST_API_ std::string FormatMatcherDescription(bool negation,
6573 const char* matcher_name,
6574 const Strings& param_values);
6575
6576 // Implements a matcher that checks the value of a optional<> type variable.
6577 template <typename ValueMatcher>
6578 class OptionalMatcher {
6579 public:
6580 explicit OptionalMatcher(const ValueMatcher& value_matcher)
6581 : value_matcher_(value_matcher) {}
6582
6583 template <typename Optional>
6584 operator Matcher<Optional>() const {
6585 return Matcher<Optional>(new Impl<const Optional&>(value_matcher_));
6586 }
6587
6588 template <typename Optional>
6589 class Impl : public MatcherInterface<Optional> {
6590 public:
6591 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
6592 typedef typename OptionalView::value_type ValueType;
6593 explicit Impl(const ValueMatcher& value_matcher)
6594 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
6595
6596 void DescribeTo(::std::ostream* os) const override {
6597 *os << "value ";
6598 value_matcher_.DescribeTo(os);
6599 }
6600
6601 void DescribeNegationTo(::std::ostream* os) const override {
6602 *os << "value ";
6603 value_matcher_.DescribeNegationTo(os);
6604 }
6605
6606 bool MatchAndExplain(Optional optional,
6607 MatchResultListener* listener) const override {
6608 if (!optional) {
6609 *listener << "which is not engaged";
6610 return false;
6611 }
6612 const ValueType& value = *optional;
6613 StringMatchResultListener value_listener;
6614 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
6615 *listener << "whose value " << PrintToString(value)
6616 << (match ? " matches" : " doesn't match");
6617 PrintIfNotEmpty(value_listener.str(), listener->stream());
6618 return match;
6619 }
6620
6621 private:
6622 const Matcher<ValueType> value_matcher_;
6623 };
6624
6625 private:
6626 const ValueMatcher value_matcher_;
6627 };
6628
6629 namespace variant_matcher {
6630 // Overloads to allow VariantMatcher to do proper ADL lookup.
6631 template <typename T>
6632 void holds_alternative() {}
6633 template <typename T>
6634 void get() {}
6635
6636 // Implements a matcher that checks the value of a variant<> type variable.
6637 template <typename T>
6638 class VariantMatcher {
6639 public:
6640 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
6641 : matcher_(std::move(matcher)) {}
6642
6643 template <typename Variant>
6644 bool MatchAndExplain(const Variant& value,
6645 ::testing::MatchResultListener* listener) const {
6646 using std::get;
6647 if (!listener->IsInterested()) {
6648 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
6649 }
6650
6651 if (!holds_alternative<T>(value)) {
6652 *listener << "whose value is not of type '" << GetTypeName() << "'";
6653 return false;
6654 }
6655
6656 const T& elem = get<T>(value);
6657 StringMatchResultListener elem_listener;
6658 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
6659 *listener << "whose value " << PrintToString(elem)
6660 << (match ? " matches" : " doesn't match");
6661 PrintIfNotEmpty(elem_listener.str(), listener->stream());
6662 return match;
6663 }
6664
6665 void DescribeTo(std::ostream* os) const {
6666 *os << "is a variant<> with value of type '" << GetTypeName()
6667 << "' and the value ";
6668 matcher_.DescribeTo(os);
6669 }
6670
6671 void DescribeNegationTo(std::ostream* os) const {
6672 *os << "is a variant<> with value of type other than '" << GetTypeName()
6673 << "' or the value ";
6674 matcher_.DescribeNegationTo(os);
6675 }
6676
6677 private:
6678 static std::string GetTypeName() {
6679 #if GTEST_HAS_RTTI
6680 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
6681 return internal::GetTypeName<T>());
6682 #endif
6683 return "the element type";
6684 }
6685
6686 const ::testing::Matcher<const T&> matcher_;
6687 };
6688
6689 } // namespace variant_matcher
6690
6691 namespace any_cast_matcher {
6692
6693 // Overloads to allow AnyCastMatcher to do proper ADL lookup.
6694 template <typename T>
6695 void any_cast() {}
6696
6697 // Implements a matcher that any_casts the value.
6698 template <typename T>
6699 class AnyCastMatcher {
6700 public:
6701 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
6702 : matcher_(matcher) {}
6703
6704 template <typename AnyType>
6705 bool MatchAndExplain(const AnyType& value,
6706 ::testing::MatchResultListener* listener) const {
6707 if (!listener->IsInterested()) {
6708 const T* ptr = any_cast<T>(&value);
6709 return ptr != nullptr && matcher_.Matches(*ptr);
6710 }
6711
6712 const T* elem = any_cast<T>(&value);
6713 if (elem == nullptr) {
6714 *listener << "whose value is not of type '" << GetTypeName() << "'";
6715 return false;
6716 }
6717
6718 StringMatchResultListener elem_listener;
6719 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
6720 *listener << "whose value " << PrintToString(*elem)
6721 << (match ? " matches" : " doesn't match");
6722 PrintIfNotEmpty(elem_listener.str(), listener->stream());
6723 return match;
6724 }
6725
6726 void DescribeTo(std::ostream* os) const {
6727 *os << "is an 'any' type with value of type '" << GetTypeName()
6728 << "' and the value ";
6729 matcher_.DescribeTo(os);
6730 }
6731
6732 void DescribeNegationTo(std::ostream* os) const {
6733 *os << "is an 'any' type with value of type other than '" << GetTypeName()
6734 << "' or the value ";
6735 matcher_.DescribeNegationTo(os);
6736 }
6737
6738 private:
6739 static std::string GetTypeName() {
6740 #if GTEST_HAS_RTTI
6741 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
6742 return internal::GetTypeName<T>());
6743 #endif
6744 return "the element type";
6745 }
6746
6747 const ::testing::Matcher<const T&> matcher_;
6748 };
6749
6750 } // namespace any_cast_matcher
6751
6752 // Implements the Args() matcher.
6753 template <class ArgsTuple, size_t... k>
6754 class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
6755 public:
6756 using RawArgsTuple = typename std::decay<ArgsTuple>::type;
6757 using SelectedArgs =
6758 std::tuple<typename std::tuple_element<k, RawArgsTuple>::type...>;
6759 using MonomorphicInnerMatcher = Matcher<const SelectedArgs&>;
6760
6761 template <typename InnerMatcher>
6762 explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)
6763 : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}
6764
6765 bool MatchAndExplain(ArgsTuple args,
6766 MatchResultListener* listener) const override {
6767 // Workaround spurious C4100 on MSVC<=15.7 when k is empty.
6768 (void)args;
6769 const SelectedArgs& selected_args =
6770 std::forward_as_tuple(std::get<k>(args)...);
6771 if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args);
6772
6773 PrintIndices(listener->stream());
6774 *listener << "are " << PrintToString(selected_args);
6775
6776 StringMatchResultListener inner_listener;
6777 const bool match =
6778 inner_matcher_.MatchAndExplain(selected_args, &inner_listener);
6779 PrintIfNotEmpty(inner_listener.str(), listener->stream());
6780 return match;
6781 }
6782
6783 void DescribeTo(::std::ostream* os) const override {
6784 *os << "are a tuple ";
6785 PrintIndices(os);
6786 inner_matcher_.DescribeTo(os);
6787 }
6788
6789 void DescribeNegationTo(::std::ostream* os) const override {
6790 *os << "are a tuple ";
6791 PrintIndices(os);
6792 inner_matcher_.DescribeNegationTo(os);
6793 }
6794
6795 private:
6796 // Prints the indices of the selected fields.
6797 static void PrintIndices(::std::ostream* os) {
6798 *os << "whose fields (";
6799 const char* sep = "";
6800 // Workaround spurious C4189 on MSVC<=15.7 when k is empty.
6801 (void)sep;
6802 const char* dummy[] = {"", (*os << sep << "#" << k, sep = ", ")...};
6803 (void)dummy;
6804 *os << ") ";
6805 }
6806
6807 MonomorphicInnerMatcher inner_matcher_;
6808 };
6809
6810 template <class InnerMatcher, size_t... k>
6811 class ArgsMatcher {
6812 public:
6813 explicit ArgsMatcher(InnerMatcher inner_matcher)
6814 : inner_matcher_(std::move(inner_matcher)) {}
6815
6816 template <typename ArgsTuple>
6817 operator Matcher<ArgsTuple>() const { // NOLINT
6818 return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k...>(inner_matcher_));
6819 }
6820
6821 private:
6822 InnerMatcher inner_matcher_;
6823 };
6824
6825 } // namespace internal
6826
6827 // ElementsAreArray(iterator_first, iterator_last)
6828 // ElementsAreArray(pointer, count)
6829 // ElementsAreArray(array)
6830 // ElementsAreArray(container)
6831 // ElementsAreArray({ e1, e2, ..., en })
6832 //
6833 // The ElementsAreArray() functions are like ElementsAre(...), except
6834 // that they are given a homogeneous sequence rather than taking each
6835 // element as a function argument. The sequence can be specified as an
6836 // array, a pointer and count, a vector, an initializer list, or an
6837 // STL iterator range. In each of these cases, the underlying sequence
6838 // can be either a sequence of values or a sequence of matchers.
6839 //
6840 // All forms of ElementsAreArray() make a copy of the input matcher sequence.
6841
6842 template <typename Iter>
6843 inline internal::ElementsAreArrayMatcher<
6844 typename ::std::iterator_traits<Iter>::value_type>
6845 ElementsAreArray(Iter first, Iter last) {
6846 typedef typename ::std::iterator_traits<Iter>::value_type T;
6847 return internal::ElementsAreArrayMatcher<T>(first, last);
6848 }
6849
6850 template <typename T>
6851 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
6852 const T* pointer, size_t count) {
6853 return ElementsAreArray(pointer, pointer + count);
6854 }
6855
6856 template <typename T, size_t N>
6857 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
6858 const T (&array)[N]) {
6859 return ElementsAreArray(array, N);
6860 }
6861
6862 template <typename Container>
6863 inline internal::ElementsAreArrayMatcher<typename Container::value_type>
6864 ElementsAreArray(const Container& container) {
6865 return ElementsAreArray(container.begin(), container.end());
6866 }
6867
6868 template <typename T>
6869 inline internal::ElementsAreArrayMatcher<T>
6870 ElementsAreArray(::std::initializer_list<T> xs) {
6871 return ElementsAreArray(xs.begin(), xs.end());
6872 }
6873
6874 // UnorderedElementsAreArray(iterator_first, iterator_last)
6875 // UnorderedElementsAreArray(pointer, count)
6876 // UnorderedElementsAreArray(array)
6877 // UnorderedElementsAreArray(container)
6878 // UnorderedElementsAreArray({ e1, e2, ..., en })
6879 //
6880 // UnorderedElementsAreArray() verifies that a bijective mapping onto a
6881 // collection of matchers exists.
6882 //
6883 // The matchers can be specified as an array, a pointer and count, a container,
6884 // an initializer list, or an STL iterator range. In each of these cases, the
6885 // underlying matchers can be either values or matchers.
6886
6887 template <typename Iter>
6888 inline internal::UnorderedElementsAreArrayMatcher<
6889 typename ::std::iterator_traits<Iter>::value_type>
6890 UnorderedElementsAreArray(Iter first, Iter last) {
6891 typedef typename ::std::iterator_traits<Iter>::value_type T;
6892 return internal::UnorderedElementsAreArrayMatcher<T>(
6893 internal::UnorderedMatcherRequire::ExactMatch, first, last);
6894 }
6895
6896 template <typename T>
6897 inline internal::UnorderedElementsAreArrayMatcher<T>
6898 UnorderedElementsAreArray(const T* pointer, size_t count) {
6899 return UnorderedElementsAreArray(pointer, pointer + count);
6900 }
6901
6902 template <typename T, size_t N>
6903 inline internal::UnorderedElementsAreArrayMatcher<T>
6904 UnorderedElementsAreArray(const T (&array)[N]) {
6905 return UnorderedElementsAreArray(array, N);
6906 }
6907
6908 template <typename Container>
6909 inline internal::UnorderedElementsAreArrayMatcher<
6910 typename Container::value_type>
6911 UnorderedElementsAreArray(const Container& container) {
6912 return UnorderedElementsAreArray(container.begin(), container.end());
6913 }
6914
6915 template <typename T>
6916 inline internal::UnorderedElementsAreArrayMatcher<T>
6917 UnorderedElementsAreArray(::std::initializer_list<T> xs) {
6918 return UnorderedElementsAreArray(xs.begin(), xs.end());
6919 }
6920
6921 // _ is a matcher that matches anything of any type.
6922 //
6923 // This definition is fine as:
6924 //
6925 // 1. The C++ standard permits using the name _ in a namespace that
6926 // is not the global namespace or ::std.
6927 // 2. The AnythingMatcher class has no data member or constructor,
6928 // so it's OK to create global variables of this type.
6929 // 3. c-style has approved of using _ in this case.
6930 const internal::AnythingMatcher _ = {};
6931 // Creates a matcher that matches any value of the given type T.
6932 template <typename T>
6933 inline Matcher<T> A() {
6934 return _;
6935 }
6936
6937 // Creates a matcher that matches any value of the given type T.
6938 template <typename T>
6939 inline Matcher<T> An() {
6940 return _;
6941 }
6942
6943 template <typename T, typename M>
6944 Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
6945 const M& value, std::false_type /* convertible_to_matcher */,
6946 std::false_type /* convertible_to_T */) {
6947 return Eq(value);
6948 }
6949
6950 // Creates a polymorphic matcher that matches any NULL pointer.
6951 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
6952 return MakePolymorphicMatcher(internal::IsNullMatcher());
6953 }
6954
6955 // Creates a polymorphic matcher that matches any non-NULL pointer.
6956 // This is convenient as Not(NULL) doesn't compile (the compiler
6957 // thinks that that expression is comparing a pointer with an integer).
6958 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
6959 return MakePolymorphicMatcher(internal::NotNullMatcher());
6960 }
6961
6962 // Creates a polymorphic matcher that matches any argument that
6963 // references variable x.
6964 template <typename T>
6965 inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
6966 return internal::RefMatcher<T&>(x);
6967 }
6968
6969 // Creates a polymorphic matcher that matches any NaN floating point.
6970 inline PolymorphicMatcher<internal::IsNanMatcher> IsNan() {
6971 return MakePolymorphicMatcher(internal::IsNanMatcher());
6972 }
6973
6974 // Creates a matcher that matches any double argument approximately
6975 // equal to rhs, where two NANs are considered unequal.
6976 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
6977 return internal::FloatingEqMatcher<double>(rhs, false);
6978 }
6979
6980 // Creates a matcher that matches any double argument approximately
6981 // equal to rhs, including NaN values when rhs is NaN.
6982 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
6983 return internal::FloatingEqMatcher<double>(rhs, true);
6984 }
6985
6986 // Creates a matcher that matches any double argument approximately equal to
6987 // rhs, up to the specified max absolute error bound, where two NANs are
6988 // considered unequal. The max absolute error bound must be non-negative.
6989 inline internal::FloatingEqMatcher<double> DoubleNear(
6990 double rhs, double max_abs_error) {
6991 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
6992 }
6993
6994 // Creates a matcher that matches any double argument approximately equal to
6995 // rhs, up to the specified max absolute error bound, including NaN values when
6996 // rhs is NaN. The max absolute error bound must be non-negative.
6997 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
6998 double rhs, double max_abs_error) {
6999 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
7000 }
7001
7002 // Creates a matcher that matches any float argument approximately
7003 // equal to rhs, where two NANs are considered unequal.
7004 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
7005 return internal::FloatingEqMatcher<float>(rhs, false);
7006 }
7007
7008 // Creates a matcher that matches any float argument approximately
7009 // equal to rhs, including NaN values when rhs is NaN.
7010 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
7011 return internal::FloatingEqMatcher<float>(rhs, true);
7012 }
7013
7014 // Creates a matcher that matches any float argument approximately equal to
7015 // rhs, up to the specified max absolute error bound, where two NANs are
7016 // considered unequal. The max absolute error bound must be non-negative.
7017 inline internal::FloatingEqMatcher<float> FloatNear(
7018 float rhs, float max_abs_error) {
7019 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
7020 }
7021
7022 // Creates a matcher that matches any float argument approximately equal to
7023 // rhs, up to the specified max absolute error bound, including NaN values when
7024 // rhs is NaN. The max absolute error bound must be non-negative.
7025 inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
7026 float rhs, float max_abs_error) {
7027 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
7028 }
7029
7030 // Creates a matcher that matches a pointer (raw or smart) that points
7031 // to a value that matches inner_matcher.
7032 template <typename InnerMatcher>
7033 inline internal::PointeeMatcher<InnerMatcher> Pointee(
7034 const InnerMatcher& inner_matcher) {
7035 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
7036 }
7037
7038 #if GTEST_HAS_RTTI
7039 // Creates a matcher that matches a pointer or reference that matches
7040 // inner_matcher when dynamic_cast<To> is applied.
7041 // The result of dynamic_cast<To> is forwarded to the inner matcher.
7042 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
7043 // If To is a reference and the cast fails, this matcher returns false
7044 // immediately.
7045 template <typename To>
7046 inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
7047 WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
7048 return MakePolymorphicMatcher(
7049 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
7050 }
7051 #endif // GTEST_HAS_RTTI
7052
7053 // Creates a matcher that matches an object whose given field matches
7054 // 'matcher'. For example,
7055 // Field(&Foo::number, Ge(5))
7056 // matches a Foo object x if and only if x.number >= 5.
7057 template <typename Class, typename FieldType, typename FieldMatcher>
7058 inline PolymorphicMatcher<
7059 internal::FieldMatcher<Class, FieldType> > Field(
7060 FieldType Class::*field, const FieldMatcher& matcher) {
7061 return MakePolymorphicMatcher(
7062 internal::FieldMatcher<Class, FieldType>(
7063 field, MatcherCast<const FieldType&>(matcher)));
7064 // The call to MatcherCast() is required for supporting inner
7065 // matchers of compatible types. For example, it allows
7066 // Field(&Foo::bar, m)
7067 // to compile where bar is an int32 and m is a matcher for int64.
7068 }
7069
7070 // Same as Field() but also takes the name of the field to provide better error
7071 // messages.
7072 template <typename Class, typename FieldType, typename FieldMatcher>
7073 inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
7074 const std::string& field_name, FieldType Class::*field,
7075 const FieldMatcher& matcher) {
7076 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
7077 field_name, field, MatcherCast<const FieldType&>(matcher)));
7078 }
7079
7080 // Creates a matcher that matches an object whose given property
7081 // matches 'matcher'. For example,
7082 // Property(&Foo::str, StartsWith("hi"))
7083 // matches a Foo object x if and only if x.str() starts with "hi".
7084 template <typename Class, typename PropertyType, typename PropertyMatcher>
7085 inline PolymorphicMatcher<internal::PropertyMatcher<
7086 Class, PropertyType, PropertyType (Class::*)() const> >
7087 Property(PropertyType (Class::*property)() const,
7088 const PropertyMatcher& matcher) {
7089 return MakePolymorphicMatcher(
7090 internal::PropertyMatcher<Class, PropertyType,
7091 PropertyType (Class::*)() const>(
7092 property, MatcherCast<const PropertyType&>(matcher)));
7093 // The call to MatcherCast() is required for supporting inner
7094 // matchers of compatible types. For example, it allows
7095 // Property(&Foo::bar, m)
7096 // to compile where bar() returns an int32 and m is a matcher for int64.
7097 }
7098
7099 // Same as Property() above, but also takes the name of the property to provide
7100 // better error messages.
7101 template <typename Class, typename PropertyType, typename PropertyMatcher>
7102 inline PolymorphicMatcher<internal::PropertyMatcher<
7103 Class, PropertyType, PropertyType (Class::*)() const> >
7104 Property(const std::string& property_name,
7105 PropertyType (Class::*property)() const,
7106 const PropertyMatcher& matcher) {
7107 return MakePolymorphicMatcher(
7108 internal::PropertyMatcher<Class, PropertyType,
7109 PropertyType (Class::*)() const>(
7110 property_name, property, MatcherCast<const PropertyType&>(matcher)));
7111 }
7112
7113 // The same as above but for reference-qualified member functions.
7114 template <typename Class, typename PropertyType, typename PropertyMatcher>
7115 inline PolymorphicMatcher<internal::PropertyMatcher<
7116 Class, PropertyType, PropertyType (Class::*)() const &> >
7117 Property(PropertyType (Class::*property)() const &,
7118 const PropertyMatcher& matcher) {
7119 return MakePolymorphicMatcher(
7120 internal::PropertyMatcher<Class, PropertyType,
7121 PropertyType (Class::*)() const&>(
7122 property, MatcherCast<const PropertyType&>(matcher)));
7123 }
7124
7125 // Three-argument form for reference-qualified member functions.
7126 template <typename Class, typename PropertyType, typename PropertyMatcher>
7127 inline PolymorphicMatcher<internal::PropertyMatcher<
7128 Class, PropertyType, PropertyType (Class::*)() const &> >
7129 Property(const std::string& property_name,
7130 PropertyType (Class::*property)() const &,
7131 const PropertyMatcher& matcher) {
7132 return MakePolymorphicMatcher(
7133 internal::PropertyMatcher<Class, PropertyType,
7134 PropertyType (Class::*)() const&>(
7135 property_name, property, MatcherCast<const PropertyType&>(matcher)));
7136 }
7137
7138 // Creates a matcher that matches an object if and only if the result of
7139 // applying a callable to x matches 'matcher'. For example,
7140 // ResultOf(f, StartsWith("hi"))
7141 // matches a Foo object x if and only if f(x) starts with "hi".
7142 // `callable` parameter can be a function, function pointer, or a functor. It is
7143 // required to keep no state affecting the results of the calls on it and make
7144 // no assumptions about how many calls will be made. Any state it keeps must be
7145 // protected from the concurrent access.
7146 template <typename Callable, typename InnerMatcher>
7147 internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
7148 Callable callable, InnerMatcher matcher) {
7149 return internal::ResultOfMatcher<Callable, InnerMatcher>(
7150 std::move(callable), std::move(matcher));
7151 }
7152
7153 // String matchers.
7154
7155 // Matches a string equal to str.
7156 template <typename T = std::string>
7157 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
7158 const internal::StringLike<T>& str) {
7159 return MakePolymorphicMatcher(
7160 internal::StrEqualityMatcher<std::string>(std::string(str), true, true));
7161 }
7162
7163 // Matches a string not equal to str.
7164 template <typename T = std::string>
7165 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
7166 const internal::StringLike<T>& str) {
7167 return MakePolymorphicMatcher(
7168 internal::StrEqualityMatcher<std::string>(std::string(str), false, true));
7169 }
7170
7171 // Matches a string equal to str, ignoring case.
7172 template <typename T = std::string>
7173 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
7174 const internal::StringLike<T>& str) {
7175 return MakePolymorphicMatcher(
7176 internal::StrEqualityMatcher<std::string>(std::string(str), true, false));
7177 }
7178
7179 // Matches a string not equal to str, ignoring case.
7180 template <typename T = std::string>
7181 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
7182 const internal::StringLike<T>& str) {
7183 return MakePolymorphicMatcher(internal::StrEqualityMatcher<std::string>(
7184 std::string(str), false, false));
7185 }
7186
7187 // Creates a matcher that matches any string, std::string, or C string
7188 // that contains the given substring.
7189 template <typename T = std::string>
7190 PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
7191 const internal::StringLike<T>& substring) {
7192 return MakePolymorphicMatcher(
7193 internal::HasSubstrMatcher<std::string>(std::string(substring)));
7194 }
7195
7196 // Matches a string that starts with 'prefix' (case-sensitive).
7197 template <typename T = std::string>
7198 PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
7199 const internal::StringLike<T>& prefix) {
7200 return MakePolymorphicMatcher(
7201 internal::StartsWithMatcher<std::string>(std::string(prefix)));
7202 }
7203
7204 // Matches a string that ends with 'suffix' (case-sensitive).
7205 template <typename T = std::string>
7206 PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
7207 const internal::StringLike<T>& suffix) {
7208 return MakePolymorphicMatcher(
7209 internal::EndsWithMatcher<std::string>(std::string(suffix)));
7210 }
7211
7212 #if GTEST_HAS_STD_WSTRING
7213 // Wide string matchers.
7214
7215 // Matches a string equal to str.
7216 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
7217 const std::wstring& str) {
7218 return MakePolymorphicMatcher(
7219 internal::StrEqualityMatcher<std::wstring>(str, true, true));
7220 }
7221
7222 // Matches a string not equal to str.
7223 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
7224 const std::wstring& str) {
7225 return MakePolymorphicMatcher(
7226 internal::StrEqualityMatcher<std::wstring>(str, false, true));
7227 }
7228
7229 // Matches a string equal to str, ignoring case.
7230 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
7231 StrCaseEq(const std::wstring& str) {
7232 return MakePolymorphicMatcher(
7233 internal::StrEqualityMatcher<std::wstring>(str, true, false));
7234 }
7235
7236 // Matches a string not equal to str, ignoring case.
7237 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
7238 StrCaseNe(const std::wstring& str) {
7239 return MakePolymorphicMatcher(
7240 internal::StrEqualityMatcher<std::wstring>(str, false, false));
7241 }
7242
7243 // Creates a matcher that matches any ::wstring, std::wstring, or C wide string
7244 // that contains the given substring.
7245 inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
7246 const std::wstring& substring) {
7247 return MakePolymorphicMatcher(
7248 internal::HasSubstrMatcher<std::wstring>(substring));
7249 }
7250
7251 // Matches a string that starts with 'prefix' (case-sensitive).
7252 inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
7253 StartsWith(const std::wstring& prefix) {
7254 return MakePolymorphicMatcher(
7255 internal::StartsWithMatcher<std::wstring>(prefix));
7256 }
7257
7258 // Matches a string that ends with 'suffix' (case-sensitive).
7259 inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
7260 const std::wstring& suffix) {
7261 return MakePolymorphicMatcher(
7262 internal::EndsWithMatcher<std::wstring>(suffix));
7263 }
7264
7265 #endif // GTEST_HAS_STD_WSTRING
7266
7267 // Creates a polymorphic matcher that matches a 2-tuple where the
7268 // first field == the second field.
7269 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
7270
7271 // Creates a polymorphic matcher that matches a 2-tuple where the
7272 // first field >= the second field.
7273 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
7274
7275 // Creates a polymorphic matcher that matches a 2-tuple where the
7276 // first field > the second field.
7277 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
7278
7279 // Creates a polymorphic matcher that matches a 2-tuple where the
7280 // first field <= the second field.
7281 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
7282
7283 // Creates a polymorphic matcher that matches a 2-tuple where the
7284 // first field < the second field.
7285 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
7286
7287 // Creates a polymorphic matcher that matches a 2-tuple where the
7288 // first field != the second field.
7289 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
7290
7291 // Creates a polymorphic matcher that matches a 2-tuple where
7292 // FloatEq(first field) matches the second field.
7293 inline internal::FloatingEq2Matcher<float> FloatEq() {
7294 return internal::FloatingEq2Matcher<float>();
7295 }
7296
7297 // Creates a polymorphic matcher that matches a 2-tuple where
7298 // DoubleEq(first field) matches the second field.
7299 inline internal::FloatingEq2Matcher<double> DoubleEq() {
7300 return internal::FloatingEq2Matcher<double>();
7301 }
7302
7303 // Creates a polymorphic matcher that matches a 2-tuple where
7304 // FloatEq(first field) matches the second field with NaN equality.
7305 inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
7306 return internal::FloatingEq2Matcher<float>(true);
7307 }
7308
7309 // Creates a polymorphic matcher that matches a 2-tuple where
7310 // DoubleEq(first field) matches the second field with NaN equality.
7311 inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
7312 return internal::FloatingEq2Matcher<double>(true);
7313 }
7314
7315 // Creates a polymorphic matcher that matches a 2-tuple where
7316 // FloatNear(first field, max_abs_error) matches the second field.
7317 inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
7318 return internal::FloatingEq2Matcher<float>(max_abs_error);
7319 }
7320
7321 // Creates a polymorphic matcher that matches a 2-tuple where
7322 // DoubleNear(first field, max_abs_error) matches the second field.
7323 inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
7324 return internal::FloatingEq2Matcher<double>(max_abs_error);
7325 }
7326
7327 // Creates a polymorphic matcher that matches a 2-tuple where
7328 // FloatNear(first field, max_abs_error) matches the second field with NaN
7329 // equality.
7330 inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
7331 float max_abs_error) {
7332 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
7333 }
7334
7335 // Creates a polymorphic matcher that matches a 2-tuple where
7336 // DoubleNear(first field, max_abs_error) matches the second field with NaN
7337 // equality.
7338 inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
7339 double max_abs_error) {
7340 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
7341 }
7342
7343 // Creates a matcher that matches any value of type T that m doesn't
7344 // match.
7345 template <typename InnerMatcher>
7346 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
7347 return internal::NotMatcher<InnerMatcher>(m);
7348 }
7349
7350 // Returns a matcher that matches anything that satisfies the given
7351 // predicate. The predicate can be any unary function or functor
7352 // whose return type can be implicitly converted to bool.
7353 template <typename Predicate>
7354 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
7355 Truly(Predicate pred) {
7356 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
7357 }
7358
7359 // Returns a matcher that matches the container size. The container must
7360 // support both size() and size_type which all STL-like containers provide.
7361 // Note that the parameter 'size' can be a value of type size_type as well as
7362 // matcher. For instance:
7363 // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
7364 // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
7365 template <typename SizeMatcher>
7366 inline internal::SizeIsMatcher<SizeMatcher>
7367 SizeIs(const SizeMatcher& size_matcher) {
7368 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
7369 }
7370
7371 // Returns a matcher that matches the distance between the container's begin()
7372 // iterator and its end() iterator, i.e. the size of the container. This matcher
7373 // can be used instead of SizeIs with containers such as std::forward_list which
7374 // do not implement size(). The container must provide const_iterator (with
7375 // valid iterator_traits), begin() and end().
7376 template <typename DistanceMatcher>
7377 inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
7378 BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
7379 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
7380 }
7381
7382 // Returns a matcher that matches an equal container.
7383 // This matcher behaves like Eq(), but in the event of mismatch lists the
7384 // values that are included in one container but not the other. (Duplicate
7385 // values and order differences are not explained.)
7386 template <typename Container>
7387 inline PolymorphicMatcher<internal::ContainerEqMatcher<
7388 typename std::remove_const<Container>::type>>
7389 ContainerEq(const Container& rhs) {
7390 return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));
7391 }
7392
7393 // Returns a matcher that matches a container that, when sorted using
7394 // the given comparator, matches container_matcher.
7395 template <typename Comparator, typename ContainerMatcher>
7396 inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
7397 WhenSortedBy(const Comparator& comparator,
7398 const ContainerMatcher& container_matcher) {
7399 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
7400 comparator, container_matcher);
7401 }
7402
7403 // Returns a matcher that matches a container that, when sorted using
7404 // the < operator, matches container_matcher.
7405 template <typename ContainerMatcher>
7406 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
7407 WhenSorted(const ContainerMatcher& container_matcher) {
7408 return
7409 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
7410 internal::LessComparator(), container_matcher);
7411 }
7412
7413 // Matches an STL-style container or a native array that contains the
7414 // same number of elements as in rhs, where its i-th element and rhs's
7415 // i-th element (as a pair) satisfy the given pair matcher, for all i.
7416 // TupleMatcher must be able to be safely cast to Matcher<std::tuple<const
7417 // T1&, const T2&> >, where T1 and T2 are the types of elements in the
7418 // LHS container and the RHS container respectively.
7419 template <typename TupleMatcher, typename Container>
7420 inline internal::PointwiseMatcher<TupleMatcher,
7421 typename std::remove_const<Container>::type>
7422 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
7423 return internal::PointwiseMatcher<TupleMatcher, Container>(tuple_matcher,
7424 rhs);
7425 }
7426
7427
7428 // Supports the Pointwise(m, {a, b, c}) syntax.
7429 template <typename TupleMatcher, typename T>
7430 inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
7431 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
7432 return Pointwise(tuple_matcher, std::vector<T>(rhs));
7433 }
7434
7435
7436 // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
7437 // container or a native array that contains the same number of
7438 // elements as in rhs, where in some permutation of the container, its
7439 // i-th element and rhs's i-th element (as a pair) satisfy the given
7440 // pair matcher, for all i. Tuple2Matcher must be able to be safely
7441 // cast to Matcher<std::tuple<const T1&, const T2&> >, where T1 and T2 are
7442 // the types of elements in the LHS container and the RHS container
7443 // respectively.
7444 //
7445 // This is like Pointwise(pair_matcher, rhs), except that the element
7446 // order doesn't matter.
7447 template <typename Tuple2Matcher, typename RhsContainer>
7448 inline internal::UnorderedElementsAreArrayMatcher<
7449 typename internal::BoundSecondMatcher<
7450 Tuple2Matcher,
7451 typename internal::StlContainerView<
7452 typename std::remove_const<RhsContainer>::type>::type::value_type>>
7453 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
7454 const RhsContainer& rhs_container) {
7455 // RhsView allows the same code to handle RhsContainer being a
7456 // STL-style container and it being a native C-style array.
7457 typedef typename internal::StlContainerView<RhsContainer> RhsView;
7458 typedef typename RhsView::type RhsStlContainer;
7459 typedef typename RhsStlContainer::value_type Second;
7460 const RhsStlContainer& rhs_stl_container =
7461 RhsView::ConstReference(rhs_container);
7462
7463 // Create a matcher for each element in rhs_container.
7464 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
7465 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
7466 it != rhs_stl_container.end(); ++it) {
7467 matchers.push_back(
7468 internal::MatcherBindSecond(tuple2_matcher, *it));
7469 }
7470
7471 // Delegate the work to UnorderedElementsAreArray().
7472 return UnorderedElementsAreArray(matchers);
7473 }
7474
7475
7476 // Supports the UnorderedPointwise(m, {a, b, c}) syntax.
7477 template <typename Tuple2Matcher, typename T>
7478 inline internal::UnorderedElementsAreArrayMatcher<
7479 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
7480 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
7481 std::initializer_list<T> rhs) {
7482 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
7483 }
7484
7485
7486 // Matches an STL-style container or a native array that contains at
7487 // least one element matching the given value or matcher.
7488 //
7489 // Examples:
7490 // ::std::set<int> page_ids;
7491 // page_ids.insert(3);
7492 // page_ids.insert(1);
7493 // EXPECT_THAT(page_ids, Contains(1));
7494 // EXPECT_THAT(page_ids, Contains(Gt(2)));
7495 // EXPECT_THAT(page_ids, Not(Contains(4)));
7496 //
7497 // ::std::map<int, size_t> page_lengths;
7498 // page_lengths[1] = 100;
7499 // EXPECT_THAT(page_lengths,
7500 // Contains(::std::pair<const int, size_t>(1, 100)));
7501 //
7502 // const char* user_ids[] = { "joe", "mike", "tom" };
7503 // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
7504 template <typename M>
7505 inline internal::ContainsMatcher<M> Contains(M matcher) {
7506 return internal::ContainsMatcher<M>(matcher);
7507 }
7508
7509 // IsSupersetOf(iterator_first, iterator_last)
7510 // IsSupersetOf(pointer, count)
7511 // IsSupersetOf(array)
7512 // IsSupersetOf(container)
7513 // IsSupersetOf({e1, e2, ..., en})
7514 //
7515 // IsSupersetOf() verifies that a surjective partial mapping onto a collection
7516 // of matchers exists. In other words, a container matches
7517 // IsSupersetOf({e1, ..., en}) if and only if there is a permutation
7518 // {y1, ..., yn} of some of the container's elements where y1 matches e1,
7519 // ..., and yn matches en. Obviously, the size of the container must be >= n
7520 // in order to have a match. Examples:
7521 //
7522 // - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
7523 // 1 matches Ne(0).
7524 // - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
7525 // both Eq(1) and Lt(2). The reason is that different matchers must be used
7526 // for elements in different slots of the container.
7527 // - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
7528 // Eq(1) and (the second) 1 matches Lt(2).
7529 // - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
7530 // Gt(1) and 3 matches (the second) Gt(1).
7531 //
7532 // The matchers can be specified as an array, a pointer and count, a container,
7533 // an initializer list, or an STL iterator range. In each of these cases, the
7534 // underlying matchers can be either values or matchers.
7535
7536 template <typename Iter>
7537 inline internal::UnorderedElementsAreArrayMatcher<
7538 typename ::std::iterator_traits<Iter>::value_type>
7539 IsSupersetOf(Iter first, Iter last) {
7540 typedef typename ::std::iterator_traits<Iter>::value_type T;
7541 return internal::UnorderedElementsAreArrayMatcher<T>(
7542 internal::UnorderedMatcherRequire::Superset, first, last);
7543 }
7544
7545 template <typename T>
7546 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
7547 const T* pointer, size_t count) {
7548 return IsSupersetOf(pointer, pointer + count);
7549 }
7550
7551 template <typename T, size_t N>
7552 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
7553 const T (&array)[N]) {
7554 return IsSupersetOf(array, N);
7555 }
7556
7557 template <typename Container>
7558 inline internal::UnorderedElementsAreArrayMatcher<
7559 typename Container::value_type>
7560 IsSupersetOf(const Container& container) {
7561 return IsSupersetOf(container.begin(), container.end());
7562 }
7563
7564 template <typename T>
7565 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
7566 ::std::initializer_list<T> xs) {
7567 return IsSupersetOf(xs.begin(), xs.end());
7568 }
7569
7570 // IsSubsetOf(iterator_first, iterator_last)
7571 // IsSubsetOf(pointer, count)
7572 // IsSubsetOf(array)
7573 // IsSubsetOf(container)
7574 // IsSubsetOf({e1, e2, ..., en})
7575 //
7576 // IsSubsetOf() verifies that an injective mapping onto a collection of matchers
7577 // exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
7578 // only if there is a subset of matchers {m1, ..., mk} which would match the
7579 // container using UnorderedElementsAre. Obviously, the size of the container
7580 // must be <= n in order to have a match. Examples:
7581 //
7582 // - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
7583 // - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
7584 // matches Lt(0).
7585 // - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
7586 // match Gt(0). The reason is that different matchers must be used for
7587 // elements in different slots of the container.
7588 //
7589 // The matchers can be specified as an array, a pointer and count, a container,
7590 // an initializer list, or an STL iterator range. In each of these cases, the
7591 // underlying matchers can be either values or matchers.
7592
7593 template <typename Iter>
7594 inline internal::UnorderedElementsAreArrayMatcher<
7595 typename ::std::iterator_traits<Iter>::value_type>
7596 IsSubsetOf(Iter first, Iter last) {
7597 typedef typename ::std::iterator_traits<Iter>::value_type T;
7598 return internal::UnorderedElementsAreArrayMatcher<T>(
7599 internal::UnorderedMatcherRequire::Subset, first, last);
7600 }
7601
7602 template <typename T>
7603 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
7604 const T* pointer, size_t count) {
7605 return IsSubsetOf(pointer, pointer + count);
7606 }
7607
7608 template <typename T, size_t N>
7609 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
7610 const T (&array)[N]) {
7611 return IsSubsetOf(array, N);
7612 }
7613
7614 template <typename Container>
7615 inline internal::UnorderedElementsAreArrayMatcher<
7616 typename Container::value_type>
7617 IsSubsetOf(const Container& container) {
7618 return IsSubsetOf(container.begin(), container.end());
7619 }
7620
7621 template <typename T>
7622 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
7623 ::std::initializer_list<T> xs) {
7624 return IsSubsetOf(xs.begin(), xs.end());
7625 }
7626
7627 // Matches an STL-style container or a native array that contains only
7628 // elements matching the given value or matcher.
7629 //
7630 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
7631 // the messages are different.
7632 //
7633 // Examples:
7634 // ::std::set<int> page_ids;
7635 // // Each(m) matches an empty container, regardless of what m is.
7636 // EXPECT_THAT(page_ids, Each(Eq(1)));
7637 // EXPECT_THAT(page_ids, Each(Eq(77)));
7638 //
7639 // page_ids.insert(3);
7640 // EXPECT_THAT(page_ids, Each(Gt(0)));
7641 // EXPECT_THAT(page_ids, Not(Each(Gt(4))));
7642 // page_ids.insert(1);
7643 // EXPECT_THAT(page_ids, Not(Each(Lt(2))));
7644 //
7645 // ::std::map<int, size_t> page_lengths;
7646 // page_lengths[1] = 100;
7647 // page_lengths[2] = 200;
7648 // page_lengths[3] = 300;
7649 // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
7650 // EXPECT_THAT(page_lengths, Each(Key(Le(3))));
7651 //
7652 // const char* user_ids[] = { "joe", "mike", "tom" };
7653 // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
7654 template <typename M>
7655 inline internal::EachMatcher<M> Each(M matcher) {
7656 return internal::EachMatcher<M>(matcher);
7657 }
7658
7659 // Key(inner_matcher) matches an std::pair whose 'first' field matches
7660 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
7661 // std::map that contains at least one element whose key is >= 5.
7662 template <typename M>
7663 inline internal::KeyMatcher<M> Key(M inner_matcher) {
7664 return internal::KeyMatcher<M>(inner_matcher);
7665 }
7666
7667 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
7668 // matches first_matcher and whose 'second' field matches second_matcher. For
7669 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
7670 // to match a std::map<int, string> that contains exactly one element whose key
7671 // is >= 5 and whose value equals "foo".
7672 template <typename FirstMatcher, typename SecondMatcher>
7673 inline internal::PairMatcher<FirstMatcher, SecondMatcher>
7674 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
7675 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
7676 first_matcher, second_matcher);
7677 }
7678
7679 namespace no_adl {
7680 // FieldsAre(matchers...) matches piecewise the fields of compatible structs.
7681 // These include those that support `get<I>(obj)`, and when structured bindings
7682 // are enabled any class that supports them.
7683 // In particular, `std::tuple`, `std::pair`, `std::array` and aggregate types.
7684 template <typename... M>
7685 internal::FieldsAreMatcher<typename std::decay<M>::type...> FieldsAre(
7686 M&&... matchers) {
7687 return internal::FieldsAreMatcher<typename std::decay<M>::type...>(
7688 std::forward<M>(matchers)...);
7689 }
7690
7691 // Creates a matcher that matches a pointer (raw or smart) that matches
7692 // inner_matcher.
7693 template <typename InnerMatcher>
7694 inline internal::PointerMatcher<InnerMatcher> Pointer(
7695 const InnerMatcher& inner_matcher) {
7696 return internal::PointerMatcher<InnerMatcher>(inner_matcher);
7697 }
7698
7699 // Creates a matcher that matches an object that has an address that matches
7700 // inner_matcher.
7701 template <typename InnerMatcher>
7702 inline internal::AddressMatcher<InnerMatcher> Address(
7703 const InnerMatcher& inner_matcher) {
7704 return internal::AddressMatcher<InnerMatcher>(inner_matcher);
7705 }
7706 } // namespace no_adl
7707
7708 // Returns a predicate that is satisfied by anything that matches the
7709 // given matcher.
7710 template <typename M>
7711 inline internal::MatcherAsPredicate<M> Matches(M matcher) {
7712 return internal::MatcherAsPredicate<M>(matcher);
7713 }
7714
7715 // Returns true if and only if the value matches the matcher.
7716 template <typename T, typename M>
7717 inline bool Value(const T& value, M matcher) {
7718 return testing::Matches(matcher)(value);
7719 }
7720
7721 // Matches the value against the given matcher and explains the match
7722 // result to listener.
7723 template <typename T, typename M>
7724 inline bool ExplainMatchResult(
7725 M matcher, const T& value, MatchResultListener* listener) {
7726 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
7727 }
7728
7729 // Returns a string representation of the given matcher. Useful for description
7730 // strings of matchers defined using MATCHER_P* macros that accept matchers as
7731 // their arguments. For example:
7732 //
7733 // MATCHER_P(XAndYThat, matcher,
7734 // "X that " + DescribeMatcher<int>(matcher, negation) +
7735 // " and Y that " + DescribeMatcher<double>(matcher, negation)) {
7736 // return ExplainMatchResult(matcher, arg.x(), result_listener) &&
7737 // ExplainMatchResult(matcher, arg.y(), result_listener);
7738 // }
7739 template <typename T, typename M>
7740 std::string DescribeMatcher(const M& matcher, bool negation = false) {
7741 ::std::stringstream ss;
7742 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
7743 if (negation) {
7744 monomorphic_matcher.DescribeNegationTo(&ss);
7745 } else {
7746 monomorphic_matcher.DescribeTo(&ss);
7747 }
7748 return ss.str();
7749 }
7750
7751 template <typename... Args>
7752 internal::ElementsAreMatcher<
7753 std::tuple<typename std::decay<const Args&>::type...>>
7754 ElementsAre(const Args&... matchers) {
7755 return internal::ElementsAreMatcher<
7756 std::tuple<typename std::decay<const Args&>::type...>>(
7757 std::make_tuple(matchers...));
7758 }
7759
7760 template <typename... Args>
7761 internal::UnorderedElementsAreMatcher<
7762 std::tuple<typename std::decay<const Args&>::type...>>
7763 UnorderedElementsAre(const Args&... matchers) {
7764 return internal::UnorderedElementsAreMatcher<
7765 std::tuple<typename std::decay<const Args&>::type...>>(
7766 std::make_tuple(matchers...));
7767 }
7768
7769 // Define variadic matcher versions.
7770 template <typename... Args>
7771 internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(
7772 const Args&... matchers) {
7773 return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(
7774 matchers...);
7775 }
7776
7777 template <typename... Args>
7778 internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(
7779 const Args&... matchers) {
7780 return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(
7781 matchers...);
7782 }
7783
7784 // AnyOfArray(array)
7785 // AnyOfArray(pointer, count)
7786 // AnyOfArray(container)
7787 // AnyOfArray({ e1, e2, ..., en })
7788 // AnyOfArray(iterator_first, iterator_last)
7789 //
7790 // AnyOfArray() verifies whether a given value matches any member of a
7791 // collection of matchers.
7792 //
7793 // AllOfArray(array)
7794 // AllOfArray(pointer, count)
7795 // AllOfArray(container)
7796 // AllOfArray({ e1, e2, ..., en })
7797 // AllOfArray(iterator_first, iterator_last)
7798 //
7799 // AllOfArray() verifies whether a given value matches all members of a
7800 // collection of matchers.
7801 //
7802 // The matchers can be specified as an array, a pointer and count, a container,
7803 // an initializer list, or an STL iterator range. In each of these cases, the
7804 // underlying matchers can be either values or matchers.
7805
7806 template <typename Iter>
7807 inline internal::AnyOfArrayMatcher<
7808 typename ::std::iterator_traits<Iter>::value_type>
7809 AnyOfArray(Iter first, Iter last) {
7810 return internal::AnyOfArrayMatcher<
7811 typename ::std::iterator_traits<Iter>::value_type>(first, last);
7812 }
7813
7814 template <typename Iter>
7815 inline internal::AllOfArrayMatcher<
7816 typename ::std::iterator_traits<Iter>::value_type>
7817 AllOfArray(Iter first, Iter last) {
7818 return internal::AllOfArrayMatcher<
7819 typename ::std::iterator_traits<Iter>::value_type>(first, last);
7820 }
7821
7822 template <typename T>
7823 inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T* ptr, size_t count) {
7824 return AnyOfArray(ptr, ptr + count);
7825 }
7826
7827 template <typename T>
7828 inline internal::AllOfArrayMatcher<T> AllOfArray(const T* ptr, size_t count) {
7829 return AllOfArray(ptr, ptr + count);
7830 }
7831
7832 template <typename T, size_t N>
7833 inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T (&array)[N]) {
7834 return AnyOfArray(array, N);
7835 }
7836
7837 template <typename T, size_t N>
7838 inline internal::AllOfArrayMatcher<T> AllOfArray(const T (&array)[N]) {
7839 return AllOfArray(array, N);
7840 }
7841
7842 template <typename Container>
7843 inline internal::AnyOfArrayMatcher<typename Container::value_type> AnyOfArray(
7844 const Container& container) {
7845 return AnyOfArray(container.begin(), container.end());
7846 }
7847
7848 template <typename Container>
7849 inline internal::AllOfArrayMatcher<typename Container::value_type> AllOfArray(
7850 const Container& container) {
7851 return AllOfArray(container.begin(), container.end());
7852 }
7853
7854 template <typename T>
7855 inline internal::AnyOfArrayMatcher<T> AnyOfArray(
7856 ::std::initializer_list<T> xs) {
7857 return AnyOfArray(xs.begin(), xs.end());
7858 }
7859
7860 template <typename T>
7861 inline internal::AllOfArrayMatcher<T> AllOfArray(
7862 ::std::initializer_list<T> xs) {
7863 return AllOfArray(xs.begin(), xs.end());
7864 }
7865
7866 // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected
7867 // fields of it matches a_matcher. C++ doesn't support default
7868 // arguments for function templates, so we have to overload it.
7869 template <size_t... k, typename InnerMatcher>
7870 internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...> Args(
7871 InnerMatcher&& matcher) {
7872 return internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...>(
7873 std::forward<InnerMatcher>(matcher));
7874 }
7875
7876 // AllArgs(m) is a synonym of m. This is useful in
7877 //
7878 // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
7879 //
7880 // which is easier to read than
7881 //
7882 // EXPECT_CALL(foo, Bar(_, _)).With(Eq());
7883 template <typename InnerMatcher>
7884 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
7885
7886 // Returns a matcher that matches the value of an optional<> type variable.
7887 // The matcher implementation only uses '!arg' and requires that the optional<>
7888 // type has a 'value_type' member type and that '*arg' is of type 'value_type'
7889 // and is printable using 'PrintToString'. It is compatible with
7890 // std::optional/std::experimental::optional.
7891 // Note that to compare an optional type variable against nullopt you should
7892 // use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the
7893 // optional value contains an optional itself.
7894 template <typename ValueMatcher>
7895 inline internal::OptionalMatcher<ValueMatcher> Optional(
7896 const ValueMatcher& value_matcher) {
7897 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
7898 }
7899
7900 // Returns a matcher that matches the value of a absl::any type variable.
7901 template <typename T>
7902 PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
7903 const Matcher<const T&>& matcher) {
7904 return MakePolymorphicMatcher(
7905 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
7906 }
7907
7908 // Returns a matcher that matches the value of a variant<> type variable.
7909 // The matcher implementation uses ADL to find the holds_alternative and get
7910 // functions.
7911 // It is compatible with std::variant.
7912 template <typename T>
7913 PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
7914 const Matcher<const T&>& matcher) {
7915 return MakePolymorphicMatcher(
7916 internal::variant_matcher::VariantMatcher<T>(matcher));
7917 }
7918
7919 #if GTEST_HAS_EXCEPTIONS
7920
7921 // Anything inside the `internal` namespace is internal to the implementation
7922 // and must not be used in user code!
7923 namespace internal {
7924
7925 class WithWhatMatcherImpl {
7926 public:
7927 WithWhatMatcherImpl(Matcher<std::string> matcher)
7928 : matcher_(std::move(matcher)) {}
7929
7930 void DescribeTo(std::ostream* os) const {
7931 *os << "contains .what() that ";
7932 matcher_.DescribeTo(os);
7933 }
7934
7935 void DescribeNegationTo(std::ostream* os) const {
7936 *os << "contains .what() that does not ";
7937 matcher_.DescribeTo(os);
7938 }
7939
7940 template <typename Err>
7941 bool MatchAndExplain(const Err& err, MatchResultListener* listener) const {
7942 *listener << "which contains .what() that ";
7943 return matcher_.MatchAndExplain(err.what(), listener);
7944 }
7945
7946 private:
7947 const Matcher<std::string> matcher_;
7948 };
7949
7950 inline PolymorphicMatcher<WithWhatMatcherImpl> WithWhat(
7951 Matcher<std::string> m) {
7952 return MakePolymorphicMatcher(WithWhatMatcherImpl(std::move(m)));
7953 }
7954
7955 template <typename Err>
7956 class ExceptionMatcherImpl {
7957 class NeverThrown {
7958 public:
7959 const char* what() const noexcept {
7960 return "this exception should never be thrown";
7961 }
7962 };
7963
7964 // If the matchee raises an exception of a wrong type, we'd like to
7965 // catch it and print its message and type. To do that, we add an additional
7966 // catch clause:
7967 //
7968 // try { ... }
7969 // catch (const Err&) { /* an expected exception */ }
7970 // catch (const std::exception&) { /* exception of a wrong type */ }
7971 //
7972 // However, if the `Err` itself is `std::exception`, we'd end up with two
7973 // identical `catch` clauses:
7974 //
7975 // try { ... }
7976 // catch (const std::exception&) { /* an expected exception */ }
7977 // catch (const std::exception&) { /* exception of a wrong type */ }
7978 //
7979 // This can cause a warning or an error in some compilers. To resolve
7980 // the issue, we use a fake error type whenever `Err` is `std::exception`:
7981 //
7982 // try { ... }
7983 // catch (const std::exception&) { /* an expected exception */ }
7984 // catch (const NeverThrown&) { /* exception of a wrong type */ }
7985 using DefaultExceptionType = typename std::conditional<
7986 std::is_same<typename std::remove_cv<
7987 typename std::remove_reference<Err>::type>::type,
7988 std::exception>::value,
7989 const NeverThrown&, const std::exception&>::type;
7990
7991 public:
7992 ExceptionMatcherImpl(Matcher<const Err&> matcher)
7993 : matcher_(std::move(matcher)) {}
7994
7995 void DescribeTo(std::ostream* os) const {
7996 *os << "throws an exception which is a " << GetTypeName<Err>();
7997 *os << " which ";
7998 matcher_.DescribeTo(os);
7999 }
8000
8001 void DescribeNegationTo(std::ostream* os) const {
8002 *os << "throws an exception which is not a " << GetTypeName<Err>();
8003 *os << " which ";
8004 matcher_.DescribeNegationTo(os);
8005 }
8006
8007 template <typename T>
8008 bool MatchAndExplain(T&& x, MatchResultListener* listener) const {
8009 try {
8010 (void)(std::forward<T>(x)());
8011 } catch (const Err& err) {
8012 *listener << "throws an exception which is a " << GetTypeName<Err>();
8013 *listener << " ";
8014 return matcher_.MatchAndExplain(err, listener);
8015 } catch (DefaultExceptionType err) {
8016 #if GTEST_HAS_RTTI
8017 *listener << "throws an exception of type " << GetTypeName(typeid(err));
8018 *listener << " ";
8019 #else
8020 *listener << "throws an std::exception-derived type ";
8021 #endif
8022 *listener << "with description \"" << err.what() << "\"";
8023 return false;
8024 } catch (...) {
8025 *listener << "throws an exception of an unknown type";
8026 return false;
8027 }
8028
8029 *listener << "does not throw any exception";
8030 return false;
8031 }
8032
8033 private:
8034 const Matcher<const Err&> matcher_;
8035 };
8036
8037 } // namespace internal
8038
8039 // Throws()
8040 // Throws(exceptionMatcher)
8041 // ThrowsMessage(messageMatcher)
8042 //
8043 // This matcher accepts a callable and verifies that when invoked, it throws
8044 // an exception with the given type and properties.
8045 //
8046 // Examples:
8047 //
8048 // EXPECT_THAT(
8049 // []() { throw std::runtime_error("message"); },
8050 // Throws<std::runtime_error>());
8051 //
8052 // EXPECT_THAT(
8053 // []() { throw std::runtime_error("message"); },
8054 // ThrowsMessage<std::runtime_error>(HasSubstr("message")));
8055 //
8056 // EXPECT_THAT(
8057 // []() { throw std::runtime_error("message"); },
8058 // Throws<std::runtime_error>(
8059 // Property(&std::runtime_error::what, HasSubstr("message"))));
8060
8061 template <typename Err>
8062 PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws() {
8063 return MakePolymorphicMatcher(
8064 internal::ExceptionMatcherImpl<Err>(A<const Err&>()));
8065 }
8066
8067 template <typename Err, typename ExceptionMatcher>
8068 PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws(
8069 const ExceptionMatcher& exception_matcher) {
8070 // Using matcher cast allows users to pass a matcher of a more broad type.
8071 // For example user may want to pass Matcher<std::exception>
8072 // to Throws<std::runtime_error>, or Matcher<int64> to Throws<int32>.
8073 return MakePolymorphicMatcher(internal::ExceptionMatcherImpl<Err>(
8074 SafeMatcherCast<const Err&>(exception_matcher)));
8075 }
8076
8077 template <typename Err, typename MessageMatcher>
8078 PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
8079 MessageMatcher&& message_matcher) {
8080 static_assert(std::is_base_of<std::exception, Err>::value,
8081 "expected an std::exception-derived type");
8082 return Throws<Err>(internal::WithWhat(
8083 MatcherCast<std::string>(std::forward<MessageMatcher>(message_matcher))));
8084 }
8085
8086 #endif // GTEST_HAS_EXCEPTIONS
8087
8088 // These macros allow using matchers to check values in Google Test
8089 // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
8090 // succeed if and only if the value matches the matcher. If the assertion
8091 // fails, the value and the description of the matcher will be printed.
8092 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
8093 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
8094 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
8095 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
8096
8097 // MATCHER* macroses itself are listed below.
8098 #define MATCHER(name, description) \
8099 class name##Matcher \
8100 : public ::testing::internal::MatcherBaseImpl<name##Matcher> { \
8101 public: \
8102 template <typename arg_type> \
8103 class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
8104 public: \
8105 gmock_Impl() {} \
8106 bool MatchAndExplain( \
8107 const arg_type& arg, \
8108 ::testing::MatchResultListener* result_listener) const override; \
8109 void DescribeTo(::std::ostream* gmock_os) const override { \
8110 *gmock_os << FormatDescription(false); \
8111 } \
8112 void DescribeNegationTo(::std::ostream* gmock_os) const override { \
8113 *gmock_os << FormatDescription(true); \
8114 } \
8115 \
8116 private: \
8117 ::std::string FormatDescription(bool negation) const { \
8118 ::std::string gmock_description = (description); \
8119 if (!gmock_description.empty()) { \
8120 return gmock_description; \
8121 } \
8122 return ::testing::internal::FormatMatcherDescription(negation, #name, \
8123 {}); \
8124 } \
8125 }; \
8126 }; \
8127 GTEST_ATTRIBUTE_UNUSED_ inline name##Matcher name() { return {}; } \
8128 template <typename arg_type> \
8129 bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \
8130 const arg_type& arg, \
8131 ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) \
8132 const
8133
8134 #define MATCHER_P(name, p0, description) \
8135 GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (p0))
8136 #define MATCHER_P2(name, p0, p1, description) \
8137 GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (p0, p1))
8138 #define MATCHER_P3(name, p0, p1, p2, description) \
8139 GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (p0, p1, p2))
8140 #define MATCHER_P4(name, p0, p1, p2, p3, description) \
8141 GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, (p0, p1, p2, p3))
8142 #define MATCHER_P5(name, p0, p1, p2, p3, p4, description) \
8143 GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \
8144 (p0, p1, p2, p3, p4))
8145 #define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \
8146 GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description, \
8147 (p0, p1, p2, p3, p4, p5))
8148 #define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \
8149 GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description, \
8150 (p0, p1, p2, p3, p4, p5, p6))
8151 #define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \
8152 GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description, \
8153 (p0, p1, p2, p3, p4, p5, p6, p7))
8154 #define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \
8155 GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description, \
8156 (p0, p1, p2, p3, p4, p5, p6, p7, p8))
8157 #define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \
8158 GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description, \
8159 (p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))
8160
8161 #define GMOCK_INTERNAL_MATCHER(name, full_name, description, args) \
8162 template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
8163 class full_name : public ::testing::internal::MatcherBaseImpl< \
8164 full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \
8165 public: \
8166 using full_name::MatcherBaseImpl::MatcherBaseImpl; \
8167 template <typename arg_type> \
8168 class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
8169 public: \
8170 explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) \
8171 : GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {} \
8172 bool MatchAndExplain( \
8173 const arg_type& arg, \
8174 ::testing::MatchResultListener* result_listener) const override; \
8175 void DescribeTo(::std::ostream* gmock_os) const override { \
8176 *gmock_os << FormatDescription(false); \
8177 } \
8178 void DescribeNegationTo(::std::ostream* gmock_os) const override { \
8179 *gmock_os << FormatDescription(true); \
8180 } \
8181 GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
8182 \
8183 private: \
8184 ::std::string FormatDescription(bool negation) const { \
8185 ::std::string gmock_description = (description); \
8186 if (!gmock_description.empty()) { \
8187 return gmock_description; \
8188 } \
8189 return ::testing::internal::FormatMatcherDescription( \
8190 negation, #name, \
8191 ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \
8192 ::std::tuple<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
8193 GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args)))); \
8194 } \
8195 }; \
8196 }; \
8197 template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
8198 inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name( \
8199 GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) { \
8200 return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
8201 GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args)); \
8202 } \
8203 template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
8204 template <typename arg_type> \
8205 bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>::gmock_Impl< \
8206 arg_type>::MatchAndExplain(const arg_type& arg, \
8207 ::testing::MatchResultListener* \
8208 result_listener GTEST_ATTRIBUTE_UNUSED_) \
8209 const
8210
8211 #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \
8212 GMOCK_PP_TAIL( \
8213 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args))
8214 #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \
8215 , typename arg##_type
8216
8217 #define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \
8218 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args))
8219 #define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \
8220 , arg##_type
8221
8222 #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \
8223 GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH( \
8224 GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args))
8225 #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \
8226 , arg##_type gmock_p##i
8227
8228 #define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \
8229 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args))
8230 #define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \
8231 , arg(::std::forward<arg##_type>(gmock_p##i))
8232
8233 #define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
8234 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args)
8235 #define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \
8236 const arg##_type arg;
8237
8238 #define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \
8239 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args))
8240 #define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg
8241
8242 #define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \
8243 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))
8244 #define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg_unused) \
8245 , gmock_p##i
8246
8247 // To prevent ADL on certain functions we put them on a separate namespace.
8248 using namespace no_adl; // NOLINT
8249
8250 } // namespace testing
8251
8252 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
8253
8254 // Include any custom callback matchers added by the local installation.
8255 // We must include this header at the end to make sure it can use the
8256 // declarations from this file.
8257 // Copyright 2015, Google Inc.
8258 // All rights reserved.
8259 //
8260 // Redistribution and use in source and binary forms, with or without
8261 // modification, are permitted provided that the following conditions are
8262 // met:
8263 //
8264 // * Redistributions of source code must retain the above copyright
8265 // notice, this list of conditions and the following disclaimer.
8266 // * Redistributions in binary form must reproduce the above
8267 // copyright notice, this list of conditions and the following disclaimer
8268 // in the documentation and/or other materials provided with the
8269 // distribution.
8270 // * Neither the name of Google Inc. nor the names of its
8271 // contributors may be used to endorse or promote products derived from
8272 // this software without specific prior written permission.
8273 //
8274 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8275 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8276 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8277 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8278 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8279 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8280 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8281 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8282 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8283 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8284 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8285 //
8286 // Injection point for custom user configurations. See README for details
8287 //
8288 // GOOGLETEST_CM0002 DO NOT DELETE
8289
8290 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
8291 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
8292 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
8293
8294 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
8295
8296 #if GTEST_HAS_EXCEPTIONS
8297 # include <stdexcept> // NOLINT
8298 #endif
8299
8300 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
8301 /* class A needs to have dll-interface to be used by clients of class B */)
8302
8303 namespace testing {
8304
8305 // An abstract handle of an expectation.
8306 class Expectation;
8307
8308 // A set of expectation handles.
8309 class ExpectationSet;
8310
8311 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
8312 // and MUST NOT BE USED IN USER CODE!!!
8313 namespace internal {
8314
8315 // Implements a mock function.
8316 template <typename F> class FunctionMocker;
8317
8318 // Base class for expectations.
8319 class ExpectationBase;
8320
8321 // Implements an expectation.
8322 template <typename F> class TypedExpectation;
8323
8324 // Helper class for testing the Expectation class template.
8325 class ExpectationTester;
8326
8327 // Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
8328 template <typename MockClass>
8329 class NiceMockImpl;
8330 template <typename MockClass>
8331 class StrictMockImpl;
8332 template <typename MockClass>
8333 class NaggyMockImpl;
8334
8335 // Protects the mock object registry (in class Mock), all function
8336 // mockers, and all expectations.
8337 //
8338 // The reason we don't use more fine-grained protection is: when a
8339 // mock function Foo() is called, it needs to consult its expectations
8340 // to see which one should be picked. If another thread is allowed to
8341 // call a mock function (either Foo() or a different one) at the same
8342 // time, it could affect the "retired" attributes of Foo()'s
8343 // expectations when InSequence() is used, and thus affect which
8344 // expectation gets picked. Therefore, we sequence all mock function
8345 // calls to ensure the integrity of the mock objects' states.
8346 GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
8347
8348 // Untyped base class for ActionResultHolder<R>.
8349 class UntypedActionResultHolderBase;
8350
8351 // Abstract base class of FunctionMocker. This is the
8352 // type-agnostic part of the function mocker interface. Its pure
8353 // virtual methods are implemented by FunctionMocker.
8354 class GTEST_API_ UntypedFunctionMockerBase {
8355 public:
8356 UntypedFunctionMockerBase();
8357 virtual ~UntypedFunctionMockerBase();
8358
8359 // Verifies that all expectations on this mock function have been
8360 // satisfied. Reports one or more Google Test non-fatal failures
8361 // and returns false if not.
8362 bool VerifyAndClearExpectationsLocked()
8363 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
8364
8365 // Clears the ON_CALL()s set on this mock function.
8366 virtual void ClearDefaultActionsLocked()
8367 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
8368
8369 // In all of the following Untyped* functions, it's the caller's
8370 // responsibility to guarantee the correctness of the arguments'
8371 // types.
8372
8373 // Performs the default action with the given arguments and returns
8374 // the action's result. The call description string will be used in
8375 // the error message to describe the call in the case the default
8376 // action fails.
8377 // L = *
8378 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
8379 void* untyped_args, const std::string& call_description) const = 0;
8380
8381 // Performs the given action with the given arguments and returns
8382 // the action's result.
8383 // L = *
8384 virtual UntypedActionResultHolderBase* UntypedPerformAction(
8385 const void* untyped_action, void* untyped_args) const = 0;
8386
8387 // Writes a message that the call is uninteresting (i.e. neither
8388 // explicitly expected nor explicitly unexpected) to the given
8389 // ostream.
8390 virtual void UntypedDescribeUninterestingCall(
8391 const void* untyped_args,
8392 ::std::ostream* os) const
8393 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
8394
8395 // Returns the expectation that matches the given function arguments
8396 // (or NULL is there's no match); when a match is found,
8397 // untyped_action is set to point to the action that should be
8398 // performed (or NULL if the action is "do default"), and
8399 // is_excessive is modified to indicate whether the call exceeds the
8400 // expected number.
8401 virtual const ExpectationBase* UntypedFindMatchingExpectation(
8402 const void* untyped_args,
8403 const void** untyped_action, bool* is_excessive,
8404 ::std::ostream* what, ::std::ostream* why)
8405 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
8406
8407 // Prints the given function arguments to the ostream.
8408 virtual void UntypedPrintArgs(const void* untyped_args,
8409 ::std::ostream* os) const = 0;
8410
8411 // Sets the mock object this mock method belongs to, and registers
8412 // this information in the global mock registry. Will be called
8413 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
8414 // method.
8415 void RegisterOwner(const void* mock_obj)
8416 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8417
8418 // Sets the mock object this mock method belongs to, and sets the
8419 // name of the mock function. Will be called upon each invocation
8420 // of this mock function.
8421 void SetOwnerAndName(const void* mock_obj, const char* name)
8422 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8423
8424 // Returns the mock object this mock method belongs to. Must be
8425 // called after RegisterOwner() or SetOwnerAndName() has been
8426 // called.
8427 const void* MockObject() const
8428 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8429
8430 // Returns the name of this mock method. Must be called after
8431 // SetOwnerAndName() has been called.
8432 const char* Name() const
8433 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8434
8435 // Returns the result of invoking this mock function with the given
8436 // arguments. This function can be safely called from multiple
8437 // threads concurrently. The caller is responsible for deleting the
8438 // result.
8439 UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
8440 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8441
8442 protected:
8443 typedef std::vector<const void*> UntypedOnCallSpecs;
8444
8445 using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
8446
8447 // Returns an Expectation object that references and co-owns exp,
8448 // which must be an expectation on this mock function.
8449 Expectation GetHandleOf(ExpectationBase* exp);
8450
8451 // Address of the mock object this mock method belongs to. Only
8452 // valid after this mock method has been called or
8453 // ON_CALL/EXPECT_CALL has been invoked on it.
8454 const void* mock_obj_; // Protected by g_gmock_mutex.
8455
8456 // Name of the function being mocked. Only valid after this mock
8457 // method has been called.
8458 const char* name_; // Protected by g_gmock_mutex.
8459
8460 // All default action specs for this function mocker.
8461 UntypedOnCallSpecs untyped_on_call_specs_;
8462
8463 // All expectations for this function mocker.
8464 //
8465 // It's undefined behavior to interleave expectations (EXPECT_CALLs
8466 // or ON_CALLs) and mock function calls. Also, the order of
8467 // expectations is important. Therefore it's a logic race condition
8468 // to read/write untyped_expectations_ concurrently. In order for
8469 // tools like tsan to catch concurrent read/write accesses to
8470 // untyped_expectations, we deliberately leave accesses to it
8471 // unprotected.
8472 UntypedExpectations untyped_expectations_;
8473 }; // class UntypedFunctionMockerBase
8474
8475 // Untyped base class for OnCallSpec<F>.
8476 class UntypedOnCallSpecBase {
8477 public:
8478 // The arguments are the location of the ON_CALL() statement.
8479 UntypedOnCallSpecBase(const char* a_file, int a_line)
8480 : file_(a_file), line_(a_line), last_clause_(kNone) {}
8481
8482 // Where in the source file was the default action spec defined?
8483 const char* file() const { return file_; }
8484 int line() const { return line_; }
8485
8486 protected:
8487 // Gives each clause in the ON_CALL() statement a name.
8488 enum Clause {
8489 // Do not change the order of the enum members! The run-time
8490 // syntax checking relies on it.
8491 kNone,
8492 kWith,
8493 kWillByDefault
8494 };
8495
8496 // Asserts that the ON_CALL() statement has a certain property.
8497 void AssertSpecProperty(bool property,
8498 const std::string& failure_message) const {
8499 Assert(property, file_, line_, failure_message);
8500 }
8501
8502 // Expects that the ON_CALL() statement has a certain property.
8503 void ExpectSpecProperty(bool property,
8504 const std::string& failure_message) const {
8505 Expect(property, file_, line_, failure_message);
8506 }
8507
8508 const char* file_;
8509 int line_;
8510
8511 // The last clause in the ON_CALL() statement as seen so far.
8512 // Initially kNone and changes as the statement is parsed.
8513 Clause last_clause_;
8514 }; // class UntypedOnCallSpecBase
8515
8516 // This template class implements an ON_CALL spec.
8517 template <typename F>
8518 class OnCallSpec : public UntypedOnCallSpecBase {
8519 public:
8520 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
8521 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
8522
8523 // Constructs an OnCallSpec object from the information inside
8524 // the parenthesis of an ON_CALL() statement.
8525 OnCallSpec(const char* a_file, int a_line,
8526 const ArgumentMatcherTuple& matchers)
8527 : UntypedOnCallSpecBase(a_file, a_line),
8528 matchers_(matchers),
8529 // By default, extra_matcher_ should match anything. However,
8530 // we cannot initialize it with _ as that causes ambiguity between
8531 // Matcher's copy and move constructor for some argument types.
8532 extra_matcher_(A<const ArgumentTuple&>()) {}
8533
8534 // Implements the .With() clause.
8535 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
8536 // Makes sure this is called at most once.
8537 ExpectSpecProperty(last_clause_ < kWith,
8538 ".With() cannot appear "
8539 "more than once in an ON_CALL().");
8540 last_clause_ = kWith;
8541
8542 extra_matcher_ = m;
8543 return *this;
8544 }
8545
8546 // Implements the .WillByDefault() clause.
8547 OnCallSpec& WillByDefault(const Action<F>& action) {
8548 ExpectSpecProperty(last_clause_ < kWillByDefault,
8549 ".WillByDefault() must appear "
8550 "exactly once in an ON_CALL().");
8551 last_clause_ = kWillByDefault;
8552
8553 ExpectSpecProperty(!action.IsDoDefault(),
8554 "DoDefault() cannot be used in ON_CALL().");
8555 action_ = action;
8556 return *this;
8557 }
8558
8559 // Returns true if and only if the given arguments match the matchers.
8560 bool Matches(const ArgumentTuple& args) const {
8561 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
8562 }
8563
8564 // Returns the action specified by the user.
8565 const Action<F>& GetAction() const {
8566 AssertSpecProperty(last_clause_ == kWillByDefault,
8567 ".WillByDefault() must appear exactly "
8568 "once in an ON_CALL().");
8569 return action_;
8570 }
8571
8572 private:
8573 // The information in statement
8574 //
8575 // ON_CALL(mock_object, Method(matchers))
8576 // .With(multi-argument-matcher)
8577 // .WillByDefault(action);
8578 //
8579 // is recorded in the data members like this:
8580 //
8581 // source file that contains the statement => file_
8582 // line number of the statement => line_
8583 // matchers => matchers_
8584 // multi-argument-matcher => extra_matcher_
8585 // action => action_
8586 ArgumentMatcherTuple matchers_;
8587 Matcher<const ArgumentTuple&> extra_matcher_;
8588 Action<F> action_;
8589 }; // class OnCallSpec
8590
8591 // Possible reactions on uninteresting calls.
8592 enum CallReaction {
8593 kAllow,
8594 kWarn,
8595 kFail,
8596 };
8597
8598 } // namespace internal
8599
8600 // Utilities for manipulating mock objects.
8601 class GTEST_API_ Mock {
8602 public:
8603 // The following public methods can be called concurrently.
8604
8605 // Tells Google Mock to ignore mock_obj when checking for leaked
8606 // mock objects.
8607 static void AllowLeak(const void* mock_obj)
8608 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8609
8610 // Verifies and clears all expectations on the given mock object.
8611 // If the expectations aren't satisfied, generates one or more
8612 // Google Test non-fatal failures and returns false.
8613 static bool VerifyAndClearExpectations(void* mock_obj)
8614 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8615
8616 // Verifies all expectations on the given mock object and clears its
8617 // default actions and expectations. Returns true if and only if the
8618 // verification was successful.
8619 static bool VerifyAndClear(void* mock_obj)
8620 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8621
8622 // Returns whether the mock was created as a naggy mock (default)
8623 static bool IsNaggy(void* mock_obj)
8624 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8625 // Returns whether the mock was created as a nice mock
8626 static bool IsNice(void* mock_obj)
8627 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8628 // Returns whether the mock was created as a strict mock
8629 static bool IsStrict(void* mock_obj)
8630 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8631
8632 private:
8633 friend class internal::UntypedFunctionMockerBase;
8634
8635 // Needed for a function mocker to register itself (so that we know
8636 // how to clear a mock object).
8637 template <typename F>
8638 friend class internal::FunctionMocker;
8639
8640 template <typename MockClass>
8641 friend class internal::NiceMockImpl;
8642 template <typename MockClass>
8643 friend class internal::NaggyMockImpl;
8644 template <typename MockClass>
8645 friend class internal::StrictMockImpl;
8646
8647 // Tells Google Mock to allow uninteresting calls on the given mock
8648 // object.
8649 static void AllowUninterestingCalls(const void* mock_obj)
8650 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8651
8652 // Tells Google Mock to warn the user about uninteresting calls on
8653 // the given mock object.
8654 static void WarnUninterestingCalls(const void* mock_obj)
8655 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8656
8657 // Tells Google Mock to fail uninteresting calls on the given mock
8658 // object.
8659 static void FailUninterestingCalls(const void* mock_obj)
8660 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8661
8662 // Tells Google Mock the given mock object is being destroyed and
8663 // its entry in the call-reaction table should be removed.
8664 static void UnregisterCallReaction(const void* mock_obj)
8665 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8666
8667 // Returns the reaction Google Mock will have on uninteresting calls
8668 // made on the given mock object.
8669 static internal::CallReaction GetReactionOnUninterestingCalls(
8670 const void* mock_obj)
8671 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8672
8673 // Verifies that all expectations on the given mock object have been
8674 // satisfied. Reports one or more Google Test non-fatal failures
8675 // and returns false if not.
8676 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
8677 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
8678
8679 // Clears all ON_CALL()s set on the given mock object.
8680 static void ClearDefaultActionsLocked(void* mock_obj)
8681 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
8682
8683 // Registers a mock object and a mock method it owns.
8684 static void Register(
8685 const void* mock_obj,
8686 internal::UntypedFunctionMockerBase* mocker)
8687 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8688
8689 // Tells Google Mock where in the source code mock_obj is used in an
8690 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
8691 // information helps the user identify which object it is.
8692 static void RegisterUseByOnCallOrExpectCall(
8693 const void* mock_obj, const char* file, int line)
8694 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8695
8696 // Unregisters a mock method; removes the owning mock object from
8697 // the registry when the last mock method associated with it has
8698 // been unregistered. This is called only in the destructor of
8699 // FunctionMocker.
8700 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
8701 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
8702 }; // class Mock
8703
8704 // An abstract handle of an expectation. Useful in the .After()
8705 // clause of EXPECT_CALL() for setting the (partial) order of
8706 // expectations. The syntax:
8707 //
8708 // Expectation e1 = EXPECT_CALL(...)...;
8709 // EXPECT_CALL(...).After(e1)...;
8710 //
8711 // sets two expectations where the latter can only be matched after
8712 // the former has been satisfied.
8713 //
8714 // Notes:
8715 // - This class is copyable and has value semantics.
8716 // - Constness is shallow: a const Expectation object itself cannot
8717 // be modified, but the mutable methods of the ExpectationBase
8718 // object it references can be called via expectation_base().
8719
8720 class GTEST_API_ Expectation {
8721 public:
8722 // Constructs a null object that doesn't reference any expectation.
8723 Expectation();
8724 Expectation(Expectation&&) = default;
8725 Expectation(const Expectation&) = default;
8726 Expectation& operator=(Expectation&&) = default;
8727 Expectation& operator=(const Expectation&) = default;
8728 ~Expectation();
8729
8730 // This single-argument ctor must not be explicit, in order to support the
8731 // Expectation e = EXPECT_CALL(...);
8732 // syntax.
8733 //
8734 // A TypedExpectation object stores its pre-requisites as
8735 // Expectation objects, and needs to call the non-const Retire()
8736 // method on the ExpectationBase objects they reference. Therefore
8737 // Expectation must receive a *non-const* reference to the
8738 // ExpectationBase object.
8739 Expectation(internal::ExpectationBase& exp); // NOLINT
8740
8741 // The compiler-generated copy ctor and operator= work exactly as
8742 // intended, so we don't need to define our own.
8743
8744 // Returns true if and only if rhs references the same expectation as this
8745 // object does.
8746 bool operator==(const Expectation& rhs) const {
8747 return expectation_base_ == rhs.expectation_base_;
8748 }
8749
8750 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
8751
8752 private:
8753 friend class ExpectationSet;
8754 friend class Sequence;
8755 friend class ::testing::internal::ExpectationBase;
8756 friend class ::testing::internal::UntypedFunctionMockerBase;
8757
8758 template <typename F>
8759 friend class ::testing::internal::FunctionMocker;
8760
8761 template <typename F>
8762 friend class ::testing::internal::TypedExpectation;
8763
8764 // This comparator is needed for putting Expectation objects into a set.
8765 class Less {
8766 public:
8767 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
8768 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
8769 }
8770 };
8771
8772 typedef ::std::set<Expectation, Less> Set;
8773
8774 Expectation(
8775 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
8776
8777 // Returns the expectation this object references.
8778 const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
8779 return expectation_base_;
8780 }
8781
8782 // A shared_ptr that co-owns the expectation this handle references.
8783 std::shared_ptr<internal::ExpectationBase> expectation_base_;
8784 };
8785
8786 // A set of expectation handles. Useful in the .After() clause of
8787 // EXPECT_CALL() for setting the (partial) order of expectations. The
8788 // syntax:
8789 //
8790 // ExpectationSet es;
8791 // es += EXPECT_CALL(...)...;
8792 // es += EXPECT_CALL(...)...;
8793 // EXPECT_CALL(...).After(es)...;
8794 //
8795 // sets three expectations where the last one can only be matched
8796 // after the first two have both been satisfied.
8797 //
8798 // This class is copyable and has value semantics.
8799 class ExpectationSet {
8800 public:
8801 // A bidirectional iterator that can read a const element in the set.
8802 typedef Expectation::Set::const_iterator const_iterator;
8803
8804 // An object stored in the set. This is an alias of Expectation.
8805 typedef Expectation::Set::value_type value_type;
8806
8807 // Constructs an empty set.
8808 ExpectationSet() {}
8809
8810 // This single-argument ctor must not be explicit, in order to support the
8811 // ExpectationSet es = EXPECT_CALL(...);
8812 // syntax.
8813 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
8814 *this += Expectation(exp);
8815 }
8816
8817 // This single-argument ctor implements implicit conversion from
8818 // Expectation and thus must not be explicit. This allows either an
8819 // Expectation or an ExpectationSet to be used in .After().
8820 ExpectationSet(const Expectation& e) { // NOLINT
8821 *this += e;
8822 }
8823
8824 // The compiler-generator ctor and operator= works exactly as
8825 // intended, so we don't need to define our own.
8826
8827 // Returns true if and only if rhs contains the same set of Expectation
8828 // objects as this does.
8829 bool operator==(const ExpectationSet& rhs) const {
8830 return expectations_ == rhs.expectations_;
8831 }
8832
8833 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
8834
8835 // Implements the syntax
8836 // expectation_set += EXPECT_CALL(...);
8837 ExpectationSet& operator+=(const Expectation& e) {
8838 expectations_.insert(e);
8839 return *this;
8840 }
8841
8842 int size() const { return static_cast<int>(expectations_.size()); }
8843
8844 const_iterator begin() const { return expectations_.begin(); }
8845 const_iterator end() const { return expectations_.end(); }
8846
8847 private:
8848 Expectation::Set expectations_;
8849 };
8850
8851
8852 // Sequence objects are used by a user to specify the relative order
8853 // in which the expectations should match. They are copyable (we rely
8854 // on the compiler-defined copy constructor and assignment operator).
8855 class GTEST_API_ Sequence {
8856 public:
8857 // Constructs an empty sequence.
8858 Sequence() : last_expectation_(new Expectation) {}
8859
8860 // Adds an expectation to this sequence. The caller must ensure
8861 // that no other thread is accessing this Sequence object.
8862 void AddExpectation(const Expectation& expectation) const;
8863
8864 private:
8865 // The last expectation in this sequence.
8866 std::shared_ptr<Expectation> last_expectation_;
8867 }; // class Sequence
8868
8869 // An object of this type causes all EXPECT_CALL() statements
8870 // encountered in its scope to be put in an anonymous sequence. The
8871 // work is done in the constructor and destructor. You should only
8872 // create an InSequence object on the stack.
8873 //
8874 // The sole purpose for this class is to support easy definition of
8875 // sequential expectations, e.g.
8876 //
8877 // {
8878 // InSequence dummy; // The name of the object doesn't matter.
8879 //
8880 // // The following expectations must match in the order they appear.
8881 // EXPECT_CALL(a, Bar())...;
8882 // EXPECT_CALL(a, Baz())...;
8883 // ...
8884 // EXPECT_CALL(b, Xyz())...;
8885 // }
8886 //
8887 // You can create InSequence objects in multiple threads, as long as
8888 // they are used to affect different mock objects. The idea is that
8889 // each thread can create and set up its own mocks as if it's the only
8890 // thread. However, for clarity of your tests we recommend you to set
8891 // up mocks in the main thread unless you have a good reason not to do
8892 // so.
8893 class GTEST_API_ InSequence {
8894 public:
8895 InSequence();
8896 ~InSequence();
8897 private:
8898 bool sequence_created_;
8899
8900 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
8901 } GTEST_ATTRIBUTE_UNUSED_;
8902
8903 namespace internal {
8904
8905 // Points to the implicit sequence introduced by a living InSequence
8906 // object (if any) in the current thread or NULL.
8907 GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
8908
8909 // Base class for implementing expectations.
8910 //
8911 // There are two reasons for having a type-agnostic base class for
8912 // Expectation:
8913 //
8914 // 1. We need to store collections of expectations of different
8915 // types (e.g. all pre-requisites of a particular expectation, all
8916 // expectations in a sequence). Therefore these expectation objects
8917 // must share a common base class.
8918 //
8919 // 2. We can avoid binary code bloat by moving methods not depending
8920 // on the template argument of Expectation to the base class.
8921 //
8922 // This class is internal and mustn't be used by user code directly.
8923 class GTEST_API_ ExpectationBase {
8924 public:
8925 // source_text is the EXPECT_CALL(...) source that created this Expectation.
8926 ExpectationBase(const char* file, int line, const std::string& source_text);
8927
8928 virtual ~ExpectationBase();
8929
8930 // Where in the source file was the expectation spec defined?
8931 const char* file() const { return file_; }
8932 int line() const { return line_; }
8933 const char* source_text() const { return source_text_.c_str(); }
8934 // Returns the cardinality specified in the expectation spec.
8935 const Cardinality& cardinality() const { return cardinality_; }
8936
8937 // Describes the source file location of this expectation.
8938 void DescribeLocationTo(::std::ostream* os) const {
8939 *os << FormatFileLocation(file(), line()) << " ";
8940 }
8941
8942 // Describes how many times a function call matching this
8943 // expectation has occurred.
8944 void DescribeCallCountTo(::std::ostream* os) const
8945 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
8946
8947 // If this mock method has an extra matcher (i.e. .With(matcher)),
8948 // describes it to the ostream.
8949 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
8950
8951 protected:
8952 friend class ::testing::Expectation;
8953 friend class UntypedFunctionMockerBase;
8954
8955 enum Clause {
8956 // Don't change the order of the enum members!
8957 kNone,
8958 kWith,
8959 kTimes,
8960 kInSequence,
8961 kAfter,
8962 kWillOnce,
8963 kWillRepeatedly,
8964 kRetiresOnSaturation
8965 };
8966
8967 typedef std::vector<const void*> UntypedActions;
8968
8969 // Returns an Expectation object that references and co-owns this
8970 // expectation.
8971 virtual Expectation GetHandle() = 0;
8972
8973 // Asserts that the EXPECT_CALL() statement has the given property.
8974 void AssertSpecProperty(bool property,
8975 const std::string& failure_message) const {
8976 Assert(property, file_, line_, failure_message);
8977 }
8978
8979 // Expects that the EXPECT_CALL() statement has the given property.
8980 void ExpectSpecProperty(bool property,
8981 const std::string& failure_message) const {
8982 Expect(property, file_, line_, failure_message);
8983 }
8984
8985 // Explicitly specifies the cardinality of this expectation. Used
8986 // by the subclasses to implement the .Times() clause.
8987 void SpecifyCardinality(const Cardinality& cardinality);
8988
8989 // Returns true if and only if the user specified the cardinality
8990 // explicitly using a .Times().
8991 bool cardinality_specified() const { return cardinality_specified_; }
8992
8993 // Sets the cardinality of this expectation spec.
8994 void set_cardinality(const Cardinality& a_cardinality) {
8995 cardinality_ = a_cardinality;
8996 }
8997
8998 // The following group of methods should only be called after the
8999 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
9000 // the current thread.
9001
9002 // Retires all pre-requisites of this expectation.
9003 void RetireAllPreRequisites()
9004 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
9005
9006 // Returns true if and only if this expectation is retired.
9007 bool is_retired() const
9008 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9009 g_gmock_mutex.AssertHeld();
9010 return retired_;
9011 }
9012
9013 // Retires this expectation.
9014 void Retire()
9015 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9016 g_gmock_mutex.AssertHeld();
9017 retired_ = true;
9018 }
9019
9020 // Returns true if and only if this expectation is satisfied.
9021 bool IsSatisfied() const
9022 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9023 g_gmock_mutex.AssertHeld();
9024 return cardinality().IsSatisfiedByCallCount(call_count_);
9025 }
9026
9027 // Returns true if and only if this expectation is saturated.
9028 bool IsSaturated() const
9029 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9030 g_gmock_mutex.AssertHeld();
9031 return cardinality().IsSaturatedByCallCount(call_count_);
9032 }
9033
9034 // Returns true if and only if this expectation is over-saturated.
9035 bool IsOverSaturated() const
9036 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9037 g_gmock_mutex.AssertHeld();
9038 return cardinality().IsOverSaturatedByCallCount(call_count_);
9039 }
9040
9041 // Returns true if and only if all pre-requisites of this expectation are
9042 // satisfied.
9043 bool AllPrerequisitesAreSatisfied() const
9044 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
9045
9046 // Adds unsatisfied pre-requisites of this expectation to 'result'.
9047 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
9048 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
9049
9050 // Returns the number this expectation has been invoked.
9051 int call_count() const
9052 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9053 g_gmock_mutex.AssertHeld();
9054 return call_count_;
9055 }
9056
9057 // Increments the number this expectation has been invoked.
9058 void IncrementCallCount()
9059 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9060 g_gmock_mutex.AssertHeld();
9061 call_count_++;
9062 }
9063
9064 // Checks the action count (i.e. the number of WillOnce() and
9065 // WillRepeatedly() clauses) against the cardinality if this hasn't
9066 // been done before. Prints a warning if there are too many or too
9067 // few actions.
9068 void CheckActionCountIfNotDone() const
9069 GTEST_LOCK_EXCLUDED_(mutex_);
9070
9071 friend class ::testing::Sequence;
9072 friend class ::testing::internal::ExpectationTester;
9073
9074 template <typename Function>
9075 friend class TypedExpectation;
9076
9077 // Implements the .Times() clause.
9078 void UntypedTimes(const Cardinality& a_cardinality);
9079
9080 // This group of fields are part of the spec and won't change after
9081 // an EXPECT_CALL() statement finishes.
9082 const char* file_; // The file that contains the expectation.
9083 int line_; // The line number of the expectation.
9084 const std::string source_text_; // The EXPECT_CALL(...) source text.
9085 // True if and only if the cardinality is specified explicitly.
9086 bool cardinality_specified_;
9087 Cardinality cardinality_; // The cardinality of the expectation.
9088 // The immediate pre-requisites (i.e. expectations that must be
9089 // satisfied before this expectation can be matched) of this
9090 // expectation. We use std::shared_ptr in the set because we want an
9091 // Expectation object to be co-owned by its FunctionMocker and its
9092 // successors. This allows multiple mock objects to be deleted at
9093 // different times.
9094 ExpectationSet immediate_prerequisites_;
9095
9096 // This group of fields are the current state of the expectation,
9097 // and can change as the mock function is called.
9098 int call_count_; // How many times this expectation has been invoked.
9099 bool retired_; // True if and only if this expectation has retired.
9100 UntypedActions untyped_actions_;
9101 bool extra_matcher_specified_;
9102 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
9103 bool retires_on_saturation_;
9104 Clause last_clause_;
9105 mutable bool action_count_checked_; // Under mutex_.
9106 mutable Mutex mutex_; // Protects action_count_checked_.
9107 }; // class ExpectationBase
9108
9109 // Impements an expectation for the given function type.
9110 template <typename F>
9111 class TypedExpectation : public ExpectationBase {
9112 public:
9113 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
9114 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
9115 typedef typename Function<F>::Result Result;
9116
9117 TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
9118 const std::string& a_source_text,
9119 const ArgumentMatcherTuple& m)
9120 : ExpectationBase(a_file, a_line, a_source_text),
9121 owner_(owner),
9122 matchers_(m),
9123 // By default, extra_matcher_ should match anything. However,
9124 // we cannot initialize it with _ as that causes ambiguity between
9125 // Matcher's copy and move constructor for some argument types.
9126 extra_matcher_(A<const ArgumentTuple&>()),
9127 repeated_action_(DoDefault()) {}
9128
9129 ~TypedExpectation() override {
9130 // Check the validity of the action count if it hasn't been done
9131 // yet (for example, if the expectation was never used).
9132 CheckActionCountIfNotDone();
9133 for (UntypedActions::const_iterator it = untyped_actions_.begin();
9134 it != untyped_actions_.end(); ++it) {
9135 delete static_cast<const Action<F>*>(*it);
9136 }
9137 }
9138
9139 // Implements the .With() clause.
9140 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
9141 if (last_clause_ == kWith) {
9142 ExpectSpecProperty(false,
9143 ".With() cannot appear "
9144 "more than once in an EXPECT_CALL().");
9145 } else {
9146 ExpectSpecProperty(last_clause_ < kWith,
9147 ".With() must be the first "
9148 "clause in an EXPECT_CALL().");
9149 }
9150 last_clause_ = kWith;
9151
9152 extra_matcher_ = m;
9153 extra_matcher_specified_ = true;
9154 return *this;
9155 }
9156
9157 // Implements the .Times() clause.
9158 TypedExpectation& Times(const Cardinality& a_cardinality) {
9159 ExpectationBase::UntypedTimes(a_cardinality);
9160 return *this;
9161 }
9162
9163 // Implements the .Times() clause.
9164 TypedExpectation& Times(int n) {
9165 return Times(Exactly(n));
9166 }
9167
9168 // Implements the .InSequence() clause.
9169 TypedExpectation& InSequence(const Sequence& s) {
9170 ExpectSpecProperty(last_clause_ <= kInSequence,
9171 ".InSequence() cannot appear after .After(),"
9172 " .WillOnce(), .WillRepeatedly(), or "
9173 ".RetiresOnSaturation().");
9174 last_clause_ = kInSequence;
9175
9176 s.AddExpectation(GetHandle());
9177 return *this;
9178 }
9179 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
9180 return InSequence(s1).InSequence(s2);
9181 }
9182 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
9183 const Sequence& s3) {
9184 return InSequence(s1, s2).InSequence(s3);
9185 }
9186 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
9187 const Sequence& s3, const Sequence& s4) {
9188 return InSequence(s1, s2, s3).InSequence(s4);
9189 }
9190 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
9191 const Sequence& s3, const Sequence& s4,
9192 const Sequence& s5) {
9193 return InSequence(s1, s2, s3, s4).InSequence(s5);
9194 }
9195
9196 // Implements that .After() clause.
9197 TypedExpectation& After(const ExpectationSet& s) {
9198 ExpectSpecProperty(last_clause_ <= kAfter,
9199 ".After() cannot appear after .WillOnce(),"
9200 " .WillRepeatedly(), or "
9201 ".RetiresOnSaturation().");
9202 last_clause_ = kAfter;
9203
9204 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
9205 immediate_prerequisites_ += *it;
9206 }
9207 return *this;
9208 }
9209 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
9210 return After(s1).After(s2);
9211 }
9212 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
9213 const ExpectationSet& s3) {
9214 return After(s1, s2).After(s3);
9215 }
9216 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
9217 const ExpectationSet& s3, const ExpectationSet& s4) {
9218 return After(s1, s2, s3).After(s4);
9219 }
9220 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
9221 const ExpectationSet& s3, const ExpectationSet& s4,
9222 const ExpectationSet& s5) {
9223 return After(s1, s2, s3, s4).After(s5);
9224 }
9225
9226 // Implements the .WillOnce() clause.
9227 TypedExpectation& WillOnce(const Action<F>& action) {
9228 ExpectSpecProperty(last_clause_ <= kWillOnce,
9229 ".WillOnce() cannot appear after "
9230 ".WillRepeatedly() or .RetiresOnSaturation().");
9231 last_clause_ = kWillOnce;
9232
9233 untyped_actions_.push_back(new Action<F>(action));
9234 if (!cardinality_specified()) {
9235 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
9236 }
9237 return *this;
9238 }
9239
9240 // Implements the .WillRepeatedly() clause.
9241 TypedExpectation& WillRepeatedly(const Action<F>& action) {
9242 if (last_clause_ == kWillRepeatedly) {
9243 ExpectSpecProperty(false,
9244 ".WillRepeatedly() cannot appear "
9245 "more than once in an EXPECT_CALL().");
9246 } else {
9247 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
9248 ".WillRepeatedly() cannot appear "
9249 "after .RetiresOnSaturation().");
9250 }
9251 last_clause_ = kWillRepeatedly;
9252 repeated_action_specified_ = true;
9253
9254 repeated_action_ = action;
9255 if (!cardinality_specified()) {
9256 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
9257 }
9258
9259 // Now that no more action clauses can be specified, we check
9260 // whether their count makes sense.
9261 CheckActionCountIfNotDone();
9262 return *this;
9263 }
9264
9265 // Implements the .RetiresOnSaturation() clause.
9266 TypedExpectation& RetiresOnSaturation() {
9267 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
9268 ".RetiresOnSaturation() cannot appear "
9269 "more than once.");
9270 last_clause_ = kRetiresOnSaturation;
9271 retires_on_saturation_ = true;
9272
9273 // Now that no more action clauses can be specified, we check
9274 // whether their count makes sense.
9275 CheckActionCountIfNotDone();
9276 return *this;
9277 }
9278
9279 // Returns the matchers for the arguments as specified inside the
9280 // EXPECT_CALL() macro.
9281 const ArgumentMatcherTuple& matchers() const {
9282 return matchers_;
9283 }
9284
9285 // Returns the matcher specified by the .With() clause.
9286 const Matcher<const ArgumentTuple&>& extra_matcher() const {
9287 return extra_matcher_;
9288 }
9289
9290 // Returns the action specified by the .WillRepeatedly() clause.
9291 const Action<F>& repeated_action() const { return repeated_action_; }
9292
9293 // If this mock method has an extra matcher (i.e. .With(matcher)),
9294 // describes it to the ostream.
9295 void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
9296 if (extra_matcher_specified_) {
9297 *os << " Expected args: ";
9298 extra_matcher_.DescribeTo(os);
9299 *os << "\n";
9300 }
9301 }
9302
9303 private:
9304 template <typename Function>
9305 friend class FunctionMocker;
9306
9307 // Returns an Expectation object that references and co-owns this
9308 // expectation.
9309 Expectation GetHandle() override { return owner_->GetHandleOf(this); }
9310
9311 // The following methods will be called only after the EXPECT_CALL()
9312 // statement finishes and when the current thread holds
9313 // g_gmock_mutex.
9314
9315 // Returns true if and only if this expectation matches the given arguments.
9316 bool Matches(const ArgumentTuple& args) const
9317 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9318 g_gmock_mutex.AssertHeld();
9319 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
9320 }
9321
9322 // Returns true if and only if this expectation should handle the given
9323 // arguments.
9324 bool ShouldHandleArguments(const ArgumentTuple& args) const
9325 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9326 g_gmock_mutex.AssertHeld();
9327
9328 // In case the action count wasn't checked when the expectation
9329 // was defined (e.g. if this expectation has no WillRepeatedly()
9330 // or RetiresOnSaturation() clause), we check it when the
9331 // expectation is used for the first time.
9332 CheckActionCountIfNotDone();
9333 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
9334 }
9335
9336 // Describes the result of matching the arguments against this
9337 // expectation to the given ostream.
9338 void ExplainMatchResultTo(
9339 const ArgumentTuple& args,
9340 ::std::ostream* os) const
9341 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9342 g_gmock_mutex.AssertHeld();
9343
9344 if (is_retired()) {
9345 *os << " Expected: the expectation is active\n"
9346 << " Actual: it is retired\n";
9347 } else if (!Matches(args)) {
9348 if (!TupleMatches(matchers_, args)) {
9349 ExplainMatchFailureTupleTo(matchers_, args, os);
9350 }
9351 StringMatchResultListener listener;
9352 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
9353 *os << " Expected args: ";
9354 extra_matcher_.DescribeTo(os);
9355 *os << "\n Actual: don't match";
9356
9357 internal::PrintIfNotEmpty(listener.str(), os);
9358 *os << "\n";
9359 }
9360 } else if (!AllPrerequisitesAreSatisfied()) {
9361 *os << " Expected: all pre-requisites are satisfied\n"
9362 << " Actual: the following immediate pre-requisites "
9363 << "are not satisfied:\n";
9364 ExpectationSet unsatisfied_prereqs;
9365 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
9366 int i = 0;
9367 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
9368 it != unsatisfied_prereqs.end(); ++it) {
9369 it->expectation_base()->DescribeLocationTo(os);
9370 *os << "pre-requisite #" << i++ << "\n";
9371 }
9372 *os << " (end of pre-requisites)\n";
9373 } else {
9374 // This line is here just for completeness' sake. It will never
9375 // be executed as currently the ExplainMatchResultTo() function
9376 // is called only when the mock function call does NOT match the
9377 // expectation.
9378 *os << "The call matches the expectation.\n";
9379 }
9380 }
9381
9382 // Returns the action that should be taken for the current invocation.
9383 const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
9384 const ArgumentTuple& args) const
9385 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9386 g_gmock_mutex.AssertHeld();
9387 const int count = call_count();
9388 Assert(count >= 1, __FILE__, __LINE__,
9389 "call_count() is <= 0 when GetCurrentAction() is "
9390 "called - this should never happen.");
9391
9392 const int action_count = static_cast<int>(untyped_actions_.size());
9393 if (action_count > 0 && !repeated_action_specified_ &&
9394 count > action_count) {
9395 // If there is at least one WillOnce() and no WillRepeatedly(),
9396 // we warn the user when the WillOnce() clauses ran out.
9397 ::std::stringstream ss;
9398 DescribeLocationTo(&ss);
9399 ss << "Actions ran out in " << source_text() << "...\n"
9400 << "Called " << count << " times, but only "
9401 << action_count << " WillOnce()"
9402 << (action_count == 1 ? " is" : "s are") << " specified - ";
9403 mocker->DescribeDefaultActionTo(args, &ss);
9404 Log(kWarning, ss.str(), 1);
9405 }
9406
9407 return count <= action_count
9408 ? *static_cast<const Action<F>*>(
9409 untyped_actions_[static_cast<size_t>(count - 1)])
9410 : repeated_action();
9411 }
9412
9413 // Given the arguments of a mock function call, if the call will
9414 // over-saturate this expectation, returns the default action;
9415 // otherwise, returns the next action in this expectation. Also
9416 // describes *what* happened to 'what', and explains *why* Google
9417 // Mock does it to 'why'. This method is not const as it calls
9418 // IncrementCallCount(). A return value of NULL means the default
9419 // action.
9420 const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
9421 const ArgumentTuple& args,
9422 ::std::ostream* what,
9423 ::std::ostream* why)
9424 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9425 g_gmock_mutex.AssertHeld();
9426 if (IsSaturated()) {
9427 // We have an excessive call.
9428 IncrementCallCount();
9429 *what << "Mock function called more times than expected - ";
9430 mocker->DescribeDefaultActionTo(args, what);
9431 DescribeCallCountTo(why);
9432
9433 return nullptr;
9434 }
9435
9436 IncrementCallCount();
9437 RetireAllPreRequisites();
9438
9439 if (retires_on_saturation_ && IsSaturated()) {
9440 Retire();
9441 }
9442
9443 // Must be done after IncrementCount()!
9444 *what << "Mock function call matches " << source_text() <<"...\n";
9445 return &(GetCurrentAction(mocker, args));
9446 }
9447
9448 // All the fields below won't change once the EXPECT_CALL()
9449 // statement finishes.
9450 FunctionMocker<F>* const owner_;
9451 ArgumentMatcherTuple matchers_;
9452 Matcher<const ArgumentTuple&> extra_matcher_;
9453 Action<F> repeated_action_;
9454
9455 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
9456 }; // class TypedExpectation
9457
9458 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
9459 // specifying the default behavior of, or expectation on, a mock
9460 // function.
9461
9462 // Note: class MockSpec really belongs to the ::testing namespace.
9463 // However if we define it in ::testing, MSVC will complain when
9464 // classes in ::testing::internal declare it as a friend class
9465 // template. To workaround this compiler bug, we define MockSpec in
9466 // ::testing::internal and import it into ::testing.
9467
9468 // Logs a message including file and line number information.
9469 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
9470 const char* file, int line,
9471 const std::string& message);
9472
9473 template <typename F>
9474 class MockSpec {
9475 public:
9476 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
9477 typedef typename internal::Function<F>::ArgumentMatcherTuple
9478 ArgumentMatcherTuple;
9479
9480 // Constructs a MockSpec object, given the function mocker object
9481 // that the spec is associated with.
9482 MockSpec(internal::FunctionMocker<F>* function_mocker,
9483 const ArgumentMatcherTuple& matchers)
9484 : function_mocker_(function_mocker), matchers_(matchers) {}
9485
9486 // Adds a new default action spec to the function mocker and returns
9487 // the newly created spec.
9488 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
9489 const char* file, int line, const char* obj, const char* call) {
9490 LogWithLocation(internal::kInfo, file, line,
9491 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
9492 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
9493 }
9494
9495 // Adds a new expectation spec to the function mocker and returns
9496 // the newly created spec.
9497 internal::TypedExpectation<F>& InternalExpectedAt(
9498 const char* file, int line, const char* obj, const char* call) {
9499 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
9500 call + ")");
9501 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
9502 return function_mocker_->AddNewExpectation(
9503 file, line, source_text, matchers_);
9504 }
9505
9506 // This operator overload is used to swallow the superfluous parameter list
9507 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
9508 // explanation.
9509 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
9510 return *this;
9511 }
9512
9513 private:
9514 template <typename Function>
9515 friend class internal::FunctionMocker;
9516
9517 // The function mocker that owns this spec.
9518 internal::FunctionMocker<F>* const function_mocker_;
9519 // The argument matchers specified in the spec.
9520 ArgumentMatcherTuple matchers_;
9521 }; // class MockSpec
9522
9523 // Wrapper type for generically holding an ordinary value or lvalue reference.
9524 // If T is not a reference type, it must be copyable or movable.
9525 // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
9526 // T is a move-only value type (which means that it will always be copyable
9527 // if the current platform does not support move semantics).
9528 //
9529 // The primary template defines handling for values, but function header
9530 // comments describe the contract for the whole template (including
9531 // specializations).
9532 template <typename T>
9533 class ReferenceOrValueWrapper {
9534 public:
9535 // Constructs a wrapper from the given value/reference.
9536 explicit ReferenceOrValueWrapper(T value)
9537 : value_(std::move(value)) {
9538 }
9539
9540 // Unwraps and returns the underlying value/reference, exactly as
9541 // originally passed. The behavior of calling this more than once on
9542 // the same object is unspecified.
9543 T Unwrap() { return std::move(value_); }
9544
9545 // Provides nondestructive access to the underlying value/reference.
9546 // Always returns a const reference (more precisely,
9547 // const std::add_lvalue_reference<T>::type). The behavior of calling this
9548 // after calling Unwrap on the same object is unspecified.
9549 const T& Peek() const {
9550 return value_;
9551 }
9552
9553 private:
9554 T value_;
9555 };
9556
9557 // Specialization for lvalue reference types. See primary template
9558 // for documentation.
9559 template <typename T>
9560 class ReferenceOrValueWrapper<T&> {
9561 public:
9562 // Workaround for debatable pass-by-reference lint warning (c-library-team
9563 // policy precludes NOLINT in this context)
9564 typedef T& reference;
9565 explicit ReferenceOrValueWrapper(reference ref)
9566 : value_ptr_(&ref) {}
9567 T& Unwrap() { return *value_ptr_; }
9568 const T& Peek() const { return *value_ptr_; }
9569
9570 private:
9571 T* value_ptr_;
9572 };
9573
9574 // C++ treats the void type specially. For example, you cannot define
9575 // a void-typed variable or pass a void value to a function.
9576 // ActionResultHolder<T> holds a value of type T, where T must be a
9577 // copyable type or void (T doesn't need to be default-constructable).
9578 // It hides the syntactic difference between void and other types, and
9579 // is used to unify the code for invoking both void-returning and
9580 // non-void-returning mock functions.
9581
9582 // Untyped base class for ActionResultHolder<T>.
9583 class UntypedActionResultHolderBase {
9584 public:
9585 virtual ~UntypedActionResultHolderBase() {}
9586
9587 // Prints the held value as an action's result to os.
9588 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
9589 };
9590
9591 // This generic definition is used when T is not void.
9592 template <typename T>
9593 class ActionResultHolder : public UntypedActionResultHolderBase {
9594 public:
9595 // Returns the held value. Must not be called more than once.
9596 T Unwrap() {
9597 return result_.Unwrap();
9598 }
9599
9600 // Prints the held value as an action's result to os.
9601 void PrintAsActionResult(::std::ostream* os) const override {
9602 *os << "\n Returns: ";
9603 // T may be a reference type, so we don't use UniversalPrint().
9604 UniversalPrinter<T>::Print(result_.Peek(), os);
9605 }
9606
9607 // Performs the given mock function's default action and returns the
9608 // result in a new-ed ActionResultHolder.
9609 template <typename F>
9610 static ActionResultHolder* PerformDefaultAction(
9611 const FunctionMocker<F>* func_mocker,
9612 typename Function<F>::ArgumentTuple&& args,
9613 const std::string& call_description) {
9614 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
9615 std::move(args), call_description)));
9616 }
9617
9618 // Performs the given action and returns the result in a new-ed
9619 // ActionResultHolder.
9620 template <typename F>
9621 static ActionResultHolder* PerformAction(
9622 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
9623 return new ActionResultHolder(
9624 Wrapper(action.Perform(std::move(args))));
9625 }
9626
9627 private:
9628 typedef ReferenceOrValueWrapper<T> Wrapper;
9629
9630 explicit ActionResultHolder(Wrapper result)
9631 : result_(std::move(result)) {
9632 }
9633
9634 Wrapper result_;
9635
9636 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
9637 };
9638
9639 // Specialization for T = void.
9640 template <>
9641 class ActionResultHolder<void> : public UntypedActionResultHolderBase {
9642 public:
9643 void Unwrap() { }
9644
9645 void PrintAsActionResult(::std::ostream* /* os */) const override {}
9646
9647 // Performs the given mock function's default action and returns ownership
9648 // of an empty ActionResultHolder*.
9649 template <typename F>
9650 static ActionResultHolder* PerformDefaultAction(
9651 const FunctionMocker<F>* func_mocker,
9652 typename Function<F>::ArgumentTuple&& args,
9653 const std::string& call_description) {
9654 func_mocker->PerformDefaultAction(std::move(args), call_description);
9655 return new ActionResultHolder;
9656 }
9657
9658 // Performs the given action and returns ownership of an empty
9659 // ActionResultHolder*.
9660 template <typename F>
9661 static ActionResultHolder* PerformAction(
9662 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
9663 action.Perform(std::move(args));
9664 return new ActionResultHolder;
9665 }
9666
9667 private:
9668 ActionResultHolder() {}
9669 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
9670 };
9671
9672 template <typename F>
9673 class FunctionMocker;
9674
9675 template <typename R, typename... Args>
9676 class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
9677 using F = R(Args...);
9678
9679 public:
9680 using Result = R;
9681 using ArgumentTuple = std::tuple<Args...>;
9682 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
9683
9684 FunctionMocker() {}
9685
9686 // There is no generally useful and implementable semantics of
9687 // copying a mock object, so copying a mock is usually a user error.
9688 // Thus we disallow copying function mockers. If the user really
9689 // wants to copy a mock object, they should implement their own copy
9690 // operation, for example:
9691 //
9692 // class MockFoo : public Foo {
9693 // public:
9694 // // Defines a copy constructor explicitly.
9695 // MockFoo(const MockFoo& src) {}
9696 // ...
9697 // };
9698 FunctionMocker(const FunctionMocker&) = delete;
9699 FunctionMocker& operator=(const FunctionMocker&) = delete;
9700
9701 // The destructor verifies that all expectations on this mock
9702 // function have been satisfied. If not, it will report Google Test
9703 // non-fatal failures for the violations.
9704 ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9705 MutexLock l(&g_gmock_mutex);
9706 VerifyAndClearExpectationsLocked();
9707 Mock::UnregisterLocked(this);
9708 ClearDefaultActionsLocked();
9709 }
9710
9711 // Returns the ON_CALL spec that matches this mock function with the
9712 // given arguments; returns NULL if no matching ON_CALL is found.
9713 // L = *
9714 const OnCallSpec<F>* FindOnCallSpec(
9715 const ArgumentTuple& args) const {
9716 for (UntypedOnCallSpecs::const_reverse_iterator it
9717 = untyped_on_call_specs_.rbegin();
9718 it != untyped_on_call_specs_.rend(); ++it) {
9719 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
9720 if (spec->Matches(args))
9721 return spec;
9722 }
9723
9724 return nullptr;
9725 }
9726
9727 // Performs the default action of this mock function on the given
9728 // arguments and returns the result. Asserts (or throws if
9729 // exceptions are enabled) with a helpful call descrption if there
9730 // is no valid return value. This method doesn't depend on the
9731 // mutable state of this object, and thus can be called concurrently
9732 // without locking.
9733 // L = *
9734 Result PerformDefaultAction(ArgumentTuple&& args,
9735 const std::string& call_description) const {
9736 const OnCallSpec<F>* const spec =
9737 this->FindOnCallSpec(args);
9738 if (spec != nullptr) {
9739 return spec->GetAction().Perform(std::move(args));
9740 }
9741 const std::string message =
9742 call_description +
9743 "\n The mock function has no default action "
9744 "set, and its return type has no default value set.";
9745 #if GTEST_HAS_EXCEPTIONS
9746 if (!DefaultValue<Result>::Exists()) {
9747 throw std::runtime_error(message);
9748 }
9749 #else
9750 Assert(DefaultValue<Result>::Exists(), "", -1, message);
9751 #endif
9752 return DefaultValue<Result>::Get();
9753 }
9754
9755 // Performs the default action with the given arguments and returns
9756 // the action's result. The call description string will be used in
9757 // the error message to describe the call in the case the default
9758 // action fails. The caller is responsible for deleting the result.
9759 // L = *
9760 UntypedActionResultHolderBase* UntypedPerformDefaultAction(
9761 void* untyped_args, // must point to an ArgumentTuple
9762 const std::string& call_description) const override {
9763 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
9764 return ResultHolder::PerformDefaultAction(this, std::move(*args),
9765 call_description);
9766 }
9767
9768 // Performs the given action with the given arguments and returns
9769 // the action's result. The caller is responsible for deleting the
9770 // result.
9771 // L = *
9772 UntypedActionResultHolderBase* UntypedPerformAction(
9773 const void* untyped_action, void* untyped_args) const override {
9774 // Make a copy of the action before performing it, in case the
9775 // action deletes the mock object (and thus deletes itself).
9776 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
9777 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
9778 return ResultHolder::PerformAction(action, std::move(*args));
9779 }
9780
9781 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
9782 // clears the ON_CALL()s set on this mock function.
9783 void ClearDefaultActionsLocked() override
9784 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9785 g_gmock_mutex.AssertHeld();
9786
9787 // Deleting our default actions may trigger other mock objects to be
9788 // deleted, for example if an action contains a reference counted smart
9789 // pointer to that mock object, and that is the last reference. So if we
9790 // delete our actions within the context of the global mutex we may deadlock
9791 // when this method is called again. Instead, make a copy of the set of
9792 // actions to delete, clear our set within the mutex, and then delete the
9793 // actions outside of the mutex.
9794 UntypedOnCallSpecs specs_to_delete;
9795 untyped_on_call_specs_.swap(specs_to_delete);
9796
9797 g_gmock_mutex.Unlock();
9798 for (UntypedOnCallSpecs::const_iterator it =
9799 specs_to_delete.begin();
9800 it != specs_to_delete.end(); ++it) {
9801 delete static_cast<const OnCallSpec<F>*>(*it);
9802 }
9803
9804 // Lock the mutex again, since the caller expects it to be locked when we
9805 // return.
9806 g_gmock_mutex.Lock();
9807 }
9808
9809 // Returns the result of invoking this mock function with the given
9810 // arguments. This function can be safely called from multiple
9811 // threads concurrently.
9812 Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9813 ArgumentTuple tuple(std::forward<Args>(args)...);
9814 std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
9815 this->UntypedInvokeWith(static_cast<void*>(&tuple))));
9816 return holder->Unwrap();
9817 }
9818
9819 MockSpec<F> With(Matcher<Args>... m) {
9820 return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
9821 }
9822
9823 protected:
9824 template <typename Function>
9825 friend class MockSpec;
9826
9827 typedef ActionResultHolder<Result> ResultHolder;
9828
9829 // Adds and returns a default action spec for this mock function.
9830 OnCallSpec<F>& AddNewOnCallSpec(
9831 const char* file, int line,
9832 const ArgumentMatcherTuple& m)
9833 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9834 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
9835 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
9836 untyped_on_call_specs_.push_back(on_call_spec);
9837 return *on_call_spec;
9838 }
9839
9840 // Adds and returns an expectation spec for this mock function.
9841 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
9842 const std::string& source_text,
9843 const ArgumentMatcherTuple& m)
9844 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9845 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
9846 TypedExpectation<F>* const expectation =
9847 new TypedExpectation<F>(this, file, line, source_text, m);
9848 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
9849 // See the definition of untyped_expectations_ for why access to
9850 // it is unprotected here.
9851 untyped_expectations_.push_back(untyped_expectation);
9852
9853 // Adds this expectation into the implicit sequence if there is one.
9854 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
9855 if (implicit_sequence != nullptr) {
9856 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
9857 }
9858
9859 return *expectation;
9860 }
9861
9862 private:
9863 template <typename Func> friend class TypedExpectation;
9864
9865 // Some utilities needed for implementing UntypedInvokeWith().
9866
9867 // Describes what default action will be performed for the given
9868 // arguments.
9869 // L = *
9870 void DescribeDefaultActionTo(const ArgumentTuple& args,
9871 ::std::ostream* os) const {
9872 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
9873
9874 if (spec == nullptr) {
9875 *os << (std::is_void<Result>::value ? "returning directly.\n"
9876 : "returning default value.\n");
9877 } else {
9878 *os << "taking default action specified at:\n"
9879 << FormatFileLocation(spec->file(), spec->line()) << "\n";
9880 }
9881 }
9882
9883 // Writes a message that the call is uninteresting (i.e. neither
9884 // explicitly expected nor explicitly unexpected) to the given
9885 // ostream.
9886 void UntypedDescribeUninterestingCall(const void* untyped_args,
9887 ::std::ostream* os) const override
9888 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9889 const ArgumentTuple& args =
9890 *static_cast<const ArgumentTuple*>(untyped_args);
9891 *os << "Uninteresting mock function call - ";
9892 DescribeDefaultActionTo(args, os);
9893 *os << " Function call: " << Name();
9894 UniversalPrint(args, os);
9895 }
9896
9897 // Returns the expectation that matches the given function arguments
9898 // (or NULL is there's no match); when a match is found,
9899 // untyped_action is set to point to the action that should be
9900 // performed (or NULL if the action is "do default"), and
9901 // is_excessive is modified to indicate whether the call exceeds the
9902 // expected number.
9903 //
9904 // Critical section: We must find the matching expectation and the
9905 // corresponding action that needs to be taken in an ATOMIC
9906 // transaction. Otherwise another thread may call this mock
9907 // method in the middle and mess up the state.
9908 //
9909 // However, performing the action has to be left out of the critical
9910 // section. The reason is that we have no control on what the
9911 // action does (it can invoke an arbitrary user function or even a
9912 // mock function) and excessive locking could cause a dead lock.
9913 const ExpectationBase* UntypedFindMatchingExpectation(
9914 const void* untyped_args, const void** untyped_action, bool* is_excessive,
9915 ::std::ostream* what, ::std::ostream* why) override
9916 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9917 const ArgumentTuple& args =
9918 *static_cast<const ArgumentTuple*>(untyped_args);
9919 MutexLock l(&g_gmock_mutex);
9920 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
9921 if (exp == nullptr) { // A match wasn't found.
9922 this->FormatUnexpectedCallMessageLocked(args, what, why);
9923 return nullptr;
9924 }
9925
9926 // This line must be done before calling GetActionForArguments(),
9927 // which will increment the call count for *exp and thus affect
9928 // its saturation status.
9929 *is_excessive = exp->IsSaturated();
9930 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
9931 if (action != nullptr && action->IsDoDefault())
9932 action = nullptr; // Normalize "do default" to NULL.
9933 *untyped_action = action;
9934 return exp;
9935 }
9936
9937 // Prints the given function arguments to the ostream.
9938 void UntypedPrintArgs(const void* untyped_args,
9939 ::std::ostream* os) const override {
9940 const ArgumentTuple& args =
9941 *static_cast<const ArgumentTuple*>(untyped_args);
9942 UniversalPrint(args, os);
9943 }
9944
9945 // Returns the expectation that matches the arguments, or NULL if no
9946 // expectation matches them.
9947 TypedExpectation<F>* FindMatchingExpectationLocked(
9948 const ArgumentTuple& args) const
9949 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9950 g_gmock_mutex.AssertHeld();
9951 // See the definition of untyped_expectations_ for why access to
9952 // it is unprotected here.
9953 for (typename UntypedExpectations::const_reverse_iterator it =
9954 untyped_expectations_.rbegin();
9955 it != untyped_expectations_.rend(); ++it) {
9956 TypedExpectation<F>* const exp =
9957 static_cast<TypedExpectation<F>*>(it->get());
9958 if (exp->ShouldHandleArguments(args)) {
9959 return exp;
9960 }
9961 }
9962 return nullptr;
9963 }
9964
9965 // Returns a message that the arguments don't match any expectation.
9966 void FormatUnexpectedCallMessageLocked(
9967 const ArgumentTuple& args,
9968 ::std::ostream* os,
9969 ::std::ostream* why) const
9970 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9971 g_gmock_mutex.AssertHeld();
9972 *os << "\nUnexpected mock function call - ";
9973 DescribeDefaultActionTo(args, os);
9974 PrintTriedExpectationsLocked(args, why);
9975 }
9976
9977 // Prints a list of expectations that have been tried against the
9978 // current mock function call.
9979 void PrintTriedExpectationsLocked(
9980 const ArgumentTuple& args,
9981 ::std::ostream* why) const
9982 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9983 g_gmock_mutex.AssertHeld();
9984 const size_t count = untyped_expectations_.size();
9985 *why << "Google Mock tried the following " << count << " "
9986 << (count == 1 ? "expectation, but it didn't match" :
9987 "expectations, but none matched")
9988 << ":\n";
9989 for (size_t i = 0; i < count; i++) {
9990 TypedExpectation<F>* const expectation =
9991 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
9992 *why << "\n";
9993 expectation->DescribeLocationTo(why);
9994 if (count > 1) {
9995 *why << "tried expectation #" << i << ": ";
9996 }
9997 *why << expectation->source_text() << "...\n";
9998 expectation->ExplainMatchResultTo(args, why);
9999 expectation->DescribeCallCountTo(why);
10000 }
10001 }
10002 }; // class FunctionMocker
10003
10004 // Reports an uninteresting call (whose description is in msg) in the
10005 // manner specified by 'reaction'.
10006 void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
10007
10008 } // namespace internal
10009
10010 namespace internal {
10011
10012 template <typename F>
10013 class MockFunction;
10014
10015 template <typename R, typename... Args>
10016 class MockFunction<R(Args...)> {
10017 public:
10018 MockFunction(const MockFunction&) = delete;
10019 MockFunction& operator=(const MockFunction&) = delete;
10020
10021 std::function<R(Args...)> AsStdFunction() {
10022 return [this](Args... args) -> R {
10023 return this->Call(std::forward<Args>(args)...);
10024 };
10025 }
10026
10027 // Implementation detail: the expansion of the MOCK_METHOD macro.
10028 R Call(Args... args) {
10029 mock_.SetOwnerAndName(this, "Call");
10030 return mock_.Invoke(std::forward<Args>(args)...);
10031 }
10032
10033 MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
10034 mock_.RegisterOwner(this);
10035 return mock_.With(std::move(m)...);
10036 }
10037
10038 MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
10039 return this->gmock_Call(::testing::A<Args>()...);
10040 }
10041
10042 protected:
10043 MockFunction() = default;
10044 ~MockFunction() = default;
10045
10046 private:
10047 FunctionMocker<R(Args...)> mock_;
10048 };
10049
10050 /*
10051 The SignatureOf<F> struct is a meta-function returning function signature
10052 corresponding to the provided F argument.
10053
10054 It makes use of MockFunction easier by allowing it to accept more F arguments
10055 than just function signatures.
10056
10057 Specializations provided here cover only a signature type itself and
10058 std::function. However, if need be it can be easily extended to cover also other
10059 types (like for example boost::function).
10060 */
10061
10062 template <typename F>
10063 struct SignatureOf;
10064
10065 template <typename R, typename... Args>
10066 struct SignatureOf<R(Args...)> {
10067 using type = R(Args...);
10068 };
10069
10070 template <typename F>
10071 struct SignatureOf<std::function<F>> : SignatureOf<F> {};
10072
10073 template <typename F>
10074 using SignatureOfT = typename SignatureOf<F>::type;
10075
10076 } // namespace internal
10077
10078 // A MockFunction<F> type has one mock method whose type is
10079 // internal::SignatureOfT<F>. It is useful when you just want your
10080 // test code to emit some messages and have Google Mock verify the
10081 // right messages are sent (and perhaps at the right times). For
10082 // example, if you are exercising code:
10083 //
10084 // Foo(1);
10085 // Foo(2);
10086 // Foo(3);
10087 //
10088 // and want to verify that Foo(1) and Foo(3) both invoke
10089 // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
10090 //
10091 // TEST(FooTest, InvokesBarCorrectly) {
10092 // MyMock mock;
10093 // MockFunction<void(string check_point_name)> check;
10094 // {
10095 // InSequence s;
10096 //
10097 // EXPECT_CALL(mock, Bar("a"));
10098 // EXPECT_CALL(check, Call("1"));
10099 // EXPECT_CALL(check, Call("2"));
10100 // EXPECT_CALL(mock, Bar("a"));
10101 // }
10102 // Foo(1);
10103 // check.Call("1");
10104 // Foo(2);
10105 // check.Call("2");
10106 // Foo(3);
10107 // }
10108 //
10109 // The expectation spec says that the first Bar("a") must happen
10110 // before check point "1", the second Bar("a") must happen after check
10111 // point "2", and nothing should happen between the two check
10112 // points. The explicit check points make it easy to tell which
10113 // Bar("a") is called by which call to Foo().
10114 //
10115 // MockFunction<F> can also be used to exercise code that accepts
10116 // std::function<internal::SignatureOfT<F>> callbacks. To do so, use
10117 // AsStdFunction() method to create std::function proxy forwarding to
10118 // original object's Call. Example:
10119 //
10120 // TEST(FooTest, RunsCallbackWithBarArgument) {
10121 // MockFunction<int(string)> callback;
10122 // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
10123 // Foo(callback.AsStdFunction());
10124 // }
10125 //
10126 // The internal::SignatureOfT<F> indirection allows to use other types
10127 // than just function signature type. This is typically useful when
10128 // providing a mock for a predefined std::function type. Example:
10129 //
10130 // using FilterPredicate = std::function<bool(string)>;
10131 // void MyFilterAlgorithm(FilterPredicate predicate);
10132 //
10133 // TEST(FooTest, FilterPredicateAlwaysAccepts) {
10134 // MockFunction<FilterPredicate> predicateMock;
10135 // EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
10136 // MyFilterAlgorithm(predicateMock.AsStdFunction());
10137 // }
10138 template <typename F>
10139 class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
10140 using Base = internal::MockFunction<internal::SignatureOfT<F>>;
10141
10142 public:
10143 using Base::Base;
10144 };
10145
10146 // The style guide prohibits "using" statements in a namespace scope
10147 // inside a header file. However, the MockSpec class template is
10148 // meant to be defined in the ::testing namespace. The following line
10149 // is just a trick for working around a bug in MSVC 8.0, which cannot
10150 // handle it if we define MockSpec in ::testing.
10151 using internal::MockSpec;
10152
10153 // Const(x) is a convenient function for obtaining a const reference
10154 // to x. This is useful for setting expectations on an overloaded
10155 // const mock method, e.g.
10156 //
10157 // class MockFoo : public FooInterface {
10158 // public:
10159 // MOCK_METHOD0(Bar, int());
10160 // MOCK_CONST_METHOD0(Bar, int&());
10161 // };
10162 //
10163 // MockFoo foo;
10164 // // Expects a call to non-const MockFoo::Bar().
10165 // EXPECT_CALL(foo, Bar());
10166 // // Expects a call to const MockFoo::Bar().
10167 // EXPECT_CALL(Const(foo), Bar());
10168 template <typename T>
10169 inline const T& Const(const T& x) { return x; }
10170
10171 // Constructs an Expectation object that references and co-owns exp.
10172 inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
10173 : expectation_base_(exp.GetHandle().expectation_base()) {}
10174
10175 } // namespace testing
10176
10177 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
10178
10179 // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
10180 // required to avoid compile errors when the name of the method used in call is
10181 // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
10182 // tests in internal/gmock-spec-builders_test.cc for more details.
10183 //
10184 // This macro supports statements both with and without parameter matchers. If
10185 // the parameter list is omitted, gMock will accept any parameters, which allows
10186 // tests to be written that don't need to encode the number of method
10187 // parameter. This technique may only be used for non-overloaded methods.
10188 //
10189 // // These are the same:
10190 // ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
10191 // ON_CALL(mock, NoArgsMethod).WillByDefault(...);
10192 //
10193 // // As are these:
10194 // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
10195 // ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
10196 //
10197 // // Can also specify args if you want, of course:
10198 // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
10199 //
10200 // // Overloads work as long as you specify parameters:
10201 // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
10202 // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
10203 //
10204 // // Oops! Which overload did you want?
10205 // ON_CALL(mock, OverloadedMethod).WillByDefault(...);
10206 // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
10207 //
10208 // How this works: The mock class uses two overloads of the gmock_Method
10209 // expectation setter method plus an operator() overload on the MockSpec object.
10210 // In the matcher list form, the macro expands to:
10211 //
10212 // // This statement:
10213 // ON_CALL(mock, TwoArgsMethod(_, 45))...
10214 //
10215 // // ...expands to:
10216 // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
10217 // |-------------v---------------||------------v-------------|
10218 // invokes first overload swallowed by operator()
10219 //
10220 // // ...which is essentially:
10221 // mock.gmock_TwoArgsMethod(_, 45)...
10222 //
10223 // Whereas the form without a matcher list:
10224 //
10225 // // This statement:
10226 // ON_CALL(mock, TwoArgsMethod)...
10227 //
10228 // // ...expands to:
10229 // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
10230 // |-----------------------v--------------------------|
10231 // invokes second overload
10232 //
10233 // // ...which is essentially:
10234 // mock.gmock_TwoArgsMethod(_, _)...
10235 //
10236 // The WithoutMatchers() argument is used to disambiguate overloads and to
10237 // block the caller from accidentally invoking the second overload directly. The
10238 // second argument is an internal type derived from the method signature. The
10239 // failure to disambiguate two overloads of this method in the ON_CALL statement
10240 // is how we block callers from setting expectations on overloaded methods.
10241 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
10242 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
10243 nullptr) \
10244 .Setter(__FILE__, __LINE__, #mock_expr, #call)
10245
10246 #define ON_CALL(obj, call) \
10247 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
10248
10249 #define EXPECT_CALL(obj, call) \
10250 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
10251
10252 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
10253
10254 namespace testing {
10255 namespace internal {
10256 template <typename T>
10257 using identity_t = T;
10258
10259 template <typename Pattern>
10260 struct ThisRefAdjuster {
10261 template <typename T>
10262 using AdjustT = typename std::conditional<
10263 std::is_const<typename std::remove_reference<Pattern>::type>::value,
10264 typename std::conditional<std::is_lvalue_reference<Pattern>::value,
10265 const T&, const T&&>::type,
10266 typename std::conditional<std::is_lvalue_reference<Pattern>::value, T&,
10267 T&&>::type>::type;
10268
10269 template <typename MockType>
10270 static AdjustT<MockType> Adjust(const MockType& mock) {
10271 return static_cast<AdjustT<MockType>>(const_cast<MockType&>(mock));
10272 }
10273 };
10274
10275 } // namespace internal
10276
10277 // The style guide prohibits "using" statements in a namespace scope
10278 // inside a header file. However, the FunctionMocker class template
10279 // is meant to be defined in the ::testing namespace. The following
10280 // line is just a trick for working around a bug in MSVC 8.0, which
10281 // cannot handle it if we define FunctionMocker in ::testing.
10282 using internal::FunctionMocker;
10283 } // namespace testing
10284
10285 #define MOCK_METHOD(...) \
10286 GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__)
10287
10288 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \
10289 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10290
10291 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \
10292 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10293
10294 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \
10295 GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ())
10296
10297 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \
10298 GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \
10299 GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \
10300 GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
10301 GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \
10302 GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
10303 GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
10304 GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \
10305 GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \
10306 GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \
10307 GMOCK_INTERNAL_GET_CALLTYPE(_Spec), GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \
10308 (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)))
10309
10310 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \
10311 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10312
10313 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \
10314 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10315
10316 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \
10317 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10318
10319 #define GMOCK_INTERNAL_WRONG_ARITY(...) \
10320 static_assert( \
10321 false, \
10322 "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \
10323 "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \
10324 "enclosed in parentheses. If _Ret is a type with unprotected commas, " \
10325 "it must also be enclosed in parentheses.")
10326
10327 #define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \
10328 static_assert( \
10329 GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \
10330 GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.")
10331
10332 #define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \
10333 static_assert( \
10334 std::is_function<__VA_ARGS__>::value, \
10335 "Signature must be a function type, maybe return type contains " \
10336 "unprotected comma."); \
10337 static_assert( \
10338 ::testing::tuple_size<typename ::testing::internal::Function< \
10339 __VA_ARGS__>::ArgumentTuple>::value == _N, \
10340 "This method does not take " GMOCK_PP_STRINGIZE( \
10341 _N) " arguments. Parenthesize all types with unprotected commas.")
10342
10343 #define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
10344 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec)
10345
10346 #define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \
10347 _Override, _Final, _NoexceptSpec, \
10348 _CallType, _RefSpec, _Signature) \
10349 typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \
10350 _Signature)>::Result \
10351 GMOCK_INTERNAL_EXPAND(_CallType) \
10352 _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \
10353 GMOCK_PP_IF(_Constness, const, ) _RefSpec _NoexceptSpec \
10354 GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \
10355 GMOCK_MOCKER_(_N, _Constness, _MethodName) \
10356 .SetOwnerAndName(this, #_MethodName); \
10357 return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
10358 .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \
10359 } \
10360 ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
10361 GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \
10362 GMOCK_PP_IF(_Constness, const, ) _RefSpec { \
10363 GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \
10364 return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
10365 .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \
10366 } \
10367 ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
10368 const ::testing::internal::WithoutMatchers&, \
10369 GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \
10370 GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \
10371 return ::testing::internal::ThisRefAdjuster<GMOCK_PP_IF( \
10372 _Constness, const, ) int _RefSpec>::Adjust(*this) \
10373 .gmock_##_MethodName(GMOCK_PP_REPEAT( \
10374 GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \
10375 } \
10376 mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \
10377 GMOCK_MOCKER_(_N, _Constness, _MethodName)
10378
10379 #define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__
10380
10381 // Five Valid modifiers.
10382 #define GMOCK_INTERNAL_HAS_CONST(_Tuple) \
10383 GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple))
10384
10385 #define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \
10386 GMOCK_PP_HAS_COMMA( \
10387 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple))
10388
10389 #define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \
10390 GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple))
10391
10392 #define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \
10393 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple)
10394
10395 #define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \
10396 GMOCK_PP_IF( \
10397 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \
10398 _elem, )
10399
10400 #define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \
10401 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple)
10402
10403 #define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \
10404 GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \
10405 GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
10406
10407 #define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \
10408 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple)
10409
10410 #define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \
10411 static_assert( \
10412 (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \
10413 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \
10414 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \
10415 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \
10416 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \
10417 GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \
10418 GMOCK_PP_STRINGIZE( \
10419 _elem) " cannot be recognized as a valid specification modifier.");
10420
10421 // Modifiers implementation.
10422 #define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \
10423 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem)
10424
10425 #define GMOCK_INTERNAL_DETECT_CONST_I_const ,
10426
10427 #define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \
10428 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem)
10429
10430 #define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override ,
10431
10432 #define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \
10433 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem)
10434
10435 #define GMOCK_INTERNAL_DETECT_FINAL_I_final ,
10436
10437 #define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \
10438 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem)
10439
10440 #define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept ,
10441
10442 #define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \
10443 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem)
10444
10445 #define GMOCK_INTERNAL_DETECT_REF_I_ref ,
10446
10447 #define GMOCK_INTERNAL_UNPACK_ref(x) x
10448
10449 #define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \
10450 GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \
10451 GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \
10452 (_elem)
10453
10454 // TODO(iserna): GMOCK_INTERNAL_IS_CALLTYPE and
10455 // GMOCK_INTERNAL_GET_VALUE_CALLTYPE needed more expansions to work on windows
10456 // maybe they can be simplified somehow.
10457 #define GMOCK_INTERNAL_IS_CALLTYPE(_arg) \
10458 GMOCK_INTERNAL_IS_CALLTYPE_I( \
10459 GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
10460 #define GMOCK_INTERNAL_IS_CALLTYPE_I(_arg) GMOCK_PP_IS_ENCLOSED_PARENS(_arg)
10461
10462 #define GMOCK_INTERNAL_GET_VALUE_CALLTYPE(_arg) \
10463 GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I( \
10464 GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
10465 #define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \
10466 GMOCK_PP_IDENTITY _arg
10467
10468 #define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype
10469
10470 // Note: The use of `identity_t` here allows _Ret to represent return types that
10471 // would normally need to be specified in a different way. For example, a method
10472 // returning a function pointer must be written as
10473 //
10474 // fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...)
10475 //
10476 // But we only support placing the return type at the beginning. To handle this,
10477 // we wrap all calls in identity_t, so that a declaration will be expanded to
10478 //
10479 // identity_t<fn_ptr_return_t (*)(fn_ptr_args_t...)> method(method_args_t...)
10480 //
10481 // This allows us to work around the syntactic oddities of function/method
10482 // types.
10483 #define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \
10484 ::testing::internal::identity_t<GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), \
10485 GMOCK_PP_REMOVE_PARENS, \
10486 GMOCK_PP_IDENTITY)(_Ret)>( \
10487 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args))
10488
10489 #define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \
10490 GMOCK_PP_COMMA_IF(_i) \
10491 GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \
10492 GMOCK_PP_IDENTITY) \
10493 (_elem)
10494
10495 #define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
10496 GMOCK_PP_COMMA_IF(_i) \
10497 GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
10498 gmock_a##_i
10499
10500 #define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
10501 GMOCK_PP_COMMA_IF(_i) \
10502 ::std::forward<GMOCK_INTERNAL_ARG_O( \
10503 _i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i)
10504
10505 #define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
10506 GMOCK_PP_COMMA_IF(_i) \
10507 GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
10508 gmock_a##_i
10509
10510 #define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \
10511 GMOCK_PP_COMMA_IF(_i) \
10512 gmock_a##_i
10513
10514 #define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
10515 GMOCK_PP_COMMA_IF(_i) \
10516 ::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>()
10517
10518 #define GMOCK_INTERNAL_ARG_O(_i, ...) \
10519 typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type
10520
10521 #define GMOCK_INTERNAL_MATCHER_O(_i, ...) \
10522 const ::testing::Matcher<typename ::testing::internal::Function< \
10523 __VA_ARGS__>::template Arg<_i>::type>&
10524
10525 #define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__)
10526 #define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__)
10527 #define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__)
10528 #define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__)
10529 #define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__)
10530 #define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__)
10531 #define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__)
10532 #define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__)
10533 #define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__)
10534 #define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__)
10535 #define MOCK_METHOD10(m, ...) \
10536 GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__)
10537
10538 #define MOCK_CONST_METHOD0(m, ...) \
10539 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__)
10540 #define MOCK_CONST_METHOD1(m, ...) \
10541 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__)
10542 #define MOCK_CONST_METHOD2(m, ...) \
10543 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__)
10544 #define MOCK_CONST_METHOD3(m, ...) \
10545 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__)
10546 #define MOCK_CONST_METHOD4(m, ...) \
10547 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__)
10548 #define MOCK_CONST_METHOD5(m, ...) \
10549 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__)
10550 #define MOCK_CONST_METHOD6(m, ...) \
10551 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__)
10552 #define MOCK_CONST_METHOD7(m, ...) \
10553 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__)
10554 #define MOCK_CONST_METHOD8(m, ...) \
10555 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__)
10556 #define MOCK_CONST_METHOD9(m, ...) \
10557 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__)
10558 #define MOCK_CONST_METHOD10(m, ...) \
10559 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__)
10560
10561 #define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__)
10562 #define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__)
10563 #define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__)
10564 #define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__)
10565 #define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__)
10566 #define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__)
10567 #define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__)
10568 #define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__)
10569 #define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__)
10570 #define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__)
10571 #define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__)
10572
10573 #define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__)
10574 #define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__)
10575 #define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__)
10576 #define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__)
10577 #define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__)
10578 #define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__)
10579 #define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__)
10580 #define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__)
10581 #define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__)
10582 #define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__)
10583 #define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__)
10584
10585 #define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
10586 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__)
10587 #define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
10588 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__)
10589 #define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
10590 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__)
10591 #define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
10592 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__)
10593 #define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
10594 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__)
10595 #define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
10596 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__)
10597 #define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
10598 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__)
10599 #define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
10600 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__)
10601 #define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
10602 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__)
10603 #define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
10604 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__)
10605 #define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
10606 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__)
10607
10608 #define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
10609 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__)
10610 #define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
10611 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__)
10612 #define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
10613 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__)
10614 #define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
10615 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__)
10616 #define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
10617 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__)
10618 #define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
10619 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__)
10620 #define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
10621 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__)
10622 #define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
10623 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__)
10624 #define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
10625 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__)
10626 #define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
10627 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__)
10628 #define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
10629 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__)
10630
10631 #define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
10632 MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10633 #define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
10634 MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10635 #define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
10636 MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10637 #define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
10638 MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10639 #define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
10640 MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10641 #define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
10642 MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10643 #define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
10644 MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10645 #define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
10646 MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10647 #define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
10648 MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10649 #define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
10650 MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10651 #define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
10652 MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10653
10654 #define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
10655 MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10656 #define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
10657 MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10658 #define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
10659 MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10660 #define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
10661 MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10662 #define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
10663 MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10664 #define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
10665 MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10666 #define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
10667 MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10668 #define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
10669 MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10670 #define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
10671 MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10672 #define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
10673 MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10674 #define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
10675 MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10676
10677 #define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \
10678 GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
10679 args_num, ::testing::internal::identity_t<__VA_ARGS__>); \
10680 GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
10681 args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \
10682 (::testing::internal::identity_t<__VA_ARGS__>))
10683
10684 #define GMOCK_MOCKER_(arity, constness, Method) \
10685 GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
10686
10687 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_
10688 // Copyright 2007, Google Inc.
10689 // All rights reserved.
10690 //
10691 // Redistribution and use in source and binary forms, with or without
10692 // modification, are permitted provided that the following conditions are
10693 // met:
10694 //
10695 // * Redistributions of source code must retain the above copyright
10696 // notice, this list of conditions and the following disclaimer.
10697 // * Redistributions in binary form must reproduce the above
10698 // copyright notice, this list of conditions and the following disclaimer
10699 // in the documentation and/or other materials provided with the
10700 // distribution.
10701 // * Neither the name of Google Inc. nor the names of its
10702 // contributors may be used to endorse or promote products derived from
10703 // this software without specific prior written permission.
10704 //
10705 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10706 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10707 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10708 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10709 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10710 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10711 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10712 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10713 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10714 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10715 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10716
10717
10718 // Google Mock - a framework for writing C++ mock classes.
10719 //
10720 // This file implements some commonly used variadic actions.
10721
10722 // GOOGLETEST_CM0002 DO NOT DELETE
10723
10724 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
10725 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
10726
10727 #include <memory>
10728 #include <utility>
10729
10730
10731 // Include any custom callback actions added by the local installation.
10732 // GOOGLETEST_CM0002 DO NOT DELETE
10733
10734 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
10735 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
10736
10737 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
10738
10739 // Sometimes you want to give an action explicit template parameters
10740 // that cannot be inferred from its value parameters. ACTION() and
10741 // ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that
10742 // and can be viewed as an extension to ACTION() and ACTION_P*().
10743 //
10744 // The syntax:
10745 //
10746 // ACTION_TEMPLATE(ActionName,
10747 // HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
10748 // AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
10749 //
10750 // defines an action template that takes m explicit template
10751 // parameters and n value parameters. name_i is the name of the i-th
10752 // template parameter, and kind_i specifies whether it's a typename,
10753 // an integral constant, or a template. p_i is the name of the i-th
10754 // value parameter.
10755 //
10756 // Example:
10757 //
10758 // // DuplicateArg<k, T>(output) converts the k-th argument of the mock
10759 // // function to type T and copies it to *output.
10760 // ACTION_TEMPLATE(DuplicateArg,
10761 // HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
10762 // AND_1_VALUE_PARAMS(output)) {
10763 // *output = T(::std::get<k>(args));
10764 // }
10765 // ...
10766 // int n;
10767 // EXPECT_CALL(mock, Foo(_, _))
10768 // .WillOnce(DuplicateArg<1, unsigned char>(&n));
10769 //
10770 // To create an instance of an action template, write:
10771 //
10772 // ActionName<t1, ..., t_m>(v1, ..., v_n)
10773 //
10774 // where the ts are the template arguments and the vs are the value
10775 // arguments. The value argument types are inferred by the compiler.
10776 // If you want to explicitly specify the value argument types, you can
10777 // provide additional template arguments:
10778 //
10779 // ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
10780 //
10781 // where u_i is the desired type of v_i.
10782 //
10783 // ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
10784 // number of value parameters, but not on the number of template
10785 // parameters. Without the restriction, the meaning of the following
10786 // is unclear:
10787 //
10788 // OverloadedAction<int, bool>(x);
10789 //
10790 // Are we using a single-template-parameter action where 'bool' refers
10791 // to the type of x, or are we using a two-template-parameter action
10792 // where the compiler is asked to infer the type of x?
10793 //
10794 // Implementation notes:
10795 //
10796 // GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
10797 // GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
10798 // implementing ACTION_TEMPLATE. The main trick we use is to create
10799 // new macro invocations when expanding a macro. For example, we have
10800 //
10801 // #define ACTION_TEMPLATE(name, template_params, value_params)
10802 // ... GMOCK_INTERNAL_DECL_##template_params ...
10803 //
10804 // which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
10805 // to expand to
10806 //
10807 // ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
10808 //
10809 // Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
10810 // preprocessor will continue to expand it to
10811 //
10812 // ... typename T ...
10813 //
10814 // This technique conforms to the C++ standard and is portable. It
10815 // allows us to implement action templates using O(N) code, where N is
10816 // the maximum number of template/value parameters supported. Without
10817 // using it, we'd have to devote O(N^2) amount of code to implement all
10818 // combinations of m and n.
10819
10820 // Declares the template parameters.
10821 #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
10822 #define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
10823 name1) kind0 name0, kind1 name1
10824 #define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10825 kind2, name2) kind0 name0, kind1 name1, kind2 name2
10826 #define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10827 kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
10828 kind3 name3
10829 #define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10830 kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
10831 kind2 name2, kind3 name3, kind4 name4
10832 #define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10833 kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
10834 kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
10835 #define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10836 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10837 name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
10838 kind5 name5, kind6 name6
10839 #define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10840 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10841 kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
10842 kind4 name4, kind5 name5, kind6 name6, kind7 name7
10843 #define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10844 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10845 kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
10846 kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
10847 kind8 name8
10848 #define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
10849 name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10850 name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
10851 kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
10852 kind6 name6, kind7 name7, kind8 name8, kind9 name9
10853
10854 // Lists the template parameters.
10855 #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
10856 #define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
10857 name1) name0, name1
10858 #define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10859 kind2, name2) name0, name1, name2
10860 #define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10861 kind2, name2, kind3, name3) name0, name1, name2, name3
10862 #define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10863 kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
10864 name4
10865 #define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10866 kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
10867 name2, name3, name4, name5
10868 #define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10869 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10870 name6) name0, name1, name2, name3, name4, name5, name6
10871 #define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10872 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10873 kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
10874 #define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10875 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10876 kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
10877 name6, name7, name8
10878 #define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
10879 name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10880 name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
10881 name3, name4, name5, name6, name7, name8, name9
10882
10883 // Declares the types of value parameters.
10884 #define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
10885 #define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
10886 #define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \
10887 typename p0##_type, typename p1##_type
10888 #define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \
10889 typename p0##_type, typename p1##_type, typename p2##_type
10890 #define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
10891 typename p0##_type, typename p1##_type, typename p2##_type, \
10892 typename p3##_type
10893 #define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
10894 typename p0##_type, typename p1##_type, typename p2##_type, \
10895 typename p3##_type, typename p4##_type
10896 #define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
10897 typename p0##_type, typename p1##_type, typename p2##_type, \
10898 typename p3##_type, typename p4##_type, typename p5##_type
10899 #define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10900 p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
10901 typename p3##_type, typename p4##_type, typename p5##_type, \
10902 typename p6##_type
10903 #define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10904 p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
10905 typename p3##_type, typename p4##_type, typename p5##_type, \
10906 typename p6##_type, typename p7##_type
10907 #define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10908 p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
10909 typename p3##_type, typename p4##_type, typename p5##_type, \
10910 typename p6##_type, typename p7##_type, typename p8##_type
10911 #define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10912 p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
10913 typename p2##_type, typename p3##_type, typename p4##_type, \
10914 typename p5##_type, typename p6##_type, typename p7##_type, \
10915 typename p8##_type, typename p9##_type
10916
10917 // Initializes the value parameters.
10918 #define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
10919 ()
10920 #define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
10921 (p0##_type gmock_p0) : p0(::std::move(gmock_p0))
10922 #define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
10923 (p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
10924 p1(::std::move(gmock_p1))
10925 #define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
10926 (p0##_type gmock_p0, p1##_type gmock_p1, \
10927 p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \
10928 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2))
10929 #define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
10930 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10931 p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \
10932 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10933 p3(::std::move(gmock_p3))
10934 #define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
10935 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10936 p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \
10937 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10938 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4))
10939 #define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
10940 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10941 p3##_type gmock_p3, p4##_type gmock_p4, \
10942 p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \
10943 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10944 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10945 p5(::std::move(gmock_p5))
10946 #define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
10947 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10948 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10949 p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \
10950 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10951 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10952 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6))
10953 #define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
10954 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10955 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10956 p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \
10957 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10958 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10959 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
10960 p7(::std::move(gmock_p7))
10961 #define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
10962 p7, p8)\
10963 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10964 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10965 p6##_type gmock_p6, p7##_type gmock_p7, \
10966 p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \
10967 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10968 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10969 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
10970 p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8))
10971 #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
10972 p7, p8, p9)\
10973 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10974 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10975 p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
10976 p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \
10977 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10978 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10979 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
10980 p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \
10981 p9(::std::move(gmock_p9))
10982
10983 // Defines the copy constructor
10984 #define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \
10985 {} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134
10986 #define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default;
10987 #define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default;
10988 #define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default;
10989 #define GMOCK_INTERNAL_DEFN_COPY_AND_4_VALUE_PARAMS(...) = default;
10990 #define GMOCK_INTERNAL_DEFN_COPY_AND_5_VALUE_PARAMS(...) = default;
10991 #define GMOCK_INTERNAL_DEFN_COPY_AND_6_VALUE_PARAMS(...) = default;
10992 #define GMOCK_INTERNAL_DEFN_COPY_AND_7_VALUE_PARAMS(...) = default;
10993 #define GMOCK_INTERNAL_DEFN_COPY_AND_8_VALUE_PARAMS(...) = default;
10994 #define GMOCK_INTERNAL_DEFN_COPY_AND_9_VALUE_PARAMS(...) = default;
10995 #define GMOCK_INTERNAL_DEFN_COPY_AND_10_VALUE_PARAMS(...) = default;
10996
10997 // Declares the fields for storing the value parameters.
10998 #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
10999 #define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
11000 #define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
11001 p1##_type p1;
11002 #define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
11003 p1##_type p1; p2##_type p2;
11004 #define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
11005 p1##_type p1; p2##_type p2; p3##_type p3;
11006 #define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
11007 p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
11008 #define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
11009 p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
11010 p5##_type p5;
11011 #define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11012 p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
11013 p5##_type p5; p6##_type p6;
11014 #define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11015 p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
11016 p5##_type p5; p6##_type p6; p7##_type p7;
11017 #define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11018 p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
11019 p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
11020 #define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11021 p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
11022 p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
11023 p9##_type p9;
11024
11025 // Lists the value parameters.
11026 #define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
11027 #define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0
11028 #define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
11029 #define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
11030 #define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
11031 #define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
11032 p2, p3, p4
11033 #define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
11034 p1, p2, p3, p4, p5
11035 #define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11036 p6) p0, p1, p2, p3, p4, p5, p6
11037 #define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11038 p7) p0, p1, p2, p3, p4, p5, p6, p7
11039 #define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11040 p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
11041 #define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11042 p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
11043
11044 // Lists the value parameter types.
11045 #define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
11046 #define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
11047 #define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
11048 p1##_type
11049 #define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
11050 p1##_type, p2##_type
11051 #define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
11052 p0##_type, p1##_type, p2##_type, p3##_type
11053 #define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
11054 p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
11055 #define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
11056 p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
11057 #define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11058 p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
11059 p6##_type
11060 #define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11061 p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
11062 p5##_type, p6##_type, p7##_type
11063 #define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11064 p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
11065 p5##_type, p6##_type, p7##_type, p8##_type
11066 #define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11067 p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
11068 p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
11069
11070 // Declares the value parameters.
11071 #define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
11072 #define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
11073 #define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
11074 p1##_type p1
11075 #define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
11076 p1##_type p1, p2##_type p2
11077 #define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
11078 p1##_type p1, p2##_type p2, p3##_type p3
11079 #define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
11080 p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
11081 #define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
11082 p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
11083 p5##_type p5
11084 #define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11085 p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
11086 p5##_type p5, p6##_type p6
11087 #define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11088 p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
11089 p5##_type p5, p6##_type p6, p7##_type p7
11090 #define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11091 p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
11092 p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
11093 #define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11094 p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
11095 p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
11096 p9##_type p9
11097
11098 // The suffix of the class template implementing the action template.
11099 #define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
11100 #define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P
11101 #define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2
11102 #define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3
11103 #define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4
11104 #define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5
11105 #define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
11106 #define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
11107 #define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11108 p7) P8
11109 #define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11110 p7, p8) P9
11111 #define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11112 p7, p8, p9) P10
11113
11114 // The name of the class template implementing the action template.
11115 #define GMOCK_ACTION_CLASS_(name, value_params)\
11116 GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
11117
11118 #define ACTION_TEMPLATE(name, template_params, value_params) \
11119 template <GMOCK_INTERNAL_DECL_##template_params \
11120 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11121 class GMOCK_ACTION_CLASS_(name, value_params) { \
11122 public: \
11123 explicit GMOCK_ACTION_CLASS_(name, value_params)( \
11124 GMOCK_INTERNAL_DECL_##value_params) \
11125 GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
11126 = default; , \
11127 : impl_(std::make_shared<gmock_Impl>( \
11128 GMOCK_INTERNAL_LIST_##value_params)) { }) \
11129 GMOCK_ACTION_CLASS_(name, value_params)( \
11130 const GMOCK_ACTION_CLASS_(name, value_params)&) noexcept \
11131 GMOCK_INTERNAL_DEFN_COPY_##value_params \
11132 GMOCK_ACTION_CLASS_(name, value_params)( \
11133 GMOCK_ACTION_CLASS_(name, value_params)&&) noexcept \
11134 GMOCK_INTERNAL_DEFN_COPY_##value_params \
11135 template <typename F> \
11136 operator ::testing::Action<F>() const { \
11137 return GMOCK_PP_IF( \
11138 GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
11139 (::testing::internal::MakeAction<F, gmock_Impl>()), \
11140 (::testing::internal::MakeAction<F>(impl_))); \
11141 } \
11142 private: \
11143 class gmock_Impl { \
11144 public: \
11145 explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {} \
11146 template <typename function_type, typename return_type, \
11147 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
11148 return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
11149 GMOCK_INTERNAL_DEFN_##value_params \
11150 }; \
11151 GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
11152 , std::shared_ptr<const gmock_Impl> impl_;) \
11153 }; \
11154 template <GMOCK_INTERNAL_DECL_##template_params \
11155 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11156 GMOCK_ACTION_CLASS_(name, value_params)< \
11157 GMOCK_INTERNAL_LIST_##template_params \
11158 GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
11159 GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
11160 template <GMOCK_INTERNAL_DECL_##template_params \
11161 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11162 inline GMOCK_ACTION_CLASS_(name, value_params)< \
11163 GMOCK_INTERNAL_LIST_##template_params \
11164 GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
11165 GMOCK_INTERNAL_DECL_##value_params) { \
11166 return GMOCK_ACTION_CLASS_(name, value_params)< \
11167 GMOCK_INTERNAL_LIST_##template_params \
11168 GMOCK_INTERNAL_LIST_TYPE_##value_params>( \
11169 GMOCK_INTERNAL_LIST_##value_params); \
11170 } \
11171 template <GMOCK_INTERNAL_DECL_##template_params \
11172 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11173 template <typename function_type, typename return_type, typename args_type, \
11174 GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
11175 return_type GMOCK_ACTION_CLASS_(name, value_params)< \
11176 GMOCK_INTERNAL_LIST_##template_params \
11177 GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \
11178 GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
11179
11180 namespace testing {
11181
11182 // The ACTION*() macros trigger warning C4100 (unreferenced formal
11183 // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
11184 // the macro definition, as the warnings are generated when the macro
11185 // is expanded and macro expansion cannot contain #pragma. Therefore
11186 // we suppress them here.
11187 #ifdef _MSC_VER
11188 # pragma warning(push)
11189 # pragma warning(disable:4100)
11190 #endif
11191
11192 namespace internal {
11193
11194 // internal::InvokeArgument - a helper for InvokeArgument action.
11195 // The basic overloads are provided here for generic functors.
11196 // Overloads for other custom-callables are provided in the
11197 // internal/custom/gmock-generated-actions.h header.
11198 template <typename F, typename... Args>
11199 auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) {
11200 return f(args...);
11201 }
11202
11203 template <std::size_t index, typename... Params>
11204 struct InvokeArgumentAction {
11205 template <typename... Args>
11206 auto operator()(Args&&... args) const -> decltype(internal::InvokeArgument(
11207 std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
11208 std::declval<const Params&>()...)) {
11209 internal::FlatTuple<Args&&...> args_tuple(FlatTupleConstructTag{},
11210 std::forward<Args>(args)...);
11211 return params.Apply([&](const Params&... unpacked_params) {
11212 auto&& callable = args_tuple.template Get<index>();
11213 return internal::InvokeArgument(
11214 std::forward<decltype(callable)>(callable), unpacked_params...);
11215 });
11216 }
11217
11218 internal::FlatTuple<Params...> params;
11219 };
11220
11221 } // namespace internal
11222
11223 // The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
11224 // (0-based) argument, which must be a k-ary callable, of the mock
11225 // function, with arguments a1, a2, ..., a_k.
11226 //
11227 // Notes:
11228 //
11229 // 1. The arguments are passed by value by default. If you need to
11230 // pass an argument by reference, wrap it inside std::ref(). For
11231 // example,
11232 //
11233 // InvokeArgument<1>(5, string("Hello"), std::ref(foo))
11234 //
11235 // passes 5 and string("Hello") by value, and passes foo by
11236 // reference.
11237 //
11238 // 2. If the callable takes an argument by reference but std::ref() is
11239 // not used, it will receive the reference to a copy of the value,
11240 // instead of the original value. For example, when the 0-th
11241 // argument of the mock function takes a const string&, the action
11242 //
11243 // InvokeArgument<0>(string("Hello"))
11244 //
11245 // makes a copy of the temporary string("Hello") object and passes a
11246 // reference of the copy, instead of the original temporary object,
11247 // to the callable. This makes it easy for a user to define an
11248 // InvokeArgument action from temporary values and have it performed
11249 // later.
11250 template <std::size_t index, typename... Params>
11251 internal::InvokeArgumentAction<index, typename std::decay<Params>::type...>
11252 InvokeArgument(Params&&... params) {
11253 return {internal::FlatTuple<typename std::decay<Params>::type...>(
11254 internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)};
11255 }
11256
11257 #ifdef _MSC_VER
11258 # pragma warning(pop)
11259 #endif
11260
11261 } // namespace testing
11262
11263 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
11264 // Copyright 2013, Google Inc.
11265 // All rights reserved.
11266 //
11267 // Redistribution and use in source and binary forms, with or without
11268 // modification, are permitted provided that the following conditions are
11269 // met:
11270 //
11271 // * Redistributions of source code must retain the above copyright
11272 // notice, this list of conditions and the following disclaimer.
11273 // * Redistributions in binary form must reproduce the above
11274 // copyright notice, this list of conditions and the following disclaimer
11275 // in the documentation and/or other materials provided with the
11276 // distribution.
11277 // * Neither the name of Google Inc. nor the names of its
11278 // contributors may be used to endorse or promote products derived from
11279 // this software without specific prior written permission.
11280 //
11281 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11282 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11283 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11284 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11285 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11286 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11287 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11288 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11289 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11290 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11291 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11292
11293
11294 // Google Mock - a framework for writing C++ mock classes.
11295 //
11296 // This file implements some matchers that depend on gmock-matchers.h.
11297 //
11298 // Note that tests are implemented in gmock-matchers_test.cc rather than
11299 // gmock-more-matchers-test.cc.
11300
11301 // GOOGLETEST_CM0002 DO NOT DELETE
11302
11303 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
11304 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
11305
11306
11307 namespace testing {
11308
11309 // Silence C4100 (unreferenced formal
11310 // parameter) for MSVC
11311 #ifdef _MSC_VER
11312 # pragma warning(push)
11313 # pragma warning(disable:4100)
11314 #if (_MSC_VER == 1900)
11315 // and silence C4800 (C4800: 'int *const ': forcing value
11316 // to bool 'true' or 'false') for MSVC 14
11317 # pragma warning(disable:4800)
11318 #endif
11319 #endif
11320
11321 // Defines a matcher that matches an empty container. The container must
11322 // support both size() and empty(), which all STL-like containers provide.
11323 MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") {
11324 if (arg.empty()) {
11325 return true;
11326 }
11327 *result_listener << "whose size is " << arg.size();
11328 return false;
11329 }
11330
11331 // Define a matcher that matches a value that evaluates in boolean
11332 // context to true. Useful for types that define "explicit operator
11333 // bool" operators and so can't be compared for equality with true
11334 // and false.
11335 MATCHER(IsTrue, negation ? "is false" : "is true") {
11336 return static_cast<bool>(arg);
11337 }
11338
11339 // Define a matcher that matches a value that evaluates in boolean
11340 // context to false. Useful for types that define "explicit operator
11341 // bool" operators and so can't be compared for equality with true
11342 // and false.
11343 MATCHER(IsFalse, negation ? "is true" : "is false") {
11344 return !static_cast<bool>(arg);
11345 }
11346
11347 #ifdef _MSC_VER
11348 # pragma warning(pop)
11349 #endif
11350
11351
11352 } // namespace testing
11353
11354 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
11355 // Copyright 2008, Google Inc.
11356 // All rights reserved.
11357 //
11358 // Redistribution and use in source and binary forms, with or without
11359 // modification, are permitted provided that the following conditions are
11360 // met:
11361 //
11362 // * Redistributions of source code must retain the above copyright
11363 // notice, this list of conditions and the following disclaimer.
11364 // * Redistributions in binary form must reproduce the above
11365 // copyright notice, this list of conditions and the following disclaimer
11366 // in the documentation and/or other materials provided with the
11367 // distribution.
11368 // * Neither the name of Google Inc. nor the names of its
11369 // contributors may be used to endorse or promote products derived from
11370 // this software without specific prior written permission.
11371 //
11372 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11373 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11374 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11375 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11376 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11377 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11378 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11379 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11380 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11381 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11382 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11383
11384
11385 // Implements class templates NiceMock, NaggyMock, and StrictMock.
11386 //
11387 // Given a mock class MockFoo that is created using Google Mock,
11388 // NiceMock<MockFoo> is a subclass of MockFoo that allows
11389 // uninteresting calls (i.e. calls to mock methods that have no
11390 // EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo
11391 // that prints a warning when an uninteresting call occurs, and
11392 // StrictMock<MockFoo> is a subclass of MockFoo that treats all
11393 // uninteresting calls as errors.
11394 //
11395 // Currently a mock is naggy by default, so MockFoo and
11396 // NaggyMock<MockFoo> behave like the same. However, we will soon
11397 // switch the default behavior of mocks to be nice, as that in general
11398 // leads to more maintainable tests. When that happens, MockFoo will
11399 // stop behaving like NaggyMock<MockFoo> and start behaving like
11400 // NiceMock<MockFoo>.
11401 //
11402 // NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
11403 // their respective base class. Therefore you can write
11404 // NiceMock<MockFoo>(5, "a") to construct a nice mock where MockFoo
11405 // has a constructor that accepts (int, const char*), for example.
11406 //
11407 // A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,
11408 // and StrictMock<MockFoo> only works for mock methods defined using
11409 // the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class.
11410 // If a mock method is defined in a base class of MockFoo, the "nice"
11411 // or "strict" modifier may not affect it, depending on the compiler.
11412 // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
11413 // supported.
11414
11415 // GOOGLETEST_CM0002 DO NOT DELETE
11416
11417 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
11418 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
11419
11420 #include <type_traits>
11421
11422
11423 namespace testing {
11424 template <class MockClass>
11425 class NiceMock;
11426 template <class MockClass>
11427 class NaggyMock;
11428 template <class MockClass>
11429 class StrictMock;
11430
11431 namespace internal {
11432 template <typename T>
11433 std::true_type StrictnessModifierProbe(const NiceMock<T>&);
11434 template <typename T>
11435 std::true_type StrictnessModifierProbe(const NaggyMock<T>&);
11436 template <typename T>
11437 std::true_type StrictnessModifierProbe(const StrictMock<T>&);
11438 std::false_type StrictnessModifierProbe(...);
11439
11440 template <typename T>
11441 constexpr bool HasStrictnessModifier() {
11442 return decltype(StrictnessModifierProbe(std::declval<const T&>()))::value;
11443 }
11444
11445 // Base classes that register and deregister with testing::Mock to alter the
11446 // default behavior around uninteresting calls. Inheriting from one of these
11447 // classes first and then MockClass ensures the MockClass constructor is run
11448 // after registration, and that the MockClass destructor runs before
11449 // deregistration. This guarantees that MockClass's constructor and destructor
11450 // run with the same level of strictness as its instance methods.
11451
11452 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \
11453 (defined(_MSC_VER) || defined(__clang__))
11454 // We need to mark these classes with this declspec to ensure that
11455 // the empty base class optimization is performed.
11456 #define GTEST_INTERNAL_EMPTY_BASE_CLASS __declspec(empty_bases)
11457 #else
11458 #define GTEST_INTERNAL_EMPTY_BASE_CLASS
11459 #endif
11460
11461 template <typename Base>
11462 class NiceMockImpl {
11463 public:
11464 NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(this); }
11465
11466 ~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
11467 };
11468
11469 template <typename Base>
11470 class NaggyMockImpl {
11471 public:
11472 NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(this); }
11473
11474 ~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
11475 };
11476
11477 template <typename Base>
11478 class StrictMockImpl {
11479 public:
11480 StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(this); }
11481
11482 ~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
11483 };
11484
11485 } // namespace internal
11486
11487 template <class MockClass>
11488 class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
11489 : private internal::NiceMockImpl<MockClass>,
11490 public MockClass {
11491 public:
11492 static_assert(!internal::HasStrictnessModifier<MockClass>(),
11493 "Can't apply NiceMock to a class hierarchy that already has a "
11494 "strictness modifier. See "
11495 "https://google.github.io/googletest/"
11496 "gmock_cook_book.html#NiceStrictNaggy");
11497 NiceMock() : MockClass() {
11498 static_assert(sizeof(*this) == sizeof(MockClass),
11499 "The impl subclass shouldn't introduce any padding");
11500 }
11501
11502 // Ideally, we would inherit base class's constructors through a using
11503 // declaration, which would preserve their visibility. However, many existing
11504 // tests rely on the fact that current implementation reexports protected
11505 // constructors as public. These tests would need to be cleaned up first.
11506
11507 // Single argument constructor is special-cased so that it can be
11508 // made explicit.
11509 template <typename A>
11510 explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) {
11511 static_assert(sizeof(*this) == sizeof(MockClass),
11512 "The impl subclass shouldn't introduce any padding");
11513 }
11514
11515 template <typename TArg1, typename TArg2, typename... An>
11516 NiceMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
11517 : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
11518 std::forward<An>(args)...) {
11519 static_assert(sizeof(*this) == sizeof(MockClass),
11520 "The impl subclass shouldn't introduce any padding");
11521 }
11522
11523 private:
11524 GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
11525 };
11526
11527 template <class MockClass>
11528 class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
11529 : private internal::NaggyMockImpl<MockClass>,
11530 public MockClass {
11531 static_assert(!internal::HasStrictnessModifier<MockClass>(),
11532 "Can't apply NaggyMock to a class hierarchy that already has a "
11533 "strictness modifier. See "
11534 "https://google.github.io/googletest/"
11535 "gmock_cook_book.html#NiceStrictNaggy");
11536
11537 public:
11538 NaggyMock() : MockClass() {
11539 static_assert(sizeof(*this) == sizeof(MockClass),
11540 "The impl subclass shouldn't introduce any padding");
11541 }
11542
11543 // Ideally, we would inherit base class's constructors through a using
11544 // declaration, which would preserve their visibility. However, many existing
11545 // tests rely on the fact that current implementation reexports protected
11546 // constructors as public. These tests would need to be cleaned up first.
11547
11548 // Single argument constructor is special-cased so that it can be
11549 // made explicit.
11550 template <typename A>
11551 explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) {
11552 static_assert(sizeof(*this) == sizeof(MockClass),
11553 "The impl subclass shouldn't introduce any padding");
11554 }
11555
11556 template <typename TArg1, typename TArg2, typename... An>
11557 NaggyMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
11558 : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
11559 std::forward<An>(args)...) {
11560 static_assert(sizeof(*this) == sizeof(MockClass),
11561 "The impl subclass shouldn't introduce any padding");
11562 }
11563
11564 private:
11565 GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock);
11566 };
11567
11568 template <class MockClass>
11569 class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
11570 : private internal::StrictMockImpl<MockClass>,
11571 public MockClass {
11572 public:
11573 static_assert(
11574 !internal::HasStrictnessModifier<MockClass>(),
11575 "Can't apply StrictMock to a class hierarchy that already has a "
11576 "strictness modifier. See "
11577 "https://google.github.io/googletest/"
11578 "gmock_cook_book.html#NiceStrictNaggy");
11579 StrictMock() : MockClass() {
11580 static_assert(sizeof(*this) == sizeof(MockClass),
11581 "The impl subclass shouldn't introduce any padding");
11582 }
11583
11584 // Ideally, we would inherit base class's constructors through a using
11585 // declaration, which would preserve their visibility. However, many existing
11586 // tests rely on the fact that current implementation reexports protected
11587 // constructors as public. These tests would need to be cleaned up first.
11588
11589 // Single argument constructor is special-cased so that it can be
11590 // made explicit.
11591 template <typename A>
11592 explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) {
11593 static_assert(sizeof(*this) == sizeof(MockClass),
11594 "The impl subclass shouldn't introduce any padding");
11595 }
11596
11597 template <typename TArg1, typename TArg2, typename... An>
11598 StrictMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
11599 : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
11600 std::forward<An>(args)...) {
11601 static_assert(sizeof(*this) == sizeof(MockClass),
11602 "The impl subclass shouldn't introduce any padding");
11603 }
11604
11605 private:
11606 GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
11607 };
11608
11609 #undef GTEST_INTERNAL_EMPTY_BASE_CLASS
11610
11611 } // namespace testing
11612
11613 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
11614
11615 namespace testing {
11616
11617 // Declares Google Mock flags that we want a user to use programmatically.
11618 GMOCK_DECLARE_bool_(catch_leaked_mocks);
11619 GMOCK_DECLARE_string_(verbose);
11620 GMOCK_DECLARE_int32_(default_mock_behavior);
11621
11622 // Initializes Google Mock. This must be called before running the
11623 // tests. In particular, it parses the command line for the flags
11624 // that Google Mock recognizes. Whenever a Google Mock flag is seen,
11625 // it is removed from argv, and *argc is decremented.
11626 //
11627 // No value is returned. Instead, the Google Mock flag variables are
11628 // updated.
11629 //
11630 // Since Google Test is needed for Google Mock to work, this function
11631 // also initializes Google Test and parses its flags, if that hasn't
11632 // been done.
11633 GTEST_API_ void InitGoogleMock(int* argc, char** argv);
11634
11635 // This overloaded version can be used in Windows programs compiled in
11636 // UNICODE mode.
11637 GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv);
11638
11639 // This overloaded version can be used on Arduino/embedded platforms where
11640 // there is no argc/argv.
11641 GTEST_API_ void InitGoogleMock();
11642
11643 } // namespace testing
11644
11645 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_