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>
GetRawPointer(const Pointer & p)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>
GetRawPointer(Element * p)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
~FailureReporterInterface()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.
Assert(bool condition,const char * file,int line,const std::string & msg)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 }
Assert(bool condition,const char * file,int line)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.
Expect(bool condition,const char * file,int line,const std::string & msg)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 }
Expect(bool condition,const char * file,int line)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:
WithoutMatchers()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>
Invalid()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
ConstReference(const RawContainer & container)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 }
Copy(const RawContainer & container)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
ConstReference(const Element (& array)[N])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 }
Copy(const Element (& array)[N])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
ConstReference(const::std::tuple<ElementPointer,Size> & array)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 }
Copy(const::std::tuple<ElementPointer,Size> & array)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 <cstdint>
2864 #include <functional>
2865 #include <map>
2866 #include <memory>
2867 #include <set>
2868 #include <sstream>
2869 #include <string>
2870 #include <type_traits>
2871 #include <utility>
2872 #include <vector>
2873 // Copyright 2007, Google Inc.
2874 // All rights reserved.
2875 //
2876 // Redistribution and use in source and binary forms, with or without
2877 // modification, are permitted provided that the following conditions are
2878 // met:
2879 //
2880 // * Redistributions of source code must retain the above copyright
2881 // notice, this list of conditions and the following disclaimer.
2882 // * Redistributions in binary form must reproduce the above
2883 // copyright notice, this list of conditions and the following disclaimer
2884 // in the documentation and/or other materials provided with the
2885 // distribution.
2886 // * Neither the name of Google Inc. nor the names of its
2887 // contributors may be used to endorse or promote products derived from
2888 // this software without specific prior written permission.
2889 //
2890 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2891 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2892 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2893 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2894 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2895 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2896 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2897 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2898 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2899 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2900 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2901
2902
2903 // Google Mock - a framework for writing C++ mock classes.
2904 //
2905 // The MATCHER* family of macros can be used in a namespace scope to
2906 // define custom matchers easily.
2907 //
2908 // Basic Usage
2909 // ===========
2910 //
2911 // The syntax
2912 //
2913 // MATCHER(name, description_string) { statements; }
2914 //
2915 // defines a matcher with the given name that executes the statements,
2916 // which must return a bool to indicate if the match succeeds. Inside
2917 // the statements, you can refer to the value being matched by 'arg',
2918 // and refer to its type by 'arg_type'.
2919 //
2920 // The description string documents what the matcher does, and is used
2921 // to generate the failure message when the match fails. Since a
2922 // MATCHER() is usually defined in a header file shared by multiple
2923 // C++ source files, we require the description to be a C-string
2924 // literal to avoid possible side effects. It can be empty, in which
2925 // case we'll use the sequence of words in the matcher name as the
2926 // description.
2927 //
2928 // For example:
2929 //
2930 // MATCHER(IsEven, "") { return (arg % 2) == 0; }
2931 //
2932 // allows you to write
2933 //
2934 // // Expects mock_foo.Bar(n) to be called where n is even.
2935 // EXPECT_CALL(mock_foo, Bar(IsEven()));
2936 //
2937 // or,
2938 //
2939 // // Verifies that the value of some_expression is even.
2940 // EXPECT_THAT(some_expression, IsEven());
2941 //
2942 // If the above assertion fails, it will print something like:
2943 //
2944 // Value of: some_expression
2945 // Expected: is even
2946 // Actual: 7
2947 //
2948 // where the description "is even" is automatically calculated from the
2949 // matcher name IsEven.
2950 //
2951 // Argument Type
2952 // =============
2953 //
2954 // Note that the type of the value being matched (arg_type) is
2955 // determined by the context in which you use the matcher and is
2956 // supplied to you by the compiler, so you don't need to worry about
2957 // declaring it (nor can you). This allows the matcher to be
2958 // polymorphic. For example, IsEven() can be used to match any type
2959 // where the value of "(arg % 2) == 0" can be implicitly converted to
2960 // a bool. In the "Bar(IsEven())" example above, if method Bar()
2961 // takes an int, 'arg_type' will be int; if it takes an unsigned long,
2962 // 'arg_type' will be unsigned long; and so on.
2963 //
2964 // Parameterizing Matchers
2965 // =======================
2966 //
2967 // Sometimes you'll want to parameterize the matcher. For that you
2968 // can use another macro:
2969 //
2970 // MATCHER_P(name, param_name, description_string) { statements; }
2971 //
2972 // For example:
2973 //
2974 // MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
2975 //
2976 // will allow you to write:
2977 //
2978 // EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
2979 //
2980 // which may lead to this message (assuming n is 10):
2981 //
2982 // Value of: Blah("a")
2983 // Expected: has absolute value 10
2984 // Actual: -9
2985 //
2986 // Note that both the matcher description and its parameter are
2987 // printed, making the message human-friendly.
2988 //
2989 // In the matcher definition body, you can write 'foo_type' to
2990 // reference the type of a parameter named 'foo'. For example, in the
2991 // body of MATCHER_P(HasAbsoluteValue, value) above, you can write
2992 // 'value_type' to refer to the type of 'value'.
2993 //
2994 // We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
2995 // support multi-parameter matchers.
2996 //
2997 // Describing Parameterized Matchers
2998 // =================================
2999 //
3000 // The last argument to MATCHER*() is a string-typed expression. The
3001 // expression can reference all of the matcher's parameters and a
3002 // special bool-typed variable named 'negation'. When 'negation' is
3003 // false, the expression should evaluate to the matcher's description;
3004 // otherwise it should evaluate to the description of the negation of
3005 // the matcher. For example,
3006 //
3007 // using testing::PrintToString;
3008 //
3009 // MATCHER_P2(InClosedRange, low, hi,
3010 // std::string(negation ? "is not" : "is") + " in range [" +
3011 // PrintToString(low) + ", " + PrintToString(hi) + "]") {
3012 // return low <= arg && arg <= hi;
3013 // }
3014 // ...
3015 // EXPECT_THAT(3, InClosedRange(4, 6));
3016 // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
3017 //
3018 // would generate two failures that contain the text:
3019 //
3020 // Expected: is in range [4, 6]
3021 // ...
3022 // Expected: is not in range [2, 4]
3023 //
3024 // If you specify "" as the description, the failure message will
3025 // contain the sequence of words in the matcher name followed by the
3026 // parameter values printed as a tuple. For example,
3027 //
3028 // MATCHER_P2(InClosedRange, low, hi, "") { ... }
3029 // ...
3030 // EXPECT_THAT(3, InClosedRange(4, 6));
3031 // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
3032 //
3033 // would generate two failures that contain the text:
3034 //
3035 // Expected: in closed range (4, 6)
3036 // ...
3037 // Expected: not (in closed range (2, 4))
3038 //
3039 // Types of Matcher Parameters
3040 // ===========================
3041 //
3042 // For the purpose of typing, you can view
3043 //
3044 // MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
3045 //
3046 // as shorthand for
3047 //
3048 // template <typename p1_type, ..., typename pk_type>
3049 // FooMatcherPk<p1_type, ..., pk_type>
3050 // Foo(p1_type p1, ..., pk_type pk) { ... }
3051 //
3052 // When you write Foo(v1, ..., vk), the compiler infers the types of
3053 // the parameters v1, ..., and vk for you. If you are not happy with
3054 // the result of the type inference, you can specify the types by
3055 // explicitly instantiating the template, as in Foo<long, bool>(5,
3056 // false). As said earlier, you don't get to (or need to) specify
3057 // 'arg_type' as that's determined by the context in which the matcher
3058 // is used. You can assign the result of expression Foo(p1, ..., pk)
3059 // to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
3060 // can be useful when composing matchers.
3061 //
3062 // While you can instantiate a matcher template with reference types,
3063 // passing the parameters by pointer usually makes your code more
3064 // readable. If, however, you still want to pass a parameter by
3065 // reference, be aware that in the failure message generated by the
3066 // matcher you will see the value of the referenced object but not its
3067 // address.
3068 //
3069 // Explaining Match Results
3070 // ========================
3071 //
3072 // Sometimes the matcher description alone isn't enough to explain why
3073 // the match has failed or succeeded. For example, when expecting a
3074 // long string, it can be very helpful to also print the diff between
3075 // the expected string and the actual one. To achieve that, you can
3076 // optionally stream additional information to a special variable
3077 // named result_listener, whose type is a pointer to class
3078 // MatchResultListener:
3079 //
3080 // MATCHER_P(EqualsLongString, str, "") {
3081 // if (arg == str) return true;
3082 //
3083 // *result_listener << "the difference: "
3084 /// << DiffStrings(str, arg);
3085 // return false;
3086 // }
3087 //
3088 // Overloading Matchers
3089 // ====================
3090 //
3091 // You can overload matchers with different numbers of parameters:
3092 //
3093 // MATCHER_P(Blah, a, description_string1) { ... }
3094 // MATCHER_P2(Blah, a, b, description_string2) { ... }
3095 //
3096 // Caveats
3097 // =======
3098 //
3099 // When defining a new matcher, you should also consider implementing
3100 // MatcherInterface or using MakePolymorphicMatcher(). These
3101 // approaches require more work than the MATCHER* macros, but also
3102 // give you more control on the types of the value being matched and
3103 // the matcher parameters, which may leads to better compiler error
3104 // messages when the matcher is used wrong. They also allow
3105 // overloading matchers based on parameter types (as opposed to just
3106 // based on the number of parameters).
3107 //
3108 // MATCHER*() can only be used in a namespace scope as templates cannot be
3109 // declared inside of a local class.
3110 //
3111 // More Information
3112 // ================
3113 //
3114 // To learn more about using these macros, please search for 'MATCHER'
3115 // on
3116 // https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
3117 //
3118 // This file also implements some commonly used argument matchers. More
3119 // matchers can be defined by the user implementing the
3120 // MatcherInterface<T> interface if necessary.
3121 //
3122 // See googletest/include/gtest/gtest-matchers.h for the definition of class
3123 // Matcher, class MatcherInterface, and others.
3124
3125 // GOOGLETEST_CM0002 DO NOT DELETE
3126
3127 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
3128 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
3129
3130 #include <algorithm>
3131 #include <cmath>
3132 #include <initializer_list>
3133 #include <iterator>
3134 #include <limits>
3135 #include <memory>
3136 #include <ostream> // NOLINT
3137 #include <sstream>
3138 #include <string>
3139 #include <type_traits>
3140 #include <utility>
3141 #include <vector>
3142
3143
3144 // MSVC warning C5046 is new as of VS2017 version 15.8.
3145 #if defined(_MSC_VER) && _MSC_VER >= 1915
3146 #define GMOCK_MAYBE_5046_ 5046
3147 #else
3148 #define GMOCK_MAYBE_5046_
3149 #endif
3150
3151 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
3152 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by
3153 clients of class B */
3154 /* Symbol involving type with internal linkage not defined */)
3155
3156 namespace testing {
3157
3158 // To implement a matcher Foo for type T, define:
3159 // 1. a class FooMatcherImpl that implements the
3160 // MatcherInterface<T> interface, and
3161 // 2. a factory function that creates a Matcher<T> object from a
3162 // FooMatcherImpl*.
3163 //
3164 // The two-level delegation design makes it possible to allow a user
3165 // to write "v" instead of "Eq(v)" where a Matcher is expected, which
3166 // is impossible if we pass matchers by pointers. It also eases
3167 // ownership management as Matcher objects can now be copied like
3168 // plain values.
3169
3170 // A match result listener that stores the explanation in a string.
3171 class StringMatchResultListener : public MatchResultListener {
3172 public:
3173 StringMatchResultListener() : MatchResultListener(&ss_) {}
3174
3175 // Returns the explanation accumulated so far.
3176 std::string str() const { return ss_.str(); }
3177
3178 // Clears the explanation accumulated so far.
3179 void Clear() { ss_.str(""); }
3180
3181 private:
3182 ::std::stringstream ss_;
3183
3184 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
3185 };
3186
3187 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
3188 // and MUST NOT BE USED IN USER CODE!!!
3189 namespace internal {
3190
3191 // The MatcherCastImpl class template is a helper for implementing
3192 // MatcherCast(). We need this helper in order to partially
3193 // specialize the implementation of MatcherCast() (C++ allows
3194 // class/struct templates to be partially specialized, but not
3195 // function templates.).
3196
3197 // This general version is used when MatcherCast()'s argument is a
3198 // polymorphic matcher (i.e. something that can be converted to a
3199 // Matcher but is not one yet; for example, Eq(value)) or a value (for
3200 // example, "hello").
3201 template <typename T, typename M>
3202 class MatcherCastImpl {
3203 public:
3204 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
3205 // M can be a polymorphic matcher, in which case we want to use
3206 // its conversion operator to create Matcher<T>. Or it can be a value
3207 // that should be passed to the Matcher<T>'s constructor.
3208 //
3209 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
3210 // polymorphic matcher because it'll be ambiguous if T has an implicit
3211 // constructor from M (this usually happens when T has an implicit
3212 // constructor from any type).
3213 //
3214 // It won't work to unconditionally implicit_cast
3215 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
3216 // a user-defined conversion from M to T if one exists (assuming M is
3217 // a value).
3218 return CastImpl(polymorphic_matcher_or_value,
3219 std::is_convertible<M, Matcher<T>>{},
3220 std::is_convertible<M, T>{});
3221 }
3222
3223 private:
3224 template <bool Ignore>
3225 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
3226 std::true_type /* convertible_to_matcher */,
3227 std::integral_constant<bool, Ignore>) {
3228 // M is implicitly convertible to Matcher<T>, which means that either
3229 // M is a polymorphic matcher or Matcher<T> has an implicit constructor
3230 // from M. In both cases using the implicit conversion will produce a
3231 // matcher.
3232 //
3233 // Even if T has an implicit constructor from M, it won't be called because
3234 // creating Matcher<T> would require a chain of two user-defined conversions
3235 // (first to create T from M and then to create Matcher<T> from T).
3236 return polymorphic_matcher_or_value;
3237 }
3238
3239 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
3240 // matcher. It's a value of a type implicitly convertible to T. Use direct
3241 // initialization to create a matcher.
3242 static Matcher<T> CastImpl(const M& value,
3243 std::false_type /* convertible_to_matcher */,
3244 std::true_type /* convertible_to_T */) {
3245 return Matcher<T>(ImplicitCast_<T>(value));
3246 }
3247
3248 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
3249 // polymorphic matcher Eq(value) in this case.
3250 //
3251 // Note that we first attempt to perform an implicit cast on the value and
3252 // only fall back to the polymorphic Eq() matcher afterwards because the
3253 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
3254 // which might be undefined even when Rhs is implicitly convertible to Lhs
3255 // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
3256 //
3257 // We don't define this method inline as we need the declaration of Eq().
3258 static Matcher<T> CastImpl(const M& value,
3259 std::false_type /* convertible_to_matcher */,
3260 std::false_type /* convertible_to_T */);
3261 };
3262
3263 // This more specialized version is used when MatcherCast()'s argument
3264 // is already a Matcher. This only compiles when type T can be
3265 // statically converted to type U.
3266 template <typename T, typename U>
3267 class MatcherCastImpl<T, Matcher<U> > {
3268 public:
3269 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
3270 return Matcher<T>(new Impl(source_matcher));
3271 }
3272
3273 private:
3274 class Impl : public MatcherInterface<T> {
3275 public:
3276 explicit Impl(const Matcher<U>& source_matcher)
3277 : source_matcher_(source_matcher) {}
3278
3279 // We delegate the matching logic to the source matcher.
3280 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
3281 using FromType = typename std::remove_cv<typename std::remove_pointer<
3282 typename std::remove_reference<T>::type>::type>::type;
3283 using ToType = typename std::remove_cv<typename std::remove_pointer<
3284 typename std::remove_reference<U>::type>::type>::type;
3285 // Do not allow implicitly converting base*/& to derived*/&.
3286 static_assert(
3287 // Do not trigger if only one of them is a pointer. That implies a
3288 // regular conversion and not a down_cast.
3289 (std::is_pointer<typename std::remove_reference<T>::type>::value !=
3290 std::is_pointer<typename std::remove_reference<U>::type>::value) ||
3291 std::is_same<FromType, ToType>::value ||
3292 !std::is_base_of<FromType, ToType>::value,
3293 "Can't implicitly convert from <base> to <derived>");
3294
3295 // Do the cast to `U` explicitly if necessary.
3296 // Otherwise, let implicit conversions do the trick.
3297 using CastType =
3298 typename std::conditional<std::is_convertible<T&, const U&>::value,
3299 T&, U>::type;
3300
3301 return source_matcher_.MatchAndExplain(static_cast<CastType>(x),
3302 listener);
3303 }
3304
3305 void DescribeTo(::std::ostream* os) const override {
3306 source_matcher_.DescribeTo(os);
3307 }
3308
3309 void DescribeNegationTo(::std::ostream* os) const override {
3310 source_matcher_.DescribeNegationTo(os);
3311 }
3312
3313 private:
3314 const Matcher<U> source_matcher_;
3315 };
3316 };
3317
3318 // This even more specialized version is used for efficiently casting
3319 // a matcher to its own type.
3320 template <typename T>
3321 class MatcherCastImpl<T, Matcher<T> > {
3322 public:
3323 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
3324 };
3325
3326 // Template specialization for parameterless Matcher.
3327 template <typename Derived>
3328 class MatcherBaseImpl {
3329 public:
3330 MatcherBaseImpl() = default;
3331
3332 template <typename T>
3333 operator ::testing::Matcher<T>() const { // NOLINT(runtime/explicit)
3334 return ::testing::Matcher<T>(new
3335 typename Derived::template gmock_Impl<T>());
3336 }
3337 };
3338
3339 // Template specialization for Matcher with parameters.
3340 template <template <typename...> class Derived, typename... Ts>
3341 class MatcherBaseImpl<Derived<Ts...>> {
3342 public:
3343 // Mark the constructor explicit for single argument T to avoid implicit
3344 // conversions.
3345 template <typename E = std::enable_if<sizeof...(Ts) == 1>,
3346 typename E::type* = nullptr>
3347 explicit MatcherBaseImpl(Ts... params)
3348 : params_(std::forward<Ts>(params)...) {}
3349 template <typename E = std::enable_if<sizeof...(Ts) != 1>,
3350 typename = typename E::type>
3351 MatcherBaseImpl(Ts... params) // NOLINT
3352 : params_(std::forward<Ts>(params)...) {}
3353
3354 template <typename F>
3355 operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit)
3356 return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{});
3357 }
3358
3359 private:
3360 template <typename F, std::size_t... tuple_ids>
3361 ::testing::Matcher<F> Apply(IndexSequence<tuple_ids...>) const {
3362 return ::testing::Matcher<F>(
3363 new typename Derived<Ts...>::template gmock_Impl<F>(
3364 std::get<tuple_ids>(params_)...));
3365 }
3366
3367 const std::tuple<Ts...> params_;
3368 };
3369
3370 } // namespace internal
3371
3372 // In order to be safe and clear, casting between different matcher
3373 // types is done explicitly via MatcherCast<T>(m), which takes a
3374 // matcher m and returns a Matcher<T>. It compiles only when T can be
3375 // statically converted to the argument type of m.
3376 template <typename T, typename M>
3377 inline Matcher<T> MatcherCast(const M& matcher) {
3378 return internal::MatcherCastImpl<T, M>::Cast(matcher);
3379 }
3380
3381 // This overload handles polymorphic matchers and values only since
3382 // monomorphic matchers are handled by the next one.
3383 template <typename T, typename M>
3384 inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {
3385 return MatcherCast<T>(polymorphic_matcher_or_value);
3386 }
3387
3388 // This overload handles monomorphic matchers.
3389 //
3390 // In general, if type T can be implicitly converted to type U, we can
3391 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
3392 // contravariant): just keep a copy of the original Matcher<U>, convert the
3393 // argument from type T to U, and then pass it to the underlying Matcher<U>.
3394 // The only exception is when U is a reference and T is not, as the
3395 // underlying Matcher<U> may be interested in the argument's address, which
3396 // is not preserved in the conversion from T to U.
3397 template <typename T, typename U>
3398 inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
3399 // Enforce that T can be implicitly converted to U.
3400 static_assert(std::is_convertible<const T&, const U&>::value,
3401 "T must be implicitly convertible to U");
3402 // Enforce that we are not converting a non-reference type T to a reference
3403 // type U.
3404 GTEST_COMPILE_ASSERT_(
3405 std::is_reference<T>::value || !std::is_reference<U>::value,
3406 cannot_convert_non_reference_arg_to_reference);
3407 // In case both T and U are arithmetic types, enforce that the
3408 // conversion is not lossy.
3409 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
3410 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
3411 constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
3412 constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
3413 GTEST_COMPILE_ASSERT_(
3414 kTIsOther || kUIsOther ||
3415 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
3416 conversion_of_arithmetic_types_must_be_lossless);
3417 return MatcherCast<T>(matcher);
3418 }
3419
3420 // A<T>() returns a matcher that matches any value of type T.
3421 template <typename T>
3422 Matcher<T> A();
3423
3424 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
3425 // and MUST NOT BE USED IN USER CODE!!!
3426 namespace internal {
3427
3428 // If the explanation is not empty, prints it to the ostream.
3429 inline void PrintIfNotEmpty(const std::string& explanation,
3430 ::std::ostream* os) {
3431 if (explanation != "" && os != nullptr) {
3432 *os << ", " << explanation;
3433 }
3434 }
3435
3436 // Returns true if the given type name is easy to read by a human.
3437 // This is used to decide whether printing the type of a value might
3438 // be helpful.
3439 inline bool IsReadableTypeName(const std::string& type_name) {
3440 // We consider a type name readable if it's short or doesn't contain
3441 // a template or function type.
3442 return (type_name.length() <= 20 ||
3443 type_name.find_first_of("<(") == std::string::npos);
3444 }
3445
3446 // Matches the value against the given matcher, prints the value and explains
3447 // the match result to the listener. Returns the match result.
3448 // 'listener' must not be NULL.
3449 // Value cannot be passed by const reference, because some matchers take a
3450 // non-const argument.
3451 template <typename Value, typename T>
3452 bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
3453 MatchResultListener* listener) {
3454 if (!listener->IsInterested()) {
3455 // If the listener is not interested, we do not need to construct the
3456 // inner explanation.
3457 return matcher.Matches(value);
3458 }
3459
3460 StringMatchResultListener inner_listener;
3461 const bool match = matcher.MatchAndExplain(value, &inner_listener);
3462
3463 UniversalPrint(value, listener->stream());
3464 #if GTEST_HAS_RTTI
3465 const std::string& type_name = GetTypeName<Value>();
3466 if (IsReadableTypeName(type_name))
3467 *listener->stream() << " (of type " << type_name << ")";
3468 #endif
3469 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3470
3471 return match;
3472 }
3473
3474 // An internal helper class for doing compile-time loop on a tuple's
3475 // fields.
3476 template <size_t N>
3477 class TuplePrefix {
3478 public:
3479 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
3480 // if and only if the first N fields of matcher_tuple matches
3481 // the first N fields of value_tuple, respectively.
3482 template <typename MatcherTuple, typename ValueTuple>
3483 static bool Matches(const MatcherTuple& matcher_tuple,
3484 const ValueTuple& value_tuple) {
3485 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) &&
3486 std::get<N - 1>(matcher_tuple).Matches(std::get<N - 1>(value_tuple));
3487 }
3488
3489 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
3490 // describes failures in matching the first N fields of matchers
3491 // against the first N fields of values. If there is no failure,
3492 // nothing will be streamed to os.
3493 template <typename MatcherTuple, typename ValueTuple>
3494 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
3495 const ValueTuple& values,
3496 ::std::ostream* os) {
3497 // First, describes failures in the first N - 1 fields.
3498 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
3499
3500 // Then describes the failure (if any) in the (N - 1)-th (0-based)
3501 // field.
3502 typename std::tuple_element<N - 1, MatcherTuple>::type matcher =
3503 std::get<N - 1>(matchers);
3504 typedef typename std::tuple_element<N - 1, ValueTuple>::type Value;
3505 const Value& value = std::get<N - 1>(values);
3506 StringMatchResultListener listener;
3507 if (!matcher.MatchAndExplain(value, &listener)) {
3508 *os << " Expected arg #" << N - 1 << ": ";
3509 std::get<N - 1>(matchers).DescribeTo(os);
3510 *os << "\n Actual: ";
3511 // We remove the reference in type Value to prevent the
3512 // universal printer from printing the address of value, which
3513 // isn't interesting to the user most of the time. The
3514 // matcher's MatchAndExplain() method handles the case when
3515 // the address is interesting.
3516 internal::UniversalPrint(value, os);
3517 PrintIfNotEmpty(listener.str(), os);
3518 *os << "\n";
3519 }
3520 }
3521 };
3522
3523 // The base case.
3524 template <>
3525 class TuplePrefix<0> {
3526 public:
3527 template <typename MatcherTuple, typename ValueTuple>
3528 static bool Matches(const MatcherTuple& /* matcher_tuple */,
3529 const ValueTuple& /* value_tuple */) {
3530 return true;
3531 }
3532
3533 template <typename MatcherTuple, typename ValueTuple>
3534 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
3535 const ValueTuple& /* values */,
3536 ::std::ostream* /* os */) {}
3537 };
3538
3539 // TupleMatches(matcher_tuple, value_tuple) returns true if and only if
3540 // all matchers in matcher_tuple match the corresponding fields in
3541 // value_tuple. It is a compiler error if matcher_tuple and
3542 // value_tuple have different number of fields or incompatible field
3543 // types.
3544 template <typename MatcherTuple, typename ValueTuple>
3545 bool TupleMatches(const MatcherTuple& matcher_tuple,
3546 const ValueTuple& value_tuple) {
3547 // Makes sure that matcher_tuple and value_tuple have the same
3548 // number of fields.
3549 GTEST_COMPILE_ASSERT_(std::tuple_size<MatcherTuple>::value ==
3550 std::tuple_size<ValueTuple>::value,
3551 matcher_and_value_have_different_numbers_of_fields);
3552 return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple,
3553 value_tuple);
3554 }
3555
3556 // Describes failures in matching matchers against values. If there
3557 // is no failure, nothing will be streamed to os.
3558 template <typename MatcherTuple, typename ValueTuple>
3559 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
3560 const ValueTuple& values,
3561 ::std::ostream* os) {
3562 TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
3563 matchers, values, os);
3564 }
3565
3566 // TransformTupleValues and its helper.
3567 //
3568 // TransformTupleValuesHelper hides the internal machinery that
3569 // TransformTupleValues uses to implement a tuple traversal.
3570 template <typename Tuple, typename Func, typename OutIter>
3571 class TransformTupleValuesHelper {
3572 private:
3573 typedef ::std::tuple_size<Tuple> TupleSize;
3574
3575 public:
3576 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
3577 // Returns the final value of 'out' in case the caller needs it.
3578 static OutIter Run(Func f, const Tuple& t, OutIter out) {
3579 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
3580 }
3581
3582 private:
3583 template <typename Tup, size_t kRemainingSize>
3584 struct IterateOverTuple {
3585 OutIter operator() (Func f, const Tup& t, OutIter out) const {
3586 *out++ = f(::std::get<TupleSize::value - kRemainingSize>(t));
3587 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
3588 }
3589 };
3590 template <typename Tup>
3591 struct IterateOverTuple<Tup, 0> {
3592 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
3593 return out;
3594 }
3595 };
3596 };
3597
3598 // Successively invokes 'f(element)' on each element of the tuple 't',
3599 // appending each result to the 'out' iterator. Returns the final value
3600 // of 'out'.
3601 template <typename Tuple, typename Func, typename OutIter>
3602 OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
3603 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
3604 }
3605
3606 // Implements _, a matcher that matches any value of any
3607 // type. This is a polymorphic matcher, so we need a template type
3608 // conversion operator to make it appearing as a Matcher<T> for any
3609 // type T.
3610 class AnythingMatcher {
3611 public:
3612 using is_gtest_matcher = void;
3613
3614 template <typename T>
3615 bool MatchAndExplain(const T& /* x */, std::ostream* /* listener */) const {
3616 return true;
3617 }
3618 void DescribeTo(std::ostream* os) const { *os << "is anything"; }
3619 void DescribeNegationTo(::std::ostream* os) const {
3620 // This is mostly for completeness' sake, as it's not very useful
3621 // to write Not(A<bool>()). However we cannot completely rule out
3622 // such a possibility, and it doesn't hurt to be prepared.
3623 *os << "never matches";
3624 }
3625 };
3626
3627 // Implements the polymorphic IsNull() matcher, which matches any raw or smart
3628 // pointer that is NULL.
3629 class IsNullMatcher {
3630 public:
3631 template <typename Pointer>
3632 bool MatchAndExplain(const Pointer& p,
3633 MatchResultListener* /* listener */) const {
3634 return p == nullptr;
3635 }
3636
3637 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
3638 void DescribeNegationTo(::std::ostream* os) const {
3639 *os << "isn't NULL";
3640 }
3641 };
3642
3643 // Implements the polymorphic NotNull() matcher, which matches any raw or smart
3644 // pointer that is not NULL.
3645 class NotNullMatcher {
3646 public:
3647 template <typename Pointer>
3648 bool MatchAndExplain(const Pointer& p,
3649 MatchResultListener* /* listener */) const {
3650 return p != nullptr;
3651 }
3652
3653 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
3654 void DescribeNegationTo(::std::ostream* os) const {
3655 *os << "is NULL";
3656 }
3657 };
3658
3659 // Ref(variable) matches any argument that is a reference to
3660 // 'variable'. This matcher is polymorphic as it can match any
3661 // super type of the type of 'variable'.
3662 //
3663 // The RefMatcher template class implements Ref(variable). It can
3664 // only be instantiated with a reference type. This prevents a user
3665 // from mistakenly using Ref(x) to match a non-reference function
3666 // argument. For example, the following will righteously cause a
3667 // compiler error:
3668 //
3669 // int n;
3670 // Matcher<int> m1 = Ref(n); // This won't compile.
3671 // Matcher<int&> m2 = Ref(n); // This will compile.
3672 template <typename T>
3673 class RefMatcher;
3674
3675 template <typename T>
3676 class RefMatcher<T&> {
3677 // Google Mock is a generic framework and thus needs to support
3678 // mocking any function types, including those that take non-const
3679 // reference arguments. Therefore the template parameter T (and
3680 // Super below) can be instantiated to either a const type or a
3681 // non-const type.
3682 public:
3683 // RefMatcher() takes a T& instead of const T&, as we want the
3684 // compiler to catch using Ref(const_value) as a matcher for a
3685 // non-const reference.
3686 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
3687
3688 template <typename Super>
3689 operator Matcher<Super&>() const {
3690 // By passing object_ (type T&) to Impl(), which expects a Super&,
3691 // we make sure that Super is a super type of T. In particular,
3692 // this catches using Ref(const_value) as a matcher for a
3693 // non-const reference, as you cannot implicitly convert a const
3694 // reference to a non-const reference.
3695 return MakeMatcher(new Impl<Super>(object_));
3696 }
3697
3698 private:
3699 template <typename Super>
3700 class Impl : public MatcherInterface<Super&> {
3701 public:
3702 explicit Impl(Super& x) : object_(x) {} // NOLINT
3703
3704 // MatchAndExplain() takes a Super& (as opposed to const Super&)
3705 // in order to match the interface MatcherInterface<Super&>.
3706 bool MatchAndExplain(Super& x,
3707 MatchResultListener* listener) const override {
3708 *listener << "which is located @" << static_cast<const void*>(&x);
3709 return &x == &object_;
3710 }
3711
3712 void DescribeTo(::std::ostream* os) const override {
3713 *os << "references the variable ";
3714 UniversalPrinter<Super&>::Print(object_, os);
3715 }
3716
3717 void DescribeNegationTo(::std::ostream* os) const override {
3718 *os << "does not reference the variable ";
3719 UniversalPrinter<Super&>::Print(object_, os);
3720 }
3721
3722 private:
3723 const Super& object_;
3724 };
3725
3726 T& object_;
3727 };
3728
3729 // Polymorphic helper functions for narrow and wide string matchers.
3730 inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
3731 return String::CaseInsensitiveCStringEquals(lhs, rhs);
3732 }
3733
3734 inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
3735 const wchar_t* rhs) {
3736 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
3737 }
3738
3739 // String comparison for narrow or wide strings that can have embedded NUL
3740 // characters.
3741 template <typename StringType>
3742 bool CaseInsensitiveStringEquals(const StringType& s1,
3743 const StringType& s2) {
3744 // Are the heads equal?
3745 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
3746 return false;
3747 }
3748
3749 // Skip the equal heads.
3750 const typename StringType::value_type nul = 0;
3751 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
3752
3753 // Are we at the end of either s1 or s2?
3754 if (i1 == StringType::npos || i2 == StringType::npos) {
3755 return i1 == i2;
3756 }
3757
3758 // Are the tails equal?
3759 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
3760 }
3761
3762 // String matchers.
3763
3764 // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
3765 template <typename StringType>
3766 class StrEqualityMatcher {
3767 public:
3768 StrEqualityMatcher(StringType str, bool expect_eq, bool case_sensitive)
3769 : string_(std::move(str)),
3770 expect_eq_(expect_eq),
3771 case_sensitive_(case_sensitive) {}
3772
3773 #if GTEST_INTERNAL_HAS_STRING_VIEW
3774 bool MatchAndExplain(const internal::StringView& s,
3775 MatchResultListener* listener) const {
3776 // This should fail to compile if StringView is used with wide
3777 // strings.
3778 const StringType& str = std::string(s);
3779 return MatchAndExplain(str, listener);
3780 }
3781 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3782
3783 // Accepts pointer types, particularly:
3784 // const char*
3785 // char*
3786 // const wchar_t*
3787 // wchar_t*
3788 template <typename CharType>
3789 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3790 if (s == nullptr) {
3791 return !expect_eq_;
3792 }
3793 return MatchAndExplain(StringType(s), listener);
3794 }
3795
3796 // Matches anything that can convert to StringType.
3797 //
3798 // This is a template, not just a plain function with const StringType&,
3799 // because StringView has some interfering non-explicit constructors.
3800 template <typename MatcheeStringType>
3801 bool MatchAndExplain(const MatcheeStringType& s,
3802 MatchResultListener* /* listener */) const {
3803 const StringType s2(s);
3804 const bool eq = case_sensitive_ ? s2 == string_ :
3805 CaseInsensitiveStringEquals(s2, string_);
3806 return expect_eq_ == eq;
3807 }
3808
3809 void DescribeTo(::std::ostream* os) const {
3810 DescribeToHelper(expect_eq_, os);
3811 }
3812
3813 void DescribeNegationTo(::std::ostream* os) const {
3814 DescribeToHelper(!expect_eq_, os);
3815 }
3816
3817 private:
3818 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
3819 *os << (expect_eq ? "is " : "isn't ");
3820 *os << "equal to ";
3821 if (!case_sensitive_) {
3822 *os << "(ignoring case) ";
3823 }
3824 UniversalPrint(string_, os);
3825 }
3826
3827 const StringType string_;
3828 const bool expect_eq_;
3829 const bool case_sensitive_;
3830 };
3831
3832 // Implements the polymorphic HasSubstr(substring) matcher, which
3833 // can be used as a Matcher<T> as long as T can be converted to a
3834 // string.
3835 template <typename StringType>
3836 class HasSubstrMatcher {
3837 public:
3838 explicit HasSubstrMatcher(const StringType& substring)
3839 : substring_(substring) {}
3840
3841 #if GTEST_INTERNAL_HAS_STRING_VIEW
3842 bool MatchAndExplain(const internal::StringView& s,
3843 MatchResultListener* listener) const {
3844 // This should fail to compile if StringView is used with wide
3845 // strings.
3846 const StringType& str = std::string(s);
3847 return MatchAndExplain(str, listener);
3848 }
3849 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3850
3851 // Accepts pointer types, particularly:
3852 // const char*
3853 // char*
3854 // const wchar_t*
3855 // wchar_t*
3856 template <typename CharType>
3857 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3858 return s != nullptr && MatchAndExplain(StringType(s), listener);
3859 }
3860
3861 // Matches anything that can convert to StringType.
3862 //
3863 // This is a template, not just a plain function with const StringType&,
3864 // because StringView has some interfering non-explicit constructors.
3865 template <typename MatcheeStringType>
3866 bool MatchAndExplain(const MatcheeStringType& s,
3867 MatchResultListener* /* listener */) const {
3868 return StringType(s).find(substring_) != StringType::npos;
3869 }
3870
3871 // Describes what this matcher matches.
3872 void DescribeTo(::std::ostream* os) const {
3873 *os << "has substring ";
3874 UniversalPrint(substring_, os);
3875 }
3876
3877 void DescribeNegationTo(::std::ostream* os) const {
3878 *os << "has no substring ";
3879 UniversalPrint(substring_, os);
3880 }
3881
3882 private:
3883 const StringType substring_;
3884 };
3885
3886 // Implements the polymorphic StartsWith(substring) matcher, which
3887 // can be used as a Matcher<T> as long as T can be converted to a
3888 // string.
3889 template <typename StringType>
3890 class StartsWithMatcher {
3891 public:
3892 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
3893 }
3894
3895 #if GTEST_INTERNAL_HAS_STRING_VIEW
3896 bool MatchAndExplain(const internal::StringView& s,
3897 MatchResultListener* listener) const {
3898 // This should fail to compile if StringView is used with wide
3899 // strings.
3900 const StringType& str = std::string(s);
3901 return MatchAndExplain(str, listener);
3902 }
3903 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3904
3905 // Accepts pointer types, particularly:
3906 // const char*
3907 // char*
3908 // const wchar_t*
3909 // wchar_t*
3910 template <typename CharType>
3911 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3912 return s != nullptr && MatchAndExplain(StringType(s), listener);
3913 }
3914
3915 // Matches anything that can convert to StringType.
3916 //
3917 // This is a template, not just a plain function with const StringType&,
3918 // because StringView has some interfering non-explicit constructors.
3919 template <typename MatcheeStringType>
3920 bool MatchAndExplain(const MatcheeStringType& s,
3921 MatchResultListener* /* listener */) const {
3922 const StringType& s2(s);
3923 return s2.length() >= prefix_.length() &&
3924 s2.substr(0, prefix_.length()) == prefix_;
3925 }
3926
3927 void DescribeTo(::std::ostream* os) const {
3928 *os << "starts with ";
3929 UniversalPrint(prefix_, os);
3930 }
3931
3932 void DescribeNegationTo(::std::ostream* os) const {
3933 *os << "doesn't start with ";
3934 UniversalPrint(prefix_, os);
3935 }
3936
3937 private:
3938 const StringType prefix_;
3939 };
3940
3941 // Implements the polymorphic EndsWith(substring) matcher, which
3942 // can be used as a Matcher<T> as long as T can be converted to a
3943 // string.
3944 template <typename StringType>
3945 class EndsWithMatcher {
3946 public:
3947 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
3948
3949 #if GTEST_INTERNAL_HAS_STRING_VIEW
3950 bool MatchAndExplain(const internal::StringView& s,
3951 MatchResultListener* listener) const {
3952 // This should fail to compile if StringView is used with wide
3953 // strings.
3954 const StringType& str = std::string(s);
3955 return MatchAndExplain(str, listener);
3956 }
3957 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
3958
3959 // Accepts pointer types, particularly:
3960 // const char*
3961 // char*
3962 // const wchar_t*
3963 // wchar_t*
3964 template <typename CharType>
3965 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
3966 return s != nullptr && MatchAndExplain(StringType(s), listener);
3967 }
3968
3969 // Matches anything that can convert to StringType.
3970 //
3971 // This is a template, not just a plain function with const StringType&,
3972 // because StringView has some interfering non-explicit constructors.
3973 template <typename MatcheeStringType>
3974 bool MatchAndExplain(const MatcheeStringType& s,
3975 MatchResultListener* /* listener */) const {
3976 const StringType& s2(s);
3977 return s2.length() >= suffix_.length() &&
3978 s2.substr(s2.length() - suffix_.length()) == suffix_;
3979 }
3980
3981 void DescribeTo(::std::ostream* os) const {
3982 *os << "ends with ";
3983 UniversalPrint(suffix_, os);
3984 }
3985
3986 void DescribeNegationTo(::std::ostream* os) const {
3987 *os << "doesn't end with ";
3988 UniversalPrint(suffix_, os);
3989 }
3990
3991 private:
3992 const StringType suffix_;
3993 };
3994
3995 // Implements a matcher that compares the two fields of a 2-tuple
3996 // using one of the ==, <=, <, etc, operators. The two fields being
3997 // compared don't have to have the same type.
3998 //
3999 // The matcher defined here is polymorphic (for example, Eq() can be
4000 // used to match a std::tuple<int, short>, a std::tuple<const long&, double>,
4001 // etc). Therefore we use a template type conversion operator in the
4002 // implementation.
4003 template <typename D, typename Op>
4004 class PairMatchBase {
4005 public:
4006 template <typename T1, typename T2>
4007 operator Matcher<::std::tuple<T1, T2>>() const {
4008 return Matcher<::std::tuple<T1, T2>>(new Impl<const ::std::tuple<T1, T2>&>);
4009 }
4010 template <typename T1, typename T2>
4011 operator Matcher<const ::std::tuple<T1, T2>&>() const {
4012 return MakeMatcher(new Impl<const ::std::tuple<T1, T2>&>);
4013 }
4014
4015 private:
4016 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
4017 return os << D::Desc();
4018 }
4019
4020 template <typename Tuple>
4021 class Impl : public MatcherInterface<Tuple> {
4022 public:
4023 bool MatchAndExplain(Tuple args,
4024 MatchResultListener* /* listener */) const override {
4025 return Op()(::std::get<0>(args), ::std::get<1>(args));
4026 }
4027 void DescribeTo(::std::ostream* os) const override {
4028 *os << "are " << GetDesc;
4029 }
4030 void DescribeNegationTo(::std::ostream* os) const override {
4031 *os << "aren't " << GetDesc;
4032 }
4033 };
4034 };
4035
4036 class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
4037 public:
4038 static const char* Desc() { return "an equal pair"; }
4039 };
4040 class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
4041 public:
4042 static const char* Desc() { return "an unequal pair"; }
4043 };
4044 class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
4045 public:
4046 static const char* Desc() { return "a pair where the first < the second"; }
4047 };
4048 class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
4049 public:
4050 static const char* Desc() { return "a pair where the first > the second"; }
4051 };
4052 class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
4053 public:
4054 static const char* Desc() { return "a pair where the first <= the second"; }
4055 };
4056 class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
4057 public:
4058 static const char* Desc() { return "a pair where the first >= the second"; }
4059 };
4060
4061 // Implements the Not(...) matcher for a particular argument type T.
4062 // We do not nest it inside the NotMatcher class template, as that
4063 // will prevent different instantiations of NotMatcher from sharing
4064 // the same NotMatcherImpl<T> class.
4065 template <typename T>
4066 class NotMatcherImpl : public MatcherInterface<const T&> {
4067 public:
4068 explicit NotMatcherImpl(const Matcher<T>& matcher)
4069 : matcher_(matcher) {}
4070
4071 bool MatchAndExplain(const T& x,
4072 MatchResultListener* listener) const override {
4073 return !matcher_.MatchAndExplain(x, listener);
4074 }
4075
4076 void DescribeTo(::std::ostream* os) const override {
4077 matcher_.DescribeNegationTo(os);
4078 }
4079
4080 void DescribeNegationTo(::std::ostream* os) const override {
4081 matcher_.DescribeTo(os);
4082 }
4083
4084 private:
4085 const Matcher<T> matcher_;
4086 };
4087
4088 // Implements the Not(m) matcher, which matches a value that doesn't
4089 // match matcher m.
4090 template <typename InnerMatcher>
4091 class NotMatcher {
4092 public:
4093 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
4094
4095 // This template type conversion operator allows Not(m) to be used
4096 // to match any type m can match.
4097 template <typename T>
4098 operator Matcher<T>() const {
4099 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
4100 }
4101
4102 private:
4103 InnerMatcher matcher_;
4104 };
4105
4106 // Implements the AllOf(m1, m2) matcher for a particular argument type
4107 // T. We do not nest it inside the BothOfMatcher class template, as
4108 // that will prevent different instantiations of BothOfMatcher from
4109 // sharing the same BothOfMatcherImpl<T> class.
4110 template <typename T>
4111 class AllOfMatcherImpl : public MatcherInterface<const T&> {
4112 public:
4113 explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers)
4114 : matchers_(std::move(matchers)) {}
4115
4116 void DescribeTo(::std::ostream* os) const override {
4117 *os << "(";
4118 for (size_t i = 0; i < matchers_.size(); ++i) {
4119 if (i != 0) *os << ") and (";
4120 matchers_[i].DescribeTo(os);
4121 }
4122 *os << ")";
4123 }
4124
4125 void DescribeNegationTo(::std::ostream* os) const override {
4126 *os << "(";
4127 for (size_t i = 0; i < matchers_.size(); ++i) {
4128 if (i != 0) *os << ") or (";
4129 matchers_[i].DescribeNegationTo(os);
4130 }
4131 *os << ")";
4132 }
4133
4134 bool MatchAndExplain(const T& x,
4135 MatchResultListener* listener) const override {
4136 // If either matcher1_ or matcher2_ doesn't match x, we only need
4137 // to explain why one of them fails.
4138 std::string all_match_result;
4139
4140 for (size_t i = 0; i < matchers_.size(); ++i) {
4141 StringMatchResultListener slistener;
4142 if (matchers_[i].MatchAndExplain(x, &slistener)) {
4143 if (all_match_result.empty()) {
4144 all_match_result = slistener.str();
4145 } else {
4146 std::string result = slistener.str();
4147 if (!result.empty()) {
4148 all_match_result += ", and ";
4149 all_match_result += result;
4150 }
4151 }
4152 } else {
4153 *listener << slistener.str();
4154 return false;
4155 }
4156 }
4157
4158 // Otherwise we need to explain why *both* of them match.
4159 *listener << all_match_result;
4160 return true;
4161 }
4162
4163 private:
4164 const std::vector<Matcher<T> > matchers_;
4165 };
4166
4167 // VariadicMatcher is used for the variadic implementation of
4168 // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
4169 // CombiningMatcher<T> is used to recursively combine the provided matchers
4170 // (of type Args...).
4171 template <template <typename T> class CombiningMatcher, typename... Args>
4172 class VariadicMatcher {
4173 public:
4174 VariadicMatcher(const Args&... matchers) // NOLINT
4175 : matchers_(matchers...) {
4176 static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
4177 }
4178
4179 VariadicMatcher(const VariadicMatcher&) = default;
4180 VariadicMatcher& operator=(const VariadicMatcher&) = delete;
4181
4182 // This template type conversion operator allows an
4183 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
4184 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
4185 template <typename T>
4186 operator Matcher<T>() const {
4187 std::vector<Matcher<T> > values;
4188 CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
4189 return Matcher<T>(new CombiningMatcher<T>(std::move(values)));
4190 }
4191
4192 private:
4193 template <typename T, size_t I>
4194 void CreateVariadicMatcher(std::vector<Matcher<T> >* values,
4195 std::integral_constant<size_t, I>) const {
4196 values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
4197 CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
4198 }
4199
4200 template <typename T>
4201 void CreateVariadicMatcher(
4202 std::vector<Matcher<T> >*,
4203 std::integral_constant<size_t, sizeof...(Args)>) const {}
4204
4205 std::tuple<Args...> matchers_;
4206 };
4207
4208 template <typename... Args>
4209 using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
4210
4211 // Implements the AnyOf(m1, m2) matcher for a particular argument type
4212 // T. We do not nest it inside the AnyOfMatcher class template, as
4213 // that will prevent different instantiations of AnyOfMatcher from
4214 // sharing the same EitherOfMatcherImpl<T> class.
4215 template <typename T>
4216 class AnyOfMatcherImpl : public MatcherInterface<const T&> {
4217 public:
4218 explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers)
4219 : matchers_(std::move(matchers)) {}
4220
4221 void DescribeTo(::std::ostream* os) const override {
4222 *os << "(";
4223 for (size_t i = 0; i < matchers_.size(); ++i) {
4224 if (i != 0) *os << ") or (";
4225 matchers_[i].DescribeTo(os);
4226 }
4227 *os << ")";
4228 }
4229
4230 void DescribeNegationTo(::std::ostream* os) const override {
4231 *os << "(";
4232 for (size_t i = 0; i < matchers_.size(); ++i) {
4233 if (i != 0) *os << ") and (";
4234 matchers_[i].DescribeNegationTo(os);
4235 }
4236 *os << ")";
4237 }
4238
4239 bool MatchAndExplain(const T& x,
4240 MatchResultListener* listener) const override {
4241 std::string no_match_result;
4242
4243 // If either matcher1_ or matcher2_ matches x, we just need to
4244 // explain why *one* of them matches.
4245 for (size_t i = 0; i < matchers_.size(); ++i) {
4246 StringMatchResultListener slistener;
4247 if (matchers_[i].MatchAndExplain(x, &slistener)) {
4248 *listener << slistener.str();
4249 return true;
4250 } else {
4251 if (no_match_result.empty()) {
4252 no_match_result = slistener.str();
4253 } else {
4254 std::string result = slistener.str();
4255 if (!result.empty()) {
4256 no_match_result += ", and ";
4257 no_match_result += result;
4258 }
4259 }
4260 }
4261 }
4262
4263 // Otherwise we need to explain why *both* of them fail.
4264 *listener << no_match_result;
4265 return false;
4266 }
4267
4268 private:
4269 const std::vector<Matcher<T> > matchers_;
4270 };
4271
4272 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
4273 template <typename... Args>
4274 using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
4275
4276 // Wrapper for implementation of Any/AllOfArray().
4277 template <template <class> class MatcherImpl, typename T>
4278 class SomeOfArrayMatcher {
4279 public:
4280 // Constructs the matcher from a sequence of element values or
4281 // element matchers.
4282 template <typename Iter>
4283 SomeOfArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
4284
4285 template <typename U>
4286 operator Matcher<U>() const { // NOLINT
4287 using RawU = typename std::decay<U>::type;
4288 std::vector<Matcher<RawU>> matchers;
4289 for (const auto& matcher : matchers_) {
4290 matchers.push_back(MatcherCast<RawU>(matcher));
4291 }
4292 return Matcher<U>(new MatcherImpl<RawU>(std::move(matchers)));
4293 }
4294
4295 private:
4296 const ::std::vector<T> matchers_;
4297 };
4298
4299 template <typename T>
4300 using AllOfArrayMatcher = SomeOfArrayMatcher<AllOfMatcherImpl, T>;
4301
4302 template <typename T>
4303 using AnyOfArrayMatcher = SomeOfArrayMatcher<AnyOfMatcherImpl, T>;
4304
4305 // Used for implementing Truly(pred), which turns a predicate into a
4306 // matcher.
4307 template <typename Predicate>
4308 class TrulyMatcher {
4309 public:
4310 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
4311
4312 // This method template allows Truly(pred) to be used as a matcher
4313 // for type T where T is the argument type of predicate 'pred'. The
4314 // argument is passed by reference as the predicate may be
4315 // interested in the address of the argument.
4316 template <typename T>
4317 bool MatchAndExplain(T& x, // NOLINT
4318 MatchResultListener* listener) const {
4319 // Without the if-statement, MSVC sometimes warns about converting
4320 // a value to bool (warning 4800).
4321 //
4322 // We cannot write 'return !!predicate_(x);' as that doesn't work
4323 // when predicate_(x) returns a class convertible to bool but
4324 // having no operator!().
4325 if (predicate_(x))
4326 return true;
4327 *listener << "didn't satisfy the given predicate";
4328 return false;
4329 }
4330
4331 void DescribeTo(::std::ostream* os) const {
4332 *os << "satisfies the given predicate";
4333 }
4334
4335 void DescribeNegationTo(::std::ostream* os) const {
4336 *os << "doesn't satisfy the given predicate";
4337 }
4338
4339 private:
4340 Predicate predicate_;
4341 };
4342
4343 // Used for implementing Matches(matcher), which turns a matcher into
4344 // a predicate.
4345 template <typename M>
4346 class MatcherAsPredicate {
4347 public:
4348 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
4349
4350 // This template operator() allows Matches(m) to be used as a
4351 // predicate on type T where m is a matcher on type T.
4352 //
4353 // The argument x is passed by reference instead of by value, as
4354 // some matcher may be interested in its address (e.g. as in
4355 // Matches(Ref(n))(x)).
4356 template <typename T>
4357 bool operator()(const T& x) const {
4358 // We let matcher_ commit to a particular type here instead of
4359 // when the MatcherAsPredicate object was constructed. This
4360 // allows us to write Matches(m) where m is a polymorphic matcher
4361 // (e.g. Eq(5)).
4362 //
4363 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
4364 // compile when matcher_ has type Matcher<const T&>; if we write
4365 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
4366 // when matcher_ has type Matcher<T>; if we just write
4367 // matcher_.Matches(x), it won't compile when matcher_ is
4368 // polymorphic, e.g. Eq(5).
4369 //
4370 // MatcherCast<const T&>() is necessary for making the code work
4371 // in all of the above situations.
4372 return MatcherCast<const T&>(matcher_).Matches(x);
4373 }
4374
4375 private:
4376 M matcher_;
4377 };
4378
4379 // For implementing ASSERT_THAT() and EXPECT_THAT(). The template
4380 // argument M must be a type that can be converted to a matcher.
4381 template <typename M>
4382 class PredicateFormatterFromMatcher {
4383 public:
4384 explicit PredicateFormatterFromMatcher(M m) : matcher_(std::move(m)) {}
4385
4386 // This template () operator allows a PredicateFormatterFromMatcher
4387 // object to act as a predicate-formatter suitable for using with
4388 // Google Test's EXPECT_PRED_FORMAT1() macro.
4389 template <typename T>
4390 AssertionResult operator()(const char* value_text, const T& x) const {
4391 // We convert matcher_ to a Matcher<const T&> *now* instead of
4392 // when the PredicateFormatterFromMatcher object was constructed,
4393 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
4394 // know which type to instantiate it to until we actually see the
4395 // type of x here.
4396 //
4397 // We write SafeMatcherCast<const T&>(matcher_) instead of
4398 // Matcher<const T&>(matcher_), as the latter won't compile when
4399 // matcher_ has type Matcher<T> (e.g. An<int>()).
4400 // We don't write MatcherCast<const T&> either, as that allows
4401 // potentially unsafe downcasting of the matcher argument.
4402 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
4403
4404 // The expected path here is that the matcher should match (i.e. that most
4405 // tests pass) so optimize for this case.
4406 if (matcher.Matches(x)) {
4407 return AssertionSuccess();
4408 }
4409
4410 ::std::stringstream ss;
4411 ss << "Value of: " << value_text << "\n"
4412 << "Expected: ";
4413 matcher.DescribeTo(&ss);
4414
4415 // Rerun the matcher to "PrintAndExplain" the failure.
4416 StringMatchResultListener listener;
4417 if (MatchPrintAndExplain(x, matcher, &listener)) {
4418 ss << "\n The matcher failed on the initial attempt; but passed when "
4419 "rerun to generate the explanation.";
4420 }
4421 ss << "\n Actual: " << listener.str();
4422 return AssertionFailure() << ss.str();
4423 }
4424
4425 private:
4426 const M matcher_;
4427 };
4428
4429 // A helper function for converting a matcher to a predicate-formatter
4430 // without the user needing to explicitly write the type. This is
4431 // used for implementing ASSERT_THAT() and EXPECT_THAT().
4432 // Implementation detail: 'matcher' is received by-value to force decaying.
4433 template <typename M>
4434 inline PredicateFormatterFromMatcher<M>
4435 MakePredicateFormatterFromMatcher(M matcher) {
4436 return PredicateFormatterFromMatcher<M>(std::move(matcher));
4437 }
4438
4439 // Implements the polymorphic IsNan() matcher, which matches any floating type
4440 // value that is Nan.
4441 class IsNanMatcher {
4442 public:
4443 template <typename FloatType>
4444 bool MatchAndExplain(const FloatType& f,
4445 MatchResultListener* /* listener */) const {
4446 return (::std::isnan)(f);
4447 }
4448
4449 void DescribeTo(::std::ostream* os) const { *os << "is NaN"; }
4450 void DescribeNegationTo(::std::ostream* os) const {
4451 *os << "isn't NaN";
4452 }
4453 };
4454
4455 // Implements the polymorphic floating point equality matcher, which matches
4456 // two float values using ULP-based approximation or, optionally, a
4457 // user-specified epsilon. The template is meant to be instantiated with
4458 // FloatType being either float or double.
4459 template <typename FloatType>
4460 class FloatingEqMatcher {
4461 public:
4462 // Constructor for FloatingEqMatcher.
4463 // The matcher's input will be compared with expected. The matcher treats two
4464 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
4465 // equality comparisons between NANs will always return false. We specify a
4466 // negative max_abs_error_ term to indicate that ULP-based approximation will
4467 // be used for comparison.
4468 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
4469 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
4470 }
4471
4472 // Constructor that supports a user-specified max_abs_error that will be used
4473 // for comparison instead of ULP-based approximation. The max absolute
4474 // should be non-negative.
4475 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
4476 FloatType max_abs_error)
4477 : expected_(expected),
4478 nan_eq_nan_(nan_eq_nan),
4479 max_abs_error_(max_abs_error) {
4480 GTEST_CHECK_(max_abs_error >= 0)
4481 << ", where max_abs_error is" << max_abs_error;
4482 }
4483
4484 // Implements floating point equality matcher as a Matcher<T>.
4485 template <typename T>
4486 class Impl : public MatcherInterface<T> {
4487 public:
4488 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
4489 : expected_(expected),
4490 nan_eq_nan_(nan_eq_nan),
4491 max_abs_error_(max_abs_error) {}
4492
4493 bool MatchAndExplain(T value,
4494 MatchResultListener* listener) const override {
4495 const FloatingPoint<FloatType> actual(value), expected(expected_);
4496
4497 // Compares NaNs first, if nan_eq_nan_ is true.
4498 if (actual.is_nan() || expected.is_nan()) {
4499 if (actual.is_nan() && expected.is_nan()) {
4500 return nan_eq_nan_;
4501 }
4502 // One is nan; the other is not nan.
4503 return false;
4504 }
4505 if (HasMaxAbsError()) {
4506 // We perform an equality check so that inf will match inf, regardless
4507 // of error bounds. If the result of value - expected_ would result in
4508 // overflow or if either value is inf, the default result is infinity,
4509 // which should only match if max_abs_error_ is also infinity.
4510 if (value == expected_) {
4511 return true;
4512 }
4513
4514 const FloatType diff = value - expected_;
4515 if (::std::fabs(diff) <= max_abs_error_) {
4516 return true;
4517 }
4518
4519 if (listener->IsInterested()) {
4520 *listener << "which is " << diff << " from " << expected_;
4521 }
4522 return false;
4523 } else {
4524 return actual.AlmostEquals(expected);
4525 }
4526 }
4527
4528 void DescribeTo(::std::ostream* os) const override {
4529 // os->precision() returns the previously set precision, which we
4530 // store to restore the ostream to its original configuration
4531 // after outputting.
4532 const ::std::streamsize old_precision = os->precision(
4533 ::std::numeric_limits<FloatType>::digits10 + 2);
4534 if (FloatingPoint<FloatType>(expected_).is_nan()) {
4535 if (nan_eq_nan_) {
4536 *os << "is NaN";
4537 } else {
4538 *os << "never matches";
4539 }
4540 } else {
4541 *os << "is approximately " << expected_;
4542 if (HasMaxAbsError()) {
4543 *os << " (absolute error <= " << max_abs_error_ << ")";
4544 }
4545 }
4546 os->precision(old_precision);
4547 }
4548
4549 void DescribeNegationTo(::std::ostream* os) const override {
4550 // As before, get original precision.
4551 const ::std::streamsize old_precision = os->precision(
4552 ::std::numeric_limits<FloatType>::digits10 + 2);
4553 if (FloatingPoint<FloatType>(expected_).is_nan()) {
4554 if (nan_eq_nan_) {
4555 *os << "isn't NaN";
4556 } else {
4557 *os << "is anything";
4558 }
4559 } else {
4560 *os << "isn't approximately " << expected_;
4561 if (HasMaxAbsError()) {
4562 *os << " (absolute error > " << max_abs_error_ << ")";
4563 }
4564 }
4565 // Restore original precision.
4566 os->precision(old_precision);
4567 }
4568
4569 private:
4570 bool HasMaxAbsError() const {
4571 return max_abs_error_ >= 0;
4572 }
4573
4574 const FloatType expected_;
4575 const bool nan_eq_nan_;
4576 // max_abs_error will be used for value comparison when >= 0.
4577 const FloatType max_abs_error_;
4578 };
4579
4580 // The following 3 type conversion operators allow FloatEq(expected) and
4581 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
4582 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
4583 operator Matcher<FloatType>() const {
4584 return MakeMatcher(
4585 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
4586 }
4587
4588 operator Matcher<const FloatType&>() const {
4589 return MakeMatcher(
4590 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
4591 }
4592
4593 operator Matcher<FloatType&>() const {
4594 return MakeMatcher(
4595 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
4596 }
4597
4598 private:
4599 const FloatType expected_;
4600 const bool nan_eq_nan_;
4601 // max_abs_error will be used for value comparison when >= 0.
4602 const FloatType max_abs_error_;
4603 };
4604
4605 // A 2-tuple ("binary") wrapper around FloatingEqMatcher:
4606 // FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
4607 // against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
4608 // against y. The former implements "Eq", the latter "Near". At present, there
4609 // is no version that compares NaNs as equal.
4610 template <typename FloatType>
4611 class FloatingEq2Matcher {
4612 public:
4613 FloatingEq2Matcher() { Init(-1, false); }
4614
4615 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
4616
4617 explicit FloatingEq2Matcher(FloatType max_abs_error) {
4618 Init(max_abs_error, false);
4619 }
4620
4621 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
4622 Init(max_abs_error, nan_eq_nan);
4623 }
4624
4625 template <typename T1, typename T2>
4626 operator Matcher<::std::tuple<T1, T2>>() const {
4627 return MakeMatcher(
4628 new Impl<::std::tuple<T1, T2>>(max_abs_error_, nan_eq_nan_));
4629 }
4630 template <typename T1, typename T2>
4631 operator Matcher<const ::std::tuple<T1, T2>&>() const {
4632 return MakeMatcher(
4633 new Impl<const ::std::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
4634 }
4635
4636 private:
4637 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
4638 return os << "an almost-equal pair";
4639 }
4640
4641 template <typename Tuple>
4642 class Impl : public MatcherInterface<Tuple> {
4643 public:
4644 Impl(FloatType max_abs_error, bool nan_eq_nan) :
4645 max_abs_error_(max_abs_error),
4646 nan_eq_nan_(nan_eq_nan) {}
4647
4648 bool MatchAndExplain(Tuple args,
4649 MatchResultListener* listener) const override {
4650 if (max_abs_error_ == -1) {
4651 FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_);
4652 return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(
4653 ::std::get<1>(args), listener);
4654 } else {
4655 FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_,
4656 max_abs_error_);
4657 return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(
4658 ::std::get<1>(args), listener);
4659 }
4660 }
4661 void DescribeTo(::std::ostream* os) const override {
4662 *os << "are " << GetDesc;
4663 }
4664 void DescribeNegationTo(::std::ostream* os) const override {
4665 *os << "aren't " << GetDesc;
4666 }
4667
4668 private:
4669 FloatType max_abs_error_;
4670 const bool nan_eq_nan_;
4671 };
4672
4673 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
4674 max_abs_error_ = max_abs_error_val;
4675 nan_eq_nan_ = nan_eq_nan_val;
4676 }
4677 FloatType max_abs_error_;
4678 bool nan_eq_nan_;
4679 };
4680
4681 // Implements the Pointee(m) matcher for matching a pointer whose
4682 // pointee matches matcher m. The pointer can be either raw or smart.
4683 template <typename InnerMatcher>
4684 class PointeeMatcher {
4685 public:
4686 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
4687
4688 // This type conversion operator template allows Pointee(m) to be
4689 // used as a matcher for any pointer type whose pointee type is
4690 // compatible with the inner matcher, where type Pointer can be
4691 // either a raw pointer or a smart pointer.
4692 //
4693 // The reason we do this instead of relying on
4694 // MakePolymorphicMatcher() is that the latter is not flexible
4695 // enough for implementing the DescribeTo() method of Pointee().
4696 template <typename Pointer>
4697 operator Matcher<Pointer>() const {
4698 return Matcher<Pointer>(new Impl<const Pointer&>(matcher_));
4699 }
4700
4701 private:
4702 // The monomorphic implementation that works for a particular pointer type.
4703 template <typename Pointer>
4704 class Impl : public MatcherInterface<Pointer> {
4705 public:
4706 using Pointee =
4707 typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
4708 Pointer)>::element_type;
4709
4710 explicit Impl(const InnerMatcher& matcher)
4711 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
4712
4713 void DescribeTo(::std::ostream* os) const override {
4714 *os << "points to a value that ";
4715 matcher_.DescribeTo(os);
4716 }
4717
4718 void DescribeNegationTo(::std::ostream* os) const override {
4719 *os << "does not point to a value that ";
4720 matcher_.DescribeTo(os);
4721 }
4722
4723 bool MatchAndExplain(Pointer pointer,
4724 MatchResultListener* listener) const override {
4725 if (GetRawPointer(pointer) == nullptr) return false;
4726
4727 *listener << "which points to ";
4728 return MatchPrintAndExplain(*pointer, matcher_, listener);
4729 }
4730
4731 private:
4732 const Matcher<const Pointee&> matcher_;
4733 };
4734
4735 const InnerMatcher matcher_;
4736 };
4737
4738 // Implements the Pointer(m) matcher
4739 // Implements the Pointer(m) matcher for matching a pointer that matches matcher
4740 // m. The pointer can be either raw or smart, and will match `m` against the
4741 // raw pointer.
4742 template <typename InnerMatcher>
4743 class PointerMatcher {
4744 public:
4745 explicit PointerMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
4746
4747 // This type conversion operator template allows Pointer(m) to be
4748 // used as a matcher for any pointer type whose pointer type is
4749 // compatible with the inner matcher, where type PointerType can be
4750 // either a raw pointer or a smart pointer.
4751 //
4752 // The reason we do this instead of relying on
4753 // MakePolymorphicMatcher() is that the latter is not flexible
4754 // enough for implementing the DescribeTo() method of Pointer().
4755 template <typename PointerType>
4756 operator Matcher<PointerType>() const { // NOLINT
4757 return Matcher<PointerType>(new Impl<const PointerType&>(matcher_));
4758 }
4759
4760 private:
4761 // The monomorphic implementation that works for a particular pointer type.
4762 template <typename PointerType>
4763 class Impl : public MatcherInterface<PointerType> {
4764 public:
4765 using Pointer =
4766 const typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
4767 PointerType)>::element_type*;
4768
4769 explicit Impl(const InnerMatcher& matcher)
4770 : matcher_(MatcherCast<Pointer>(matcher)) {}
4771
4772 void DescribeTo(::std::ostream* os) const override {
4773 *os << "is a pointer that ";
4774 matcher_.DescribeTo(os);
4775 }
4776
4777 void DescribeNegationTo(::std::ostream* os) const override {
4778 *os << "is not a pointer that ";
4779 matcher_.DescribeTo(os);
4780 }
4781
4782 bool MatchAndExplain(PointerType pointer,
4783 MatchResultListener* listener) const override {
4784 *listener << "which is a pointer that ";
4785 Pointer p = GetRawPointer(pointer);
4786 return MatchPrintAndExplain(p, matcher_, listener);
4787 }
4788
4789 private:
4790 Matcher<Pointer> matcher_;
4791 };
4792
4793 const InnerMatcher matcher_;
4794 };
4795
4796 #if GTEST_HAS_RTTI
4797 // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
4798 // reference that matches inner_matcher when dynamic_cast<T> is applied.
4799 // The result of dynamic_cast<To> is forwarded to the inner matcher.
4800 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
4801 // If To is a reference and the cast fails, this matcher returns false
4802 // immediately.
4803 template <typename To>
4804 class WhenDynamicCastToMatcherBase {
4805 public:
4806 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
4807 : matcher_(matcher) {}
4808
4809 void DescribeTo(::std::ostream* os) const {
4810 GetCastTypeDescription(os);
4811 matcher_.DescribeTo(os);
4812 }
4813
4814 void DescribeNegationTo(::std::ostream* os) const {
4815 GetCastTypeDescription(os);
4816 matcher_.DescribeNegationTo(os);
4817 }
4818
4819 protected:
4820 const Matcher<To> matcher_;
4821
4822 static std::string GetToName() {
4823 return GetTypeName<To>();
4824 }
4825
4826 private:
4827 static void GetCastTypeDescription(::std::ostream* os) {
4828 *os << "when dynamic_cast to " << GetToName() << ", ";
4829 }
4830 };
4831
4832 // Primary template.
4833 // To is a pointer. Cast and forward the result.
4834 template <typename To>
4835 class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
4836 public:
4837 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
4838 : WhenDynamicCastToMatcherBase<To>(matcher) {}
4839
4840 template <typename From>
4841 bool MatchAndExplain(From from, MatchResultListener* listener) const {
4842 To to = dynamic_cast<To>(from);
4843 return MatchPrintAndExplain(to, this->matcher_, listener);
4844 }
4845 };
4846
4847 // Specialize for references.
4848 // In this case we return false if the dynamic_cast fails.
4849 template <typename To>
4850 class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
4851 public:
4852 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
4853 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
4854
4855 template <typename From>
4856 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
4857 // We don't want an std::bad_cast here, so do the cast with pointers.
4858 To* to = dynamic_cast<To*>(&from);
4859 if (to == nullptr) {
4860 *listener << "which cannot be dynamic_cast to " << this->GetToName();
4861 return false;
4862 }
4863 return MatchPrintAndExplain(*to, this->matcher_, listener);
4864 }
4865 };
4866 #endif // GTEST_HAS_RTTI
4867
4868 // Implements the Field() matcher for matching a field (i.e. member
4869 // variable) of an object.
4870 template <typename Class, typename FieldType>
4871 class FieldMatcher {
4872 public:
4873 FieldMatcher(FieldType Class::*field,
4874 const Matcher<const FieldType&>& matcher)
4875 : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
4876
4877 FieldMatcher(const std::string& field_name, FieldType Class::*field,
4878 const Matcher<const FieldType&>& matcher)
4879 : field_(field),
4880 matcher_(matcher),
4881 whose_field_("whose field `" + field_name + "` ") {}
4882
4883 void DescribeTo(::std::ostream* os) const {
4884 *os << "is an object " << whose_field_;
4885 matcher_.DescribeTo(os);
4886 }
4887
4888 void DescribeNegationTo(::std::ostream* os) const {
4889 *os << "is an object " << whose_field_;
4890 matcher_.DescribeNegationTo(os);
4891 }
4892
4893 template <typename T>
4894 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
4895 // FIXME: The dispatch on std::is_pointer was introduced as a workaround for
4896 // a compiler bug, and can now be removed.
4897 return MatchAndExplainImpl(
4898 typename std::is_pointer<typename std::remove_const<T>::type>::type(),
4899 value, listener);
4900 }
4901
4902 private:
4903 bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,
4904 const Class& obj,
4905 MatchResultListener* listener) const {
4906 *listener << whose_field_ << "is ";
4907 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
4908 }
4909
4910 bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,
4911 MatchResultListener* listener) const {
4912 if (p == nullptr) return false;
4913
4914 *listener << "which points to an object ";
4915 // Since *p has a field, it must be a class/struct/union type and
4916 // thus cannot be a pointer. Therefore we pass false_type() as
4917 // the first argument.
4918 return MatchAndExplainImpl(std::false_type(), *p, listener);
4919 }
4920
4921 const FieldType Class::*field_;
4922 const Matcher<const FieldType&> matcher_;
4923
4924 // Contains either "whose given field " if the name of the field is unknown
4925 // or "whose field `name_of_field` " if the name is known.
4926 const std::string whose_field_;
4927 };
4928
4929 // Implements the Property() matcher for matching a property
4930 // (i.e. return value of a getter method) of an object.
4931 //
4932 // Property is a const-qualified member function of Class returning
4933 // PropertyType.
4934 template <typename Class, typename PropertyType, typename Property>
4935 class PropertyMatcher {
4936 public:
4937 typedef const PropertyType& RefToConstProperty;
4938
4939 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
4940 : property_(property),
4941 matcher_(matcher),
4942 whose_property_("whose given property ") {}
4943
4944 PropertyMatcher(const std::string& property_name, Property property,
4945 const Matcher<RefToConstProperty>& matcher)
4946 : property_(property),
4947 matcher_(matcher),
4948 whose_property_("whose property `" + property_name + "` ") {}
4949
4950 void DescribeTo(::std::ostream* os) const {
4951 *os << "is an object " << whose_property_;
4952 matcher_.DescribeTo(os);
4953 }
4954
4955 void DescribeNegationTo(::std::ostream* os) const {
4956 *os << "is an object " << whose_property_;
4957 matcher_.DescribeNegationTo(os);
4958 }
4959
4960 template <typename T>
4961 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
4962 return MatchAndExplainImpl(
4963 typename std::is_pointer<typename std::remove_const<T>::type>::type(),
4964 value, listener);
4965 }
4966
4967 private:
4968 bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,
4969 const Class& obj,
4970 MatchResultListener* listener) const {
4971 *listener << whose_property_ << "is ";
4972 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
4973 // which takes a non-const reference as argument.
4974 RefToConstProperty result = (obj.*property_)();
4975 return MatchPrintAndExplain(result, matcher_, listener);
4976 }
4977
4978 bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,
4979 MatchResultListener* listener) const {
4980 if (p == nullptr) return false;
4981
4982 *listener << "which points to an object ";
4983 // Since *p has a property method, it must be a class/struct/union
4984 // type and thus cannot be a pointer. Therefore we pass
4985 // false_type() as the first argument.
4986 return MatchAndExplainImpl(std::false_type(), *p, listener);
4987 }
4988
4989 Property property_;
4990 const Matcher<RefToConstProperty> matcher_;
4991
4992 // Contains either "whose given property " if the name of the property is
4993 // unknown or "whose property `name_of_property` " if the name is known.
4994 const std::string whose_property_;
4995 };
4996
4997 // Type traits specifying various features of different functors for ResultOf.
4998 // The default template specifies features for functor objects.
4999 template <typename Functor>
5000 struct CallableTraits {
5001 typedef Functor StorageType;
5002
5003 static void CheckIsValid(Functor /* functor */) {}
5004
5005 template <typename T>
5006 static auto Invoke(Functor f, const T& arg) -> decltype(f(arg)) {
5007 return f(arg);
5008 }
5009 };
5010
5011 // Specialization for function pointers.
5012 template <typename ArgType, typename ResType>
5013 struct CallableTraits<ResType(*)(ArgType)> {
5014 typedef ResType ResultType;
5015 typedef ResType(*StorageType)(ArgType);
5016
5017 static void CheckIsValid(ResType(*f)(ArgType)) {
5018 GTEST_CHECK_(f != nullptr)
5019 << "NULL function pointer is passed into ResultOf().";
5020 }
5021 template <typename T>
5022 static ResType Invoke(ResType(*f)(ArgType), T arg) {
5023 return (*f)(arg);
5024 }
5025 };
5026
5027 // Implements the ResultOf() matcher for matching a return value of a
5028 // unary function of an object.
5029 template <typename Callable, typename InnerMatcher>
5030 class ResultOfMatcher {
5031 public:
5032 ResultOfMatcher(Callable callable, InnerMatcher matcher)
5033 : callable_(std::move(callable)), matcher_(std::move(matcher)) {
5034 CallableTraits<Callable>::CheckIsValid(callable_);
5035 }
5036
5037 template <typename T>
5038 operator Matcher<T>() const {
5039 return Matcher<T>(new Impl<const T&>(callable_, matcher_));
5040 }
5041
5042 private:
5043 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
5044
5045 template <typename T>
5046 class Impl : public MatcherInterface<T> {
5047 using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(
5048 std::declval<CallableStorageType>(), std::declval<T>()));
5049
5050 public:
5051 template <typename M>
5052 Impl(const CallableStorageType& callable, const M& matcher)
5053 : callable_(callable), matcher_(MatcherCast<ResultType>(matcher)) {}
5054
5055 void DescribeTo(::std::ostream* os) const override {
5056 *os << "is mapped by the given callable to a value that ";
5057 matcher_.DescribeTo(os);
5058 }
5059
5060 void DescribeNegationTo(::std::ostream* os) const override {
5061 *os << "is mapped by the given callable to a value that ";
5062 matcher_.DescribeNegationTo(os);
5063 }
5064
5065 bool MatchAndExplain(T obj, MatchResultListener* listener) const override {
5066 *listener << "which is mapped by the given callable to ";
5067 // Cannot pass the return value directly to MatchPrintAndExplain, which
5068 // takes a non-const reference as argument.
5069 // Also, specifying template argument explicitly is needed because T could
5070 // be a non-const reference (e.g. Matcher<Uncopyable&>).
5071 ResultType result =
5072 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
5073 return MatchPrintAndExplain(result, matcher_, listener);
5074 }
5075
5076 private:
5077 // Functors often define operator() as non-const method even though
5078 // they are actually stateless. But we need to use them even when
5079 // 'this' is a const pointer. It's the user's responsibility not to
5080 // use stateful callables with ResultOf(), which doesn't guarantee
5081 // how many times the callable will be invoked.
5082 mutable CallableStorageType callable_;
5083 const Matcher<ResultType> matcher_;
5084 }; // class Impl
5085
5086 const CallableStorageType callable_;
5087 const InnerMatcher matcher_;
5088 };
5089
5090 // Implements a matcher that checks the size of an STL-style container.
5091 template <typename SizeMatcher>
5092 class SizeIsMatcher {
5093 public:
5094 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
5095 : size_matcher_(size_matcher) {
5096 }
5097
5098 template <typename Container>
5099 operator Matcher<Container>() const {
5100 return Matcher<Container>(new Impl<const Container&>(size_matcher_));
5101 }
5102
5103 template <typename Container>
5104 class Impl : public MatcherInterface<Container> {
5105 public:
5106 using SizeType = decltype(std::declval<Container>().size());
5107 explicit Impl(const SizeMatcher& size_matcher)
5108 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
5109
5110 void DescribeTo(::std::ostream* os) const override {
5111 *os << "size ";
5112 size_matcher_.DescribeTo(os);
5113 }
5114 void DescribeNegationTo(::std::ostream* os) const override {
5115 *os << "size ";
5116 size_matcher_.DescribeNegationTo(os);
5117 }
5118
5119 bool MatchAndExplain(Container container,
5120 MatchResultListener* listener) const override {
5121 SizeType size = container.size();
5122 StringMatchResultListener size_listener;
5123 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
5124 *listener
5125 << "whose size " << size << (result ? " matches" : " doesn't match");
5126 PrintIfNotEmpty(size_listener.str(), listener->stream());
5127 return result;
5128 }
5129
5130 private:
5131 const Matcher<SizeType> size_matcher_;
5132 };
5133
5134 private:
5135 const SizeMatcher size_matcher_;
5136 };
5137
5138 // Implements a matcher that checks the begin()..end() distance of an STL-style
5139 // container.
5140 template <typename DistanceMatcher>
5141 class BeginEndDistanceIsMatcher {
5142 public:
5143 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
5144 : distance_matcher_(distance_matcher) {}
5145
5146 template <typename Container>
5147 operator Matcher<Container>() const {
5148 return Matcher<Container>(new Impl<const Container&>(distance_matcher_));
5149 }
5150
5151 template <typename Container>
5152 class Impl : public MatcherInterface<Container> {
5153 public:
5154 typedef internal::StlContainerView<
5155 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
5156 typedef typename std::iterator_traits<
5157 typename ContainerView::type::const_iterator>::difference_type
5158 DistanceType;
5159 explicit Impl(const DistanceMatcher& distance_matcher)
5160 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
5161
5162 void DescribeTo(::std::ostream* os) const override {
5163 *os << "distance between begin() and end() ";
5164 distance_matcher_.DescribeTo(os);
5165 }
5166 void DescribeNegationTo(::std::ostream* os) const override {
5167 *os << "distance between begin() and end() ";
5168 distance_matcher_.DescribeNegationTo(os);
5169 }
5170
5171 bool MatchAndExplain(Container container,
5172 MatchResultListener* listener) const override {
5173 using std::begin;
5174 using std::end;
5175 DistanceType distance = std::distance(begin(container), end(container));
5176 StringMatchResultListener distance_listener;
5177 const bool result =
5178 distance_matcher_.MatchAndExplain(distance, &distance_listener);
5179 *listener << "whose distance between begin() and end() " << distance
5180 << (result ? " matches" : " doesn't match");
5181 PrintIfNotEmpty(distance_listener.str(), listener->stream());
5182 return result;
5183 }
5184
5185 private:
5186 const Matcher<DistanceType> distance_matcher_;
5187 };
5188
5189 private:
5190 const DistanceMatcher distance_matcher_;
5191 };
5192
5193 // Implements an equality matcher for any STL-style container whose elements
5194 // support ==. This matcher is like Eq(), but its failure explanations provide
5195 // more detailed information that is useful when the container is used as a set.
5196 // The failure message reports elements that are in one of the operands but not
5197 // the other. The failure messages do not report duplicate or out-of-order
5198 // elements in the containers (which don't properly matter to sets, but can
5199 // occur if the containers are vectors or lists, for example).
5200 //
5201 // Uses the container's const_iterator, value_type, operator ==,
5202 // begin(), and end().
5203 template <typename Container>
5204 class ContainerEqMatcher {
5205 public:
5206 typedef internal::StlContainerView<Container> View;
5207 typedef typename View::type StlContainer;
5208 typedef typename View::const_reference StlContainerReference;
5209
5210 static_assert(!std::is_const<Container>::value,
5211 "Container type must not be const");
5212 static_assert(!std::is_reference<Container>::value,
5213 "Container type must not be a reference");
5214
5215 // We make a copy of expected in case the elements in it are modified
5216 // after this matcher is created.
5217 explicit ContainerEqMatcher(const Container& expected)
5218 : expected_(View::Copy(expected)) {}
5219
5220 void DescribeTo(::std::ostream* os) const {
5221 *os << "equals ";
5222 UniversalPrint(expected_, os);
5223 }
5224 void DescribeNegationTo(::std::ostream* os) const {
5225 *os << "does not equal ";
5226 UniversalPrint(expected_, os);
5227 }
5228
5229 template <typename LhsContainer>
5230 bool MatchAndExplain(const LhsContainer& lhs,
5231 MatchResultListener* listener) const {
5232 typedef internal::StlContainerView<
5233 typename std::remove_const<LhsContainer>::type>
5234 LhsView;
5235 typedef typename LhsView::type LhsStlContainer;
5236 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
5237 if (lhs_stl_container == expected_)
5238 return true;
5239
5240 ::std::ostream* const os = listener->stream();
5241 if (os != nullptr) {
5242 // Something is different. Check for extra values first.
5243 bool printed_header = false;
5244 for (typename LhsStlContainer::const_iterator it =
5245 lhs_stl_container.begin();
5246 it != lhs_stl_container.end(); ++it) {
5247 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
5248 expected_.end()) {
5249 if (printed_header) {
5250 *os << ", ";
5251 } else {
5252 *os << "which has these unexpected elements: ";
5253 printed_header = true;
5254 }
5255 UniversalPrint(*it, os);
5256 }
5257 }
5258
5259 // Now check for missing values.
5260 bool printed_header2 = false;
5261 for (typename StlContainer::const_iterator it = expected_.begin();
5262 it != expected_.end(); ++it) {
5263 if (internal::ArrayAwareFind(
5264 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
5265 lhs_stl_container.end()) {
5266 if (printed_header2) {
5267 *os << ", ";
5268 } else {
5269 *os << (printed_header ? ",\nand" : "which")
5270 << " doesn't have these expected elements: ";
5271 printed_header2 = true;
5272 }
5273 UniversalPrint(*it, os);
5274 }
5275 }
5276 }
5277
5278 return false;
5279 }
5280
5281 private:
5282 const StlContainer expected_;
5283 };
5284
5285 // A comparator functor that uses the < operator to compare two values.
5286 struct LessComparator {
5287 template <typename T, typename U>
5288 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
5289 };
5290
5291 // Implements WhenSortedBy(comparator, container_matcher).
5292 template <typename Comparator, typename ContainerMatcher>
5293 class WhenSortedByMatcher {
5294 public:
5295 WhenSortedByMatcher(const Comparator& comparator,
5296 const ContainerMatcher& matcher)
5297 : comparator_(comparator), matcher_(matcher) {}
5298
5299 template <typename LhsContainer>
5300 operator Matcher<LhsContainer>() const {
5301 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
5302 }
5303
5304 template <typename LhsContainer>
5305 class Impl : public MatcherInterface<LhsContainer> {
5306 public:
5307 typedef internal::StlContainerView<
5308 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
5309 typedef typename LhsView::type LhsStlContainer;
5310 typedef typename LhsView::const_reference LhsStlContainerReference;
5311 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
5312 // so that we can match associative containers.
5313 typedef typename RemoveConstFromKey<
5314 typename LhsStlContainer::value_type>::type LhsValue;
5315
5316 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
5317 : comparator_(comparator), matcher_(matcher) {}
5318
5319 void DescribeTo(::std::ostream* os) const override {
5320 *os << "(when sorted) ";
5321 matcher_.DescribeTo(os);
5322 }
5323
5324 void DescribeNegationTo(::std::ostream* os) const override {
5325 *os << "(when sorted) ";
5326 matcher_.DescribeNegationTo(os);
5327 }
5328
5329 bool MatchAndExplain(LhsContainer lhs,
5330 MatchResultListener* listener) const override {
5331 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
5332 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
5333 lhs_stl_container.end());
5334 ::std::sort(
5335 sorted_container.begin(), sorted_container.end(), comparator_);
5336
5337 if (!listener->IsInterested()) {
5338 // If the listener is not interested, we do not need to
5339 // construct the inner explanation.
5340 return matcher_.Matches(sorted_container);
5341 }
5342
5343 *listener << "which is ";
5344 UniversalPrint(sorted_container, listener->stream());
5345 *listener << " when sorted";
5346
5347 StringMatchResultListener inner_listener;
5348 const bool match = matcher_.MatchAndExplain(sorted_container,
5349 &inner_listener);
5350 PrintIfNotEmpty(inner_listener.str(), listener->stream());
5351 return match;
5352 }
5353
5354 private:
5355 const Comparator comparator_;
5356 const Matcher<const ::std::vector<LhsValue>&> matcher_;
5357
5358 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
5359 };
5360
5361 private:
5362 const Comparator comparator_;
5363 const ContainerMatcher matcher_;
5364 };
5365
5366 // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
5367 // must be able to be safely cast to Matcher<std::tuple<const T1&, const
5368 // T2&> >, where T1 and T2 are the types of elements in the LHS
5369 // container and the RHS container respectively.
5370 template <typename TupleMatcher, typename RhsContainer>
5371 class PointwiseMatcher {
5372 GTEST_COMPILE_ASSERT_(
5373 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
5374 use_UnorderedPointwise_with_hash_tables);
5375
5376 public:
5377 typedef internal::StlContainerView<RhsContainer> RhsView;
5378 typedef typename RhsView::type RhsStlContainer;
5379 typedef typename RhsStlContainer::value_type RhsValue;
5380
5381 static_assert(!std::is_const<RhsContainer>::value,
5382 "RhsContainer type must not be const");
5383 static_assert(!std::is_reference<RhsContainer>::value,
5384 "RhsContainer type must not be a reference");
5385
5386 // Like ContainerEq, we make a copy of rhs in case the elements in
5387 // it are modified after this matcher is created.
5388 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
5389 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {}
5390
5391 template <typename LhsContainer>
5392 operator Matcher<LhsContainer>() const {
5393 GTEST_COMPILE_ASSERT_(
5394 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
5395 use_UnorderedPointwise_with_hash_tables);
5396
5397 return Matcher<LhsContainer>(
5398 new Impl<const LhsContainer&>(tuple_matcher_, rhs_));
5399 }
5400
5401 template <typename LhsContainer>
5402 class Impl : public MatcherInterface<LhsContainer> {
5403 public:
5404 typedef internal::StlContainerView<
5405 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
5406 typedef typename LhsView::type LhsStlContainer;
5407 typedef typename LhsView::const_reference LhsStlContainerReference;
5408 typedef typename LhsStlContainer::value_type LhsValue;
5409 // We pass the LHS value and the RHS value to the inner matcher by
5410 // reference, as they may be expensive to copy. We must use tuple
5411 // instead of pair here, as a pair cannot hold references (C++ 98,
5412 // 20.2.2 [lib.pairs]).
5413 typedef ::std::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
5414
5415 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
5416 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
5417 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
5418 rhs_(rhs) {}
5419
5420 void DescribeTo(::std::ostream* os) const override {
5421 *os << "contains " << rhs_.size()
5422 << " values, where each value and its corresponding value in ";
5423 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
5424 *os << " ";
5425 mono_tuple_matcher_.DescribeTo(os);
5426 }
5427 void DescribeNegationTo(::std::ostream* os) const override {
5428 *os << "doesn't contain exactly " << rhs_.size()
5429 << " values, or contains a value x at some index i"
5430 << " where x and the i-th value of ";
5431 UniversalPrint(rhs_, os);
5432 *os << " ";
5433 mono_tuple_matcher_.DescribeNegationTo(os);
5434 }
5435
5436 bool MatchAndExplain(LhsContainer lhs,
5437 MatchResultListener* listener) const override {
5438 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
5439 const size_t actual_size = lhs_stl_container.size();
5440 if (actual_size != rhs_.size()) {
5441 *listener << "which contains " << actual_size << " values";
5442 return false;
5443 }
5444
5445 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
5446 typename RhsStlContainer::const_iterator right = rhs_.begin();
5447 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
5448 if (listener->IsInterested()) {
5449 StringMatchResultListener inner_listener;
5450 // Create InnerMatcherArg as a temporarily object to avoid it outlives
5451 // *left and *right. Dereference or the conversion to `const T&` may
5452 // return temp objects, e.g for vector<bool>.
5453 if (!mono_tuple_matcher_.MatchAndExplain(
5454 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
5455 ImplicitCast_<const RhsValue&>(*right)),
5456 &inner_listener)) {
5457 *listener << "where the value pair (";
5458 UniversalPrint(*left, listener->stream());
5459 *listener << ", ";
5460 UniversalPrint(*right, listener->stream());
5461 *listener << ") at index #" << i << " don't match";
5462 PrintIfNotEmpty(inner_listener.str(), listener->stream());
5463 return false;
5464 }
5465 } else {
5466 if (!mono_tuple_matcher_.Matches(
5467 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
5468 ImplicitCast_<const RhsValue&>(*right))))
5469 return false;
5470 }
5471 }
5472
5473 return true;
5474 }
5475
5476 private:
5477 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
5478 const RhsStlContainer rhs_;
5479 };
5480
5481 private:
5482 const TupleMatcher tuple_matcher_;
5483 const RhsStlContainer rhs_;
5484 };
5485
5486 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
5487 template <typename Container>
5488 class QuantifierMatcherImpl : public MatcherInterface<Container> {
5489 public:
5490 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
5491 typedef StlContainerView<RawContainer> View;
5492 typedef typename View::type StlContainer;
5493 typedef typename View::const_reference StlContainerReference;
5494 typedef typename StlContainer::value_type Element;
5495
5496 template <typename InnerMatcher>
5497 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
5498 : inner_matcher_(
5499 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
5500
5501 // Checks whether:
5502 // * All elements in the container match, if all_elements_should_match.
5503 // * Any element in the container matches, if !all_elements_should_match.
5504 bool MatchAndExplainImpl(bool all_elements_should_match,
5505 Container container,
5506 MatchResultListener* listener) const {
5507 StlContainerReference stl_container = View::ConstReference(container);
5508 size_t i = 0;
5509 for (typename StlContainer::const_iterator it = stl_container.begin();
5510 it != stl_container.end(); ++it, ++i) {
5511 StringMatchResultListener inner_listener;
5512 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
5513
5514 if (matches != all_elements_should_match) {
5515 *listener << "whose element #" << i
5516 << (matches ? " matches" : " doesn't match");
5517 PrintIfNotEmpty(inner_listener.str(), listener->stream());
5518 return !all_elements_should_match;
5519 }
5520 }
5521 return all_elements_should_match;
5522 }
5523
5524 protected:
5525 const Matcher<const Element&> inner_matcher_;
5526 };
5527
5528 // Implements Contains(element_matcher) for the given argument type Container.
5529 // Symmetric to EachMatcherImpl.
5530 template <typename Container>
5531 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
5532 public:
5533 template <typename InnerMatcher>
5534 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
5535 : QuantifierMatcherImpl<Container>(inner_matcher) {}
5536
5537 // Describes what this matcher does.
5538 void DescribeTo(::std::ostream* os) const override {
5539 *os << "contains at least one element that ";
5540 this->inner_matcher_.DescribeTo(os);
5541 }
5542
5543 void DescribeNegationTo(::std::ostream* os) const override {
5544 *os << "doesn't contain any element that ";
5545 this->inner_matcher_.DescribeTo(os);
5546 }
5547
5548 bool MatchAndExplain(Container container,
5549 MatchResultListener* listener) const override {
5550 return this->MatchAndExplainImpl(false, container, listener);
5551 }
5552 };
5553
5554 // Implements Each(element_matcher) for the given argument type Container.
5555 // Symmetric to ContainsMatcherImpl.
5556 template <typename Container>
5557 class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
5558 public:
5559 template <typename InnerMatcher>
5560 explicit EachMatcherImpl(InnerMatcher inner_matcher)
5561 : QuantifierMatcherImpl<Container>(inner_matcher) {}
5562
5563 // Describes what this matcher does.
5564 void DescribeTo(::std::ostream* os) const override {
5565 *os << "only contains elements that ";
5566 this->inner_matcher_.DescribeTo(os);
5567 }
5568
5569 void DescribeNegationTo(::std::ostream* os) const override {
5570 *os << "contains some element that ";
5571 this->inner_matcher_.DescribeNegationTo(os);
5572 }
5573
5574 bool MatchAndExplain(Container container,
5575 MatchResultListener* listener) const override {
5576 return this->MatchAndExplainImpl(true, container, listener);
5577 }
5578 };
5579
5580 // Implements polymorphic Contains(element_matcher).
5581 template <typename M>
5582 class ContainsMatcher {
5583 public:
5584 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
5585
5586 template <typename Container>
5587 operator Matcher<Container>() const {
5588 return Matcher<Container>(
5589 new ContainsMatcherImpl<const Container&>(inner_matcher_));
5590 }
5591
5592 private:
5593 const M inner_matcher_;
5594 };
5595
5596 // Implements polymorphic Each(element_matcher).
5597 template <typename M>
5598 class EachMatcher {
5599 public:
5600 explicit EachMatcher(M m) : inner_matcher_(m) {}
5601
5602 template <typename Container>
5603 operator Matcher<Container>() const {
5604 return Matcher<Container>(
5605 new EachMatcherImpl<const Container&>(inner_matcher_));
5606 }
5607
5608 private:
5609 const M inner_matcher_;
5610 };
5611
5612 struct Rank1 {};
5613 struct Rank0 : Rank1 {};
5614
5615 namespace pair_getters {
5616 using std::get;
5617 template <typename T>
5618 auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
5619 return get<0>(x);
5620 }
5621 template <typename T>
5622 auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
5623 return x.first;
5624 }
5625
5626 template <typename T>
5627 auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
5628 return get<1>(x);
5629 }
5630 template <typename T>
5631 auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
5632 return x.second;
5633 }
5634 } // namespace pair_getters
5635
5636 // Implements Key(inner_matcher) for the given argument pair type.
5637 // Key(inner_matcher) matches an std::pair whose 'first' field matches
5638 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
5639 // std::map that contains at least one element whose key is >= 5.
5640 template <typename PairType>
5641 class KeyMatcherImpl : public MatcherInterface<PairType> {
5642 public:
5643 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
5644 typedef typename RawPairType::first_type KeyType;
5645
5646 template <typename InnerMatcher>
5647 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
5648 : inner_matcher_(
5649 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
5650 }
5651
5652 // Returns true if and only if 'key_value.first' (the key) matches the inner
5653 // matcher.
5654 bool MatchAndExplain(PairType key_value,
5655 MatchResultListener* listener) const override {
5656 StringMatchResultListener inner_listener;
5657 const bool match = inner_matcher_.MatchAndExplain(
5658 pair_getters::First(key_value, Rank0()), &inner_listener);
5659 const std::string explanation = inner_listener.str();
5660 if (explanation != "") {
5661 *listener << "whose first field is a value " << explanation;
5662 }
5663 return match;
5664 }
5665
5666 // Describes what this matcher does.
5667 void DescribeTo(::std::ostream* os) const override {
5668 *os << "has a key that ";
5669 inner_matcher_.DescribeTo(os);
5670 }
5671
5672 // Describes what the negation of this matcher does.
5673 void DescribeNegationTo(::std::ostream* os) const override {
5674 *os << "doesn't have a key that ";
5675 inner_matcher_.DescribeTo(os);
5676 }
5677
5678 private:
5679 const Matcher<const KeyType&> inner_matcher_;
5680 };
5681
5682 // Implements polymorphic Key(matcher_for_key).
5683 template <typename M>
5684 class KeyMatcher {
5685 public:
5686 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
5687
5688 template <typename PairType>
5689 operator Matcher<PairType>() const {
5690 return Matcher<PairType>(
5691 new KeyMatcherImpl<const PairType&>(matcher_for_key_));
5692 }
5693
5694 private:
5695 const M matcher_for_key_;
5696 };
5697
5698 // Implements polymorphic Address(matcher_for_address).
5699 template <typename InnerMatcher>
5700 class AddressMatcher {
5701 public:
5702 explicit AddressMatcher(InnerMatcher m) : matcher_(m) {}
5703
5704 template <typename Type>
5705 operator Matcher<Type>() const { // NOLINT
5706 return Matcher<Type>(new Impl<const Type&>(matcher_));
5707 }
5708
5709 private:
5710 // The monomorphic implementation that works for a particular object type.
5711 template <typename Type>
5712 class Impl : public MatcherInterface<Type> {
5713 public:
5714 using Address = const GTEST_REMOVE_REFERENCE_AND_CONST_(Type) *;
5715 explicit Impl(const InnerMatcher& matcher)
5716 : matcher_(MatcherCast<Address>(matcher)) {}
5717
5718 void DescribeTo(::std::ostream* os) const override {
5719 *os << "has address that ";
5720 matcher_.DescribeTo(os);
5721 }
5722
5723 void DescribeNegationTo(::std::ostream* os) const override {
5724 *os << "does not have address that ";
5725 matcher_.DescribeTo(os);
5726 }
5727
5728 bool MatchAndExplain(Type object,
5729 MatchResultListener* listener) const override {
5730 *listener << "which has address ";
5731 Address address = std::addressof(object);
5732 return MatchPrintAndExplain(address, matcher_, listener);
5733 }
5734
5735 private:
5736 const Matcher<Address> matcher_;
5737 };
5738 const InnerMatcher matcher_;
5739 };
5740
5741 // Implements Pair(first_matcher, second_matcher) for the given argument pair
5742 // type with its two matchers. See Pair() function below.
5743 template <typename PairType>
5744 class PairMatcherImpl : public MatcherInterface<PairType> {
5745 public:
5746 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
5747 typedef typename RawPairType::first_type FirstType;
5748 typedef typename RawPairType::second_type SecondType;
5749
5750 template <typename FirstMatcher, typename SecondMatcher>
5751 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
5752 : first_matcher_(
5753 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
5754 second_matcher_(
5755 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
5756 }
5757
5758 // Describes what this matcher does.
5759 void DescribeTo(::std::ostream* os) const override {
5760 *os << "has a first field that ";
5761 first_matcher_.DescribeTo(os);
5762 *os << ", and has a second field that ";
5763 second_matcher_.DescribeTo(os);
5764 }
5765
5766 // Describes what the negation of this matcher does.
5767 void DescribeNegationTo(::std::ostream* os) const override {
5768 *os << "has a first field that ";
5769 first_matcher_.DescribeNegationTo(os);
5770 *os << ", or has a second field that ";
5771 second_matcher_.DescribeNegationTo(os);
5772 }
5773
5774 // Returns true if and only if 'a_pair.first' matches first_matcher and
5775 // 'a_pair.second' matches second_matcher.
5776 bool MatchAndExplain(PairType a_pair,
5777 MatchResultListener* listener) const override {
5778 if (!listener->IsInterested()) {
5779 // If the listener is not interested, we don't need to construct the
5780 // explanation.
5781 return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
5782 second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
5783 }
5784 StringMatchResultListener first_inner_listener;
5785 if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
5786 &first_inner_listener)) {
5787 *listener << "whose first field does not match";
5788 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
5789 return false;
5790 }
5791 StringMatchResultListener second_inner_listener;
5792 if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
5793 &second_inner_listener)) {
5794 *listener << "whose second field does not match";
5795 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
5796 return false;
5797 }
5798 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
5799 listener);
5800 return true;
5801 }
5802
5803 private:
5804 void ExplainSuccess(const std::string& first_explanation,
5805 const std::string& second_explanation,
5806 MatchResultListener* listener) const {
5807 *listener << "whose both fields match";
5808 if (first_explanation != "") {
5809 *listener << ", where the first field is a value " << first_explanation;
5810 }
5811 if (second_explanation != "") {
5812 *listener << ", ";
5813 if (first_explanation != "") {
5814 *listener << "and ";
5815 } else {
5816 *listener << "where ";
5817 }
5818 *listener << "the second field is a value " << second_explanation;
5819 }
5820 }
5821
5822 const Matcher<const FirstType&> first_matcher_;
5823 const Matcher<const SecondType&> second_matcher_;
5824 };
5825
5826 // Implements polymorphic Pair(first_matcher, second_matcher).
5827 template <typename FirstMatcher, typename SecondMatcher>
5828 class PairMatcher {
5829 public:
5830 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
5831 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
5832
5833 template <typename PairType>
5834 operator Matcher<PairType> () const {
5835 return Matcher<PairType>(
5836 new PairMatcherImpl<const PairType&>(first_matcher_, second_matcher_));
5837 }
5838
5839 private:
5840 const FirstMatcher first_matcher_;
5841 const SecondMatcher second_matcher_;
5842 };
5843
5844 template <typename T, size_t... I>
5845 auto UnpackStructImpl(const T& t, IndexSequence<I...>, int)
5846 -> decltype(std::tie(get<I>(t)...)) {
5847 static_assert(std::tuple_size<T>::value == sizeof...(I),
5848 "Number of arguments doesn't match the number of fields.");
5849 return std::tie(get<I>(t)...);
5850 }
5851
5852 #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
5853 template <typename T>
5854 auto UnpackStructImpl(const T& t, MakeIndexSequence<1>, char) {
5855 const auto& [a] = t;
5856 return std::tie(a);
5857 }
5858 template <typename T>
5859 auto UnpackStructImpl(const T& t, MakeIndexSequence<2>, char) {
5860 const auto& [a, b] = t;
5861 return std::tie(a, b);
5862 }
5863 template <typename T>
5864 auto UnpackStructImpl(const T& t, MakeIndexSequence<3>, char) {
5865 const auto& [a, b, c] = t;
5866 return std::tie(a, b, c);
5867 }
5868 template <typename T>
5869 auto UnpackStructImpl(const T& t, MakeIndexSequence<4>, char) {
5870 const auto& [a, b, c, d] = t;
5871 return std::tie(a, b, c, d);
5872 }
5873 template <typename T>
5874 auto UnpackStructImpl(const T& t, MakeIndexSequence<5>, char) {
5875 const auto& [a, b, c, d, e] = t;
5876 return std::tie(a, b, c, d, e);
5877 }
5878 template <typename T>
5879 auto UnpackStructImpl(const T& t, MakeIndexSequence<6>, char) {
5880 const auto& [a, b, c, d, e, f] = t;
5881 return std::tie(a, b, c, d, e, f);
5882 }
5883 template <typename T>
5884 auto UnpackStructImpl(const T& t, MakeIndexSequence<7>, char) {
5885 const auto& [a, b, c, d, e, f, g] = t;
5886 return std::tie(a, b, c, d, e, f, g);
5887 }
5888 template <typename T>
5889 auto UnpackStructImpl(const T& t, MakeIndexSequence<8>, char) {
5890 const auto& [a, b, c, d, e, f, g, h] = t;
5891 return std::tie(a, b, c, d, e, f, g, h);
5892 }
5893 template <typename T>
5894 auto UnpackStructImpl(const T& t, MakeIndexSequence<9>, char) {
5895 const auto& [a, b, c, d, e, f, g, h, i] = t;
5896 return std::tie(a, b, c, d, e, f, g, h, i);
5897 }
5898 template <typename T>
5899 auto UnpackStructImpl(const T& t, MakeIndexSequence<10>, char) {
5900 const auto& [a, b, c, d, e, f, g, h, i, j] = t;
5901 return std::tie(a, b, c, d, e, f, g, h, i, j);
5902 }
5903 template <typename T>
5904 auto UnpackStructImpl(const T& t, MakeIndexSequence<11>, char) {
5905 const auto& [a, b, c, d, e, f, g, h, i, j, k] = t;
5906 return std::tie(a, b, c, d, e, f, g, h, i, j, k);
5907 }
5908 template <typename T>
5909 auto UnpackStructImpl(const T& t, MakeIndexSequence<12>, char) {
5910 const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t;
5911 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l);
5912 }
5913 template <typename T>
5914 auto UnpackStructImpl(const T& t, MakeIndexSequence<13>, char) {
5915 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t;
5916 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m);
5917 }
5918 template <typename T>
5919 auto UnpackStructImpl(const T& t, MakeIndexSequence<14>, char) {
5920 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t;
5921 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
5922 }
5923 template <typename T>
5924 auto UnpackStructImpl(const T& t, MakeIndexSequence<15>, char) {
5925 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t;
5926 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);
5927 }
5928 template <typename T>
5929 auto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) {
5930 const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;
5931 return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);
5932 }
5933 #endif // defined(__cpp_structured_bindings)
5934
5935 template <size_t I, typename T>
5936 auto UnpackStruct(const T& t)
5937 -> decltype((UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0)) {
5938 return (UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0);
5939 }
5940
5941 // Helper function to do comma folding in C++11.
5942 // The array ensures left-to-right order of evaluation.
5943 // Usage: VariadicExpand({expr...});
5944 template <typename T, size_t N>
5945 void VariadicExpand(const T (&)[N]) {}
5946
5947 template <typename Struct, typename StructSize>
5948 class FieldsAreMatcherImpl;
5949
5950 template <typename Struct, size_t... I>
5951 class FieldsAreMatcherImpl<Struct, IndexSequence<I...>>
5952 : public MatcherInterface<Struct> {
5953 using UnpackedType =
5954 decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>()));
5955 using MatchersType = std::tuple<
5956 Matcher<const typename std::tuple_element<I, UnpackedType>::type&>...>;
5957
5958 public:
5959 template <typename Inner>
5960 explicit FieldsAreMatcherImpl(const Inner& matchers)
5961 : matchers_(testing::SafeMatcherCast<
5962 const typename std::tuple_element<I, UnpackedType>::type&>(
5963 std::get<I>(matchers))...) {}
5964
5965 void DescribeTo(::std::ostream* os) const override {
5966 const char* separator = "";
5967 VariadicExpand(
5968 {(*os << separator << "has field #" << I << " that ",
5969 std::get<I>(matchers_).DescribeTo(os), separator = ", and ")...});
5970 }
5971
5972 void DescribeNegationTo(::std::ostream* os) const override {
5973 const char* separator = "";
5974 VariadicExpand({(*os << separator << "has field #" << I << " that ",
5975 std::get<I>(matchers_).DescribeNegationTo(os),
5976 separator = ", or ")...});
5977 }
5978
5979 bool MatchAndExplain(Struct t, MatchResultListener* listener) const override {
5980 return MatchInternal((UnpackStruct<sizeof...(I)>)(t), listener);
5981 }
5982
5983 private:
5984 bool MatchInternal(UnpackedType tuple, MatchResultListener* listener) const {
5985 if (!listener->IsInterested()) {
5986 // If the listener is not interested, we don't need to construct the
5987 // explanation.
5988 bool good = true;
5989 VariadicExpand({good = good && std::get<I>(matchers_).Matches(
5990 std::get<I>(tuple))...});
5991 return good;
5992 }
5993
5994 size_t failed_pos = ~size_t{};
5995
5996 std::vector<StringMatchResultListener> inner_listener(sizeof...(I));
5997
5998 VariadicExpand(
5999 {failed_pos == ~size_t{} && !std::get<I>(matchers_).MatchAndExplain(
6000 std::get<I>(tuple), &inner_listener[I])
6001 ? failed_pos = I
6002 : 0 ...});
6003 if (failed_pos != ~size_t{}) {
6004 *listener << "whose field #" << failed_pos << " does not match";
6005 PrintIfNotEmpty(inner_listener[failed_pos].str(), listener->stream());
6006 return false;
6007 }
6008
6009 *listener << "whose all elements match";
6010 const char* separator = ", where";
6011 for (size_t index = 0; index < sizeof...(I); ++index) {
6012 const std::string str = inner_listener[index].str();
6013 if (!str.empty()) {
6014 *listener << separator << " field #" << index << " is a value " << str;
6015 separator = ", and";
6016 }
6017 }
6018
6019 return true;
6020 }
6021
6022 MatchersType matchers_;
6023 };
6024
6025 template <typename... Inner>
6026 class FieldsAreMatcher {
6027 public:
6028 explicit FieldsAreMatcher(Inner... inner) : matchers_(std::move(inner)...) {}
6029
6030 template <typename Struct>
6031 operator Matcher<Struct>() const { // NOLINT
6032 return Matcher<Struct>(
6033 new FieldsAreMatcherImpl<const Struct&, IndexSequenceFor<Inner...>>(
6034 matchers_));
6035 }
6036
6037 private:
6038 std::tuple<Inner...> matchers_;
6039 };
6040
6041 // Implements ElementsAre() and ElementsAreArray().
6042 template <typename Container>
6043 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
6044 public:
6045 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6046 typedef internal::StlContainerView<RawContainer> View;
6047 typedef typename View::type StlContainer;
6048 typedef typename View::const_reference StlContainerReference;
6049 typedef typename StlContainer::value_type Element;
6050
6051 // Constructs the matcher from a sequence of element values or
6052 // element matchers.
6053 template <typename InputIter>
6054 ElementsAreMatcherImpl(InputIter first, InputIter last) {
6055 while (first != last) {
6056 matchers_.push_back(MatcherCast<const Element&>(*first++));
6057 }
6058 }
6059
6060 // Describes what this matcher does.
6061 void DescribeTo(::std::ostream* os) const override {
6062 if (count() == 0) {
6063 *os << "is empty";
6064 } else if (count() == 1) {
6065 *os << "has 1 element that ";
6066 matchers_[0].DescribeTo(os);
6067 } else {
6068 *os << "has " << Elements(count()) << " where\n";
6069 for (size_t i = 0; i != count(); ++i) {
6070 *os << "element #" << i << " ";
6071 matchers_[i].DescribeTo(os);
6072 if (i + 1 < count()) {
6073 *os << ",\n";
6074 }
6075 }
6076 }
6077 }
6078
6079 // Describes what the negation of this matcher does.
6080 void DescribeNegationTo(::std::ostream* os) const override {
6081 if (count() == 0) {
6082 *os << "isn't empty";
6083 return;
6084 }
6085
6086 *os << "doesn't have " << Elements(count()) << ", or\n";
6087 for (size_t i = 0; i != count(); ++i) {
6088 *os << "element #" << i << " ";
6089 matchers_[i].DescribeNegationTo(os);
6090 if (i + 1 < count()) {
6091 *os << ", or\n";
6092 }
6093 }
6094 }
6095
6096 bool MatchAndExplain(Container container,
6097 MatchResultListener* listener) const override {
6098 // To work with stream-like "containers", we must only walk
6099 // through the elements in one pass.
6100
6101 const bool listener_interested = listener->IsInterested();
6102
6103 // explanations[i] is the explanation of the element at index i.
6104 ::std::vector<std::string> explanations(count());
6105 StlContainerReference stl_container = View::ConstReference(container);
6106 typename StlContainer::const_iterator it = stl_container.begin();
6107 size_t exam_pos = 0;
6108 bool mismatch_found = false; // Have we found a mismatched element yet?
6109
6110 // Go through the elements and matchers in pairs, until we reach
6111 // the end of either the elements or the matchers, or until we find a
6112 // mismatch.
6113 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
6114 bool match; // Does the current element match the current matcher?
6115 if (listener_interested) {
6116 StringMatchResultListener s;
6117 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
6118 explanations[exam_pos] = s.str();
6119 } else {
6120 match = matchers_[exam_pos].Matches(*it);
6121 }
6122
6123 if (!match) {
6124 mismatch_found = true;
6125 break;
6126 }
6127 }
6128 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
6129
6130 // Find how many elements the actual container has. We avoid
6131 // calling size() s.t. this code works for stream-like "containers"
6132 // that don't define size().
6133 size_t actual_count = exam_pos;
6134 for (; it != stl_container.end(); ++it) {
6135 ++actual_count;
6136 }
6137
6138 if (actual_count != count()) {
6139 // The element count doesn't match. If the container is empty,
6140 // there's no need to explain anything as Google Mock already
6141 // prints the empty container. Otherwise we just need to show
6142 // how many elements there actually are.
6143 if (listener_interested && (actual_count != 0)) {
6144 *listener << "which has " << Elements(actual_count);
6145 }
6146 return false;
6147 }
6148
6149 if (mismatch_found) {
6150 // The element count matches, but the exam_pos-th element doesn't match.
6151 if (listener_interested) {
6152 *listener << "whose element #" << exam_pos << " doesn't match";
6153 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
6154 }
6155 return false;
6156 }
6157
6158 // Every element matches its expectation. We need to explain why
6159 // (the obvious ones can be skipped).
6160 if (listener_interested) {
6161 bool reason_printed = false;
6162 for (size_t i = 0; i != count(); ++i) {
6163 const std::string& s = explanations[i];
6164 if (!s.empty()) {
6165 if (reason_printed) {
6166 *listener << ",\nand ";
6167 }
6168 *listener << "whose element #" << i << " matches, " << s;
6169 reason_printed = true;
6170 }
6171 }
6172 }
6173 return true;
6174 }
6175
6176 private:
6177 static Message Elements(size_t count) {
6178 return Message() << count << (count == 1 ? " element" : " elements");
6179 }
6180
6181 size_t count() const { return matchers_.size(); }
6182
6183 ::std::vector<Matcher<const Element&> > matchers_;
6184 };
6185
6186 // Connectivity matrix of (elements X matchers), in element-major order.
6187 // Initially, there are no edges.
6188 // Use NextGraph() to iterate over all possible edge configurations.
6189 // Use Randomize() to generate a random edge configuration.
6190 class GTEST_API_ MatchMatrix {
6191 public:
6192 MatchMatrix(size_t num_elements, size_t num_matchers)
6193 : num_elements_(num_elements),
6194 num_matchers_(num_matchers),
6195 matched_(num_elements_* num_matchers_, 0) {
6196 }
6197
6198 size_t LhsSize() const { return num_elements_; }
6199 size_t RhsSize() const { return num_matchers_; }
6200 bool HasEdge(size_t ilhs, size_t irhs) const {
6201 return matched_[SpaceIndex(ilhs, irhs)] == 1;
6202 }
6203 void SetEdge(size_t ilhs, size_t irhs, bool b) {
6204 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
6205 }
6206
6207 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
6208 // adds 1 to that number; returns false if incrementing the graph left it
6209 // empty.
6210 bool NextGraph();
6211
6212 void Randomize();
6213
6214 std::string DebugString() const;
6215
6216 private:
6217 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
6218 return ilhs * num_matchers_ + irhs;
6219 }
6220
6221 size_t num_elements_;
6222 size_t num_matchers_;
6223
6224 // Each element is a char interpreted as bool. They are stored as a
6225 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
6226 // a (ilhs, irhs) matrix coordinate into an offset.
6227 ::std::vector<char> matched_;
6228 };
6229
6230 typedef ::std::pair<size_t, size_t> ElementMatcherPair;
6231 typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
6232
6233 // Returns a maximum bipartite matching for the specified graph 'g'.
6234 // The matching is represented as a vector of {element, matcher} pairs.
6235 GTEST_API_ ElementMatcherPairs
6236 FindMaxBipartiteMatching(const MatchMatrix& g);
6237
6238 struct UnorderedMatcherRequire {
6239 enum Flags {
6240 Superset = 1 << 0,
6241 Subset = 1 << 1,
6242 ExactMatch = Superset | Subset,
6243 };
6244 };
6245
6246 // Untyped base class for implementing UnorderedElementsAre. By
6247 // putting logic that's not specific to the element type here, we
6248 // reduce binary bloat and increase compilation speed.
6249 class GTEST_API_ UnorderedElementsAreMatcherImplBase {
6250 protected:
6251 explicit UnorderedElementsAreMatcherImplBase(
6252 UnorderedMatcherRequire::Flags matcher_flags)
6253 : match_flags_(matcher_flags) {}
6254
6255 // A vector of matcher describers, one for each element matcher.
6256 // Does not own the describers (and thus can be used only when the
6257 // element matchers are alive).
6258 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
6259
6260 // Describes this UnorderedElementsAre matcher.
6261 void DescribeToImpl(::std::ostream* os) const;
6262
6263 // Describes the negation of this UnorderedElementsAre matcher.
6264 void DescribeNegationToImpl(::std::ostream* os) const;
6265
6266 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
6267 const MatchMatrix& matrix,
6268 MatchResultListener* listener) const;
6269
6270 bool FindPairing(const MatchMatrix& matrix,
6271 MatchResultListener* listener) const;
6272
6273 MatcherDescriberVec& matcher_describers() {
6274 return matcher_describers_;
6275 }
6276
6277 static Message Elements(size_t n) {
6278 return Message() << n << " element" << (n == 1 ? "" : "s");
6279 }
6280
6281 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
6282
6283 private:
6284 UnorderedMatcherRequire::Flags match_flags_;
6285 MatcherDescriberVec matcher_describers_;
6286 };
6287
6288 // Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
6289 // IsSupersetOf.
6290 template <typename Container>
6291 class UnorderedElementsAreMatcherImpl
6292 : public MatcherInterface<Container>,
6293 public UnorderedElementsAreMatcherImplBase {
6294 public:
6295 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6296 typedef internal::StlContainerView<RawContainer> View;
6297 typedef typename View::type StlContainer;
6298 typedef typename View::const_reference StlContainerReference;
6299 typedef typename StlContainer::const_iterator StlContainerConstIterator;
6300 typedef typename StlContainer::value_type Element;
6301
6302 template <typename InputIter>
6303 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
6304 InputIter first, InputIter last)
6305 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
6306 for (; first != last; ++first) {
6307 matchers_.push_back(MatcherCast<const Element&>(*first));
6308 }
6309 for (const auto& m : matchers_) {
6310 matcher_describers().push_back(m.GetDescriber());
6311 }
6312 }
6313
6314 // Describes what this matcher does.
6315 void DescribeTo(::std::ostream* os) const override {
6316 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
6317 }
6318
6319 // Describes what the negation of this matcher does.
6320 void DescribeNegationTo(::std::ostream* os) const override {
6321 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
6322 }
6323
6324 bool MatchAndExplain(Container container,
6325 MatchResultListener* listener) const override {
6326 StlContainerReference stl_container = View::ConstReference(container);
6327 ::std::vector<std::string> element_printouts;
6328 MatchMatrix matrix =
6329 AnalyzeElements(stl_container.begin(), stl_container.end(),
6330 &element_printouts, listener);
6331
6332 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
6333 return true;
6334 }
6335
6336 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
6337 if (matrix.LhsSize() != matrix.RhsSize()) {
6338 // The element count doesn't match. If the container is empty,
6339 // there's no need to explain anything as Google Mock already
6340 // prints the empty container. Otherwise we just need to show
6341 // how many elements there actually are.
6342 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
6343 *listener << "which has " << Elements(matrix.LhsSize());
6344 }
6345 return false;
6346 }
6347 }
6348
6349 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
6350 FindPairing(matrix, listener);
6351 }
6352
6353 private:
6354 template <typename ElementIter>
6355 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
6356 ::std::vector<std::string>* element_printouts,
6357 MatchResultListener* listener) const {
6358 element_printouts->clear();
6359 ::std::vector<char> did_match;
6360 size_t num_elements = 0;
6361 DummyMatchResultListener dummy;
6362 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
6363 if (listener->IsInterested()) {
6364 element_printouts->push_back(PrintToString(*elem_first));
6365 }
6366 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
6367 did_match.push_back(
6368 matchers_[irhs].MatchAndExplain(*elem_first, &dummy));
6369 }
6370 }
6371
6372 MatchMatrix matrix(num_elements, matchers_.size());
6373 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
6374 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
6375 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
6376 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
6377 }
6378 }
6379 return matrix;
6380 }
6381
6382 ::std::vector<Matcher<const Element&> > matchers_;
6383 };
6384
6385 // Functor for use in TransformTuple.
6386 // Performs MatcherCast<Target> on an input argument of any type.
6387 template <typename Target>
6388 struct CastAndAppendTransform {
6389 template <typename Arg>
6390 Matcher<Target> operator()(const Arg& a) const {
6391 return MatcherCast<Target>(a);
6392 }
6393 };
6394
6395 // Implements UnorderedElementsAre.
6396 template <typename MatcherTuple>
6397 class UnorderedElementsAreMatcher {
6398 public:
6399 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
6400 : matchers_(args) {}
6401
6402 template <typename Container>
6403 operator Matcher<Container>() const {
6404 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6405 typedef typename internal::StlContainerView<RawContainer>::type View;
6406 typedef typename View::value_type Element;
6407 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
6408 MatcherVec matchers;
6409 matchers.reserve(::std::tuple_size<MatcherTuple>::value);
6410 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
6411 ::std::back_inserter(matchers));
6412 return Matcher<Container>(
6413 new UnorderedElementsAreMatcherImpl<const Container&>(
6414 UnorderedMatcherRequire::ExactMatch, matchers.begin(),
6415 matchers.end()));
6416 }
6417
6418 private:
6419 const MatcherTuple matchers_;
6420 };
6421
6422 // Implements ElementsAre.
6423 template <typename MatcherTuple>
6424 class ElementsAreMatcher {
6425 public:
6426 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
6427
6428 template <typename Container>
6429 operator Matcher<Container>() const {
6430 GTEST_COMPILE_ASSERT_(
6431 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
6432 ::std::tuple_size<MatcherTuple>::value < 2,
6433 use_UnorderedElementsAre_with_hash_tables);
6434
6435 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
6436 typedef typename internal::StlContainerView<RawContainer>::type View;
6437 typedef typename View::value_type Element;
6438 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
6439 MatcherVec matchers;
6440 matchers.reserve(::std::tuple_size<MatcherTuple>::value);
6441 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
6442 ::std::back_inserter(matchers));
6443 return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(
6444 matchers.begin(), matchers.end()));
6445 }
6446
6447 private:
6448 const MatcherTuple matchers_;
6449 };
6450
6451 // Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
6452 template <typename T>
6453 class UnorderedElementsAreArrayMatcher {
6454 public:
6455 template <typename Iter>
6456 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
6457 Iter first, Iter last)
6458 : match_flags_(match_flags), matchers_(first, last) {}
6459
6460 template <typename Container>
6461 operator Matcher<Container>() const {
6462 return Matcher<Container>(
6463 new UnorderedElementsAreMatcherImpl<const Container&>(
6464 match_flags_, matchers_.begin(), matchers_.end()));
6465 }
6466
6467 private:
6468 UnorderedMatcherRequire::Flags match_flags_;
6469 ::std::vector<T> matchers_;
6470 };
6471
6472 // Implements ElementsAreArray().
6473 template <typename T>
6474 class ElementsAreArrayMatcher {
6475 public:
6476 template <typename Iter>
6477 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
6478
6479 template <typename Container>
6480 operator Matcher<Container>() const {
6481 GTEST_COMPILE_ASSERT_(
6482 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
6483 use_UnorderedElementsAreArray_with_hash_tables);
6484
6485 return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(
6486 matchers_.begin(), matchers_.end()));
6487 }
6488
6489 private:
6490 const ::std::vector<T> matchers_;
6491 };
6492
6493 // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
6494 // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
6495 // second) is a polymorphic matcher that matches a value x if and only if
6496 // tm matches tuple (x, second). Useful for implementing
6497 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
6498 //
6499 // BoundSecondMatcher is copyable and assignable, as we need to put
6500 // instances of this class in a vector when implementing
6501 // UnorderedPointwise().
6502 template <typename Tuple2Matcher, typename Second>
6503 class BoundSecondMatcher {
6504 public:
6505 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
6506 : tuple2_matcher_(tm), second_value_(second) {}
6507
6508 BoundSecondMatcher(const BoundSecondMatcher& other) = default;
6509
6510 template <typename T>
6511 operator Matcher<T>() const {
6512 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
6513 }
6514
6515 // We have to define this for UnorderedPointwise() to compile in
6516 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
6517 // which requires the elements to be assignable in C++98. The
6518 // compiler cannot generate the operator= for us, as Tuple2Matcher
6519 // and Second may not be assignable.
6520 //
6521 // However, this should never be called, so the implementation just
6522 // need to assert.
6523 void operator=(const BoundSecondMatcher& /*rhs*/) {
6524 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
6525 }
6526
6527 private:
6528 template <typename T>
6529 class Impl : public MatcherInterface<T> {
6530 public:
6531 typedef ::std::tuple<T, Second> ArgTuple;
6532
6533 Impl(const Tuple2Matcher& tm, const Second& second)
6534 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
6535 second_value_(second) {}
6536
6537 void DescribeTo(::std::ostream* os) const override {
6538 *os << "and ";
6539 UniversalPrint(second_value_, os);
6540 *os << " ";
6541 mono_tuple2_matcher_.DescribeTo(os);
6542 }
6543
6544 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
6545 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
6546 listener);
6547 }
6548
6549 private:
6550 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
6551 const Second second_value_;
6552 };
6553
6554 const Tuple2Matcher tuple2_matcher_;
6555 const Second second_value_;
6556 };
6557
6558 // Given a 2-tuple matcher tm and a value second,
6559 // MatcherBindSecond(tm, second) returns a matcher that matches a
6560 // value x if and only if tm matches tuple (x, second). Useful for
6561 // implementing UnorderedPointwise() in terms of UnorderedElementsAreArray().
6562 template <typename Tuple2Matcher, typename Second>
6563 BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
6564 const Tuple2Matcher& tm, const Second& second) {
6565 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
6566 }
6567
6568 // Returns the description for a matcher defined using the MATCHER*()
6569 // macro where the user-supplied description string is "", if
6570 // 'negation' is false; otherwise returns the description of the
6571 // negation of the matcher. 'param_values' contains a list of strings
6572 // that are the print-out of the matcher's parameters.
6573 GTEST_API_ std::string FormatMatcherDescription(bool negation,
6574 const char* matcher_name,
6575 const Strings& param_values);
6576
6577 // Implements a matcher that checks the value of a optional<> type variable.
6578 template <typename ValueMatcher>
6579 class OptionalMatcher {
6580 public:
6581 explicit OptionalMatcher(const ValueMatcher& value_matcher)
6582 : value_matcher_(value_matcher) {}
6583
6584 template <typename Optional>
6585 operator Matcher<Optional>() const {
6586 return Matcher<Optional>(new Impl<const Optional&>(value_matcher_));
6587 }
6588
6589 template <typename Optional>
6590 class Impl : public MatcherInterface<Optional> {
6591 public:
6592 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
6593 typedef typename OptionalView::value_type ValueType;
6594 explicit Impl(const ValueMatcher& value_matcher)
6595 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
6596
6597 void DescribeTo(::std::ostream* os) const override {
6598 *os << "value ";
6599 value_matcher_.DescribeTo(os);
6600 }
6601
6602 void DescribeNegationTo(::std::ostream* os) const override {
6603 *os << "value ";
6604 value_matcher_.DescribeNegationTo(os);
6605 }
6606
6607 bool MatchAndExplain(Optional optional,
6608 MatchResultListener* listener) const override {
6609 if (!optional) {
6610 *listener << "which is not engaged";
6611 return false;
6612 }
6613 const ValueType& value = *optional;
6614 StringMatchResultListener value_listener;
6615 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
6616 *listener << "whose value " << PrintToString(value)
6617 << (match ? " matches" : " doesn't match");
6618 PrintIfNotEmpty(value_listener.str(), listener->stream());
6619 return match;
6620 }
6621
6622 private:
6623 const Matcher<ValueType> value_matcher_;
6624 };
6625
6626 private:
6627 const ValueMatcher value_matcher_;
6628 };
6629
6630 namespace variant_matcher {
6631 // Overloads to allow VariantMatcher to do proper ADL lookup.
6632 template <typename T>
6633 void holds_alternative() {}
6634 template <typename T>
6635 void get() {}
6636
6637 // Implements a matcher that checks the value of a variant<> type variable.
6638 template <typename T>
6639 class VariantMatcher {
6640 public:
6641 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
6642 : matcher_(std::move(matcher)) {}
6643
6644 template <typename Variant>
6645 bool MatchAndExplain(const Variant& value,
6646 ::testing::MatchResultListener* listener) const {
6647 using std::get;
6648 if (!listener->IsInterested()) {
6649 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
6650 }
6651
6652 if (!holds_alternative<T>(value)) {
6653 *listener << "whose value is not of type '" << GetTypeName() << "'";
6654 return false;
6655 }
6656
6657 const T& elem = get<T>(value);
6658 StringMatchResultListener elem_listener;
6659 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
6660 *listener << "whose value " << PrintToString(elem)
6661 << (match ? " matches" : " doesn't match");
6662 PrintIfNotEmpty(elem_listener.str(), listener->stream());
6663 return match;
6664 }
6665
6666 void DescribeTo(std::ostream* os) const {
6667 *os << "is a variant<> with value of type '" << GetTypeName()
6668 << "' and the value ";
6669 matcher_.DescribeTo(os);
6670 }
6671
6672 void DescribeNegationTo(std::ostream* os) const {
6673 *os << "is a variant<> with value of type other than '" << GetTypeName()
6674 << "' or the value ";
6675 matcher_.DescribeNegationTo(os);
6676 }
6677
6678 private:
6679 static std::string GetTypeName() {
6680 #if GTEST_HAS_RTTI
6681 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
6682 return internal::GetTypeName<T>());
6683 #endif
6684 return "the element type";
6685 }
6686
6687 const ::testing::Matcher<const T&> matcher_;
6688 };
6689
6690 } // namespace variant_matcher
6691
6692 namespace any_cast_matcher {
6693
6694 // Overloads to allow AnyCastMatcher to do proper ADL lookup.
6695 template <typename T>
6696 void any_cast() {}
6697
6698 // Implements a matcher that any_casts the value.
6699 template <typename T>
6700 class AnyCastMatcher {
6701 public:
6702 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
6703 : matcher_(matcher) {}
6704
6705 template <typename AnyType>
6706 bool MatchAndExplain(const AnyType& value,
6707 ::testing::MatchResultListener* listener) const {
6708 if (!listener->IsInterested()) {
6709 const T* ptr = any_cast<T>(&value);
6710 return ptr != nullptr && matcher_.Matches(*ptr);
6711 }
6712
6713 const T* elem = any_cast<T>(&value);
6714 if (elem == nullptr) {
6715 *listener << "whose value is not of type '" << GetTypeName() << "'";
6716 return false;
6717 }
6718
6719 StringMatchResultListener elem_listener;
6720 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
6721 *listener << "whose value " << PrintToString(*elem)
6722 << (match ? " matches" : " doesn't match");
6723 PrintIfNotEmpty(elem_listener.str(), listener->stream());
6724 return match;
6725 }
6726
6727 void DescribeTo(std::ostream* os) const {
6728 *os << "is an 'any' type with value of type '" << GetTypeName()
6729 << "' and the value ";
6730 matcher_.DescribeTo(os);
6731 }
6732
6733 void DescribeNegationTo(std::ostream* os) const {
6734 *os << "is an 'any' type with value of type other than '" << GetTypeName()
6735 << "' or the value ";
6736 matcher_.DescribeNegationTo(os);
6737 }
6738
6739 private:
6740 static std::string GetTypeName() {
6741 #if GTEST_HAS_RTTI
6742 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
6743 return internal::GetTypeName<T>());
6744 #endif
6745 return "the element type";
6746 }
6747
6748 const ::testing::Matcher<const T&> matcher_;
6749 };
6750
6751 } // namespace any_cast_matcher
6752
6753 // Implements the Args() matcher.
6754 template <class ArgsTuple, size_t... k>
6755 class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
6756 public:
6757 using RawArgsTuple = typename std::decay<ArgsTuple>::type;
6758 using SelectedArgs =
6759 std::tuple<typename std::tuple_element<k, RawArgsTuple>::type...>;
6760 using MonomorphicInnerMatcher = Matcher<const SelectedArgs&>;
6761
6762 template <typename InnerMatcher>
6763 explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)
6764 : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}
6765
6766 bool MatchAndExplain(ArgsTuple args,
6767 MatchResultListener* listener) const override {
6768 // Workaround spurious C4100 on MSVC<=15.7 when k is empty.
6769 (void)args;
6770 const SelectedArgs& selected_args =
6771 std::forward_as_tuple(std::get<k>(args)...);
6772 if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args);
6773
6774 PrintIndices(listener->stream());
6775 *listener << "are " << PrintToString(selected_args);
6776
6777 StringMatchResultListener inner_listener;
6778 const bool match =
6779 inner_matcher_.MatchAndExplain(selected_args, &inner_listener);
6780 PrintIfNotEmpty(inner_listener.str(), listener->stream());
6781 return match;
6782 }
6783
6784 void DescribeTo(::std::ostream* os) const override {
6785 *os << "are a tuple ";
6786 PrintIndices(os);
6787 inner_matcher_.DescribeTo(os);
6788 }
6789
6790 void DescribeNegationTo(::std::ostream* os) const override {
6791 *os << "are a tuple ";
6792 PrintIndices(os);
6793 inner_matcher_.DescribeNegationTo(os);
6794 }
6795
6796 private:
6797 // Prints the indices of the selected fields.
6798 static void PrintIndices(::std::ostream* os) {
6799 *os << "whose fields (";
6800 const char* sep = "";
6801 // Workaround spurious C4189 on MSVC<=15.7 when k is empty.
6802 (void)sep;
6803 const char* dummy[] = {"", (*os << sep << "#" << k, sep = ", ")...};
6804 (void)dummy;
6805 *os << ") ";
6806 }
6807
6808 MonomorphicInnerMatcher inner_matcher_;
6809 };
6810
6811 template <class InnerMatcher, size_t... k>
6812 class ArgsMatcher {
6813 public:
6814 explicit ArgsMatcher(InnerMatcher inner_matcher)
6815 : inner_matcher_(std::move(inner_matcher)) {}
6816
6817 template <typename ArgsTuple>
6818 operator Matcher<ArgsTuple>() const { // NOLINT
6819 return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k...>(inner_matcher_));
6820 }
6821
6822 private:
6823 InnerMatcher inner_matcher_;
6824 };
6825
6826 } // namespace internal
6827
6828 // ElementsAreArray(iterator_first, iterator_last)
6829 // ElementsAreArray(pointer, count)
6830 // ElementsAreArray(array)
6831 // ElementsAreArray(container)
6832 // ElementsAreArray({ e1, e2, ..., en })
6833 //
6834 // The ElementsAreArray() functions are like ElementsAre(...), except
6835 // that they are given a homogeneous sequence rather than taking each
6836 // element as a function argument. The sequence can be specified as an
6837 // array, a pointer and count, a vector, an initializer list, or an
6838 // STL iterator range. In each of these cases, the underlying sequence
6839 // can be either a sequence of values or a sequence of matchers.
6840 //
6841 // All forms of ElementsAreArray() make a copy of the input matcher sequence.
6842
6843 template <typename Iter>
6844 inline internal::ElementsAreArrayMatcher<
6845 typename ::std::iterator_traits<Iter>::value_type>
6846 ElementsAreArray(Iter first, Iter last) {
6847 typedef typename ::std::iterator_traits<Iter>::value_type T;
6848 return internal::ElementsAreArrayMatcher<T>(first, last);
6849 }
6850
6851 template <typename T>
6852 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
6853 const T* pointer, size_t count) {
6854 return ElementsAreArray(pointer, pointer + count);
6855 }
6856
6857 template <typename T, size_t N>
6858 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
6859 const T (&array)[N]) {
6860 return ElementsAreArray(array, N);
6861 }
6862
6863 template <typename Container>
6864 inline internal::ElementsAreArrayMatcher<typename Container::value_type>
6865 ElementsAreArray(const Container& container) {
6866 return ElementsAreArray(container.begin(), container.end());
6867 }
6868
6869 template <typename T>
6870 inline internal::ElementsAreArrayMatcher<T>
6871 ElementsAreArray(::std::initializer_list<T> xs) {
6872 return ElementsAreArray(xs.begin(), xs.end());
6873 }
6874
6875 // UnorderedElementsAreArray(iterator_first, iterator_last)
6876 // UnorderedElementsAreArray(pointer, count)
6877 // UnorderedElementsAreArray(array)
6878 // UnorderedElementsAreArray(container)
6879 // UnorderedElementsAreArray({ e1, e2, ..., en })
6880 //
6881 // UnorderedElementsAreArray() verifies that a bijective mapping onto a
6882 // collection of matchers exists.
6883 //
6884 // The matchers can be specified as an array, a pointer and count, a container,
6885 // an initializer list, or an STL iterator range. In each of these cases, the
6886 // underlying matchers can be either values or matchers.
6887
6888 template <typename Iter>
6889 inline internal::UnorderedElementsAreArrayMatcher<
6890 typename ::std::iterator_traits<Iter>::value_type>
6891 UnorderedElementsAreArray(Iter first, Iter last) {
6892 typedef typename ::std::iterator_traits<Iter>::value_type T;
6893 return internal::UnorderedElementsAreArrayMatcher<T>(
6894 internal::UnorderedMatcherRequire::ExactMatch, first, last);
6895 }
6896
6897 template <typename T>
6898 inline internal::UnorderedElementsAreArrayMatcher<T>
6899 UnorderedElementsAreArray(const T* pointer, size_t count) {
6900 return UnorderedElementsAreArray(pointer, pointer + count);
6901 }
6902
6903 template <typename T, size_t N>
6904 inline internal::UnorderedElementsAreArrayMatcher<T>
6905 UnorderedElementsAreArray(const T (&array)[N]) {
6906 return UnorderedElementsAreArray(array, N);
6907 }
6908
6909 template <typename Container>
6910 inline internal::UnorderedElementsAreArrayMatcher<
6911 typename Container::value_type>
6912 UnorderedElementsAreArray(const Container& container) {
6913 return UnorderedElementsAreArray(container.begin(), container.end());
6914 }
6915
6916 template <typename T>
6917 inline internal::UnorderedElementsAreArrayMatcher<T>
6918 UnorderedElementsAreArray(::std::initializer_list<T> xs) {
6919 return UnorderedElementsAreArray(xs.begin(), xs.end());
6920 }
6921
6922 // _ is a matcher that matches anything of any type.
6923 //
6924 // This definition is fine as:
6925 //
6926 // 1. The C++ standard permits using the name _ in a namespace that
6927 // is not the global namespace or ::std.
6928 // 2. The AnythingMatcher class has no data member or constructor,
6929 // so it's OK to create global variables of this type.
6930 // 3. c-style has approved of using _ in this case.
6931 const internal::AnythingMatcher _ = {};
6932 // Creates a matcher that matches any value of the given type T.
6933 template <typename T>
6934 inline Matcher<T> A() {
6935 return _;
6936 }
6937
6938 // Creates a matcher that matches any value of the given type T.
6939 template <typename T>
6940 inline Matcher<T> An() {
6941 return _;
6942 }
6943
6944 template <typename T, typename M>
6945 Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
6946 const M& value, std::false_type /* convertible_to_matcher */,
6947 std::false_type /* convertible_to_T */) {
6948 return Eq(value);
6949 }
6950
6951 // Creates a polymorphic matcher that matches any NULL pointer.
6952 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
6953 return MakePolymorphicMatcher(internal::IsNullMatcher());
6954 }
6955
6956 // Creates a polymorphic matcher that matches any non-NULL pointer.
6957 // This is convenient as Not(NULL) doesn't compile (the compiler
6958 // thinks that that expression is comparing a pointer with an integer).
6959 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
6960 return MakePolymorphicMatcher(internal::NotNullMatcher());
6961 }
6962
6963 // Creates a polymorphic matcher that matches any argument that
6964 // references variable x.
6965 template <typename T>
6966 inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
6967 return internal::RefMatcher<T&>(x);
6968 }
6969
6970 // Creates a polymorphic matcher that matches any NaN floating point.
6971 inline PolymorphicMatcher<internal::IsNanMatcher> IsNan() {
6972 return MakePolymorphicMatcher(internal::IsNanMatcher());
6973 }
6974
6975 // Creates a matcher that matches any double argument approximately
6976 // equal to rhs, where two NANs are considered unequal.
6977 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
6978 return internal::FloatingEqMatcher<double>(rhs, false);
6979 }
6980
6981 // Creates a matcher that matches any double argument approximately
6982 // equal to rhs, including NaN values when rhs is NaN.
6983 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
6984 return internal::FloatingEqMatcher<double>(rhs, true);
6985 }
6986
6987 // Creates a matcher that matches any double argument approximately equal to
6988 // rhs, up to the specified max absolute error bound, where two NANs are
6989 // considered unequal. The max absolute error bound must be non-negative.
6990 inline internal::FloatingEqMatcher<double> DoubleNear(
6991 double rhs, double max_abs_error) {
6992 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
6993 }
6994
6995 // Creates a matcher that matches any double argument approximately equal to
6996 // rhs, up to the specified max absolute error bound, including NaN values when
6997 // rhs is NaN. The max absolute error bound must be non-negative.
6998 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
6999 double rhs, double max_abs_error) {
7000 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
7001 }
7002
7003 // Creates a matcher that matches any float argument approximately
7004 // equal to rhs, where two NANs are considered unequal.
7005 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
7006 return internal::FloatingEqMatcher<float>(rhs, false);
7007 }
7008
7009 // Creates a matcher that matches any float argument approximately
7010 // equal to rhs, including NaN values when rhs is NaN.
7011 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
7012 return internal::FloatingEqMatcher<float>(rhs, true);
7013 }
7014
7015 // Creates a matcher that matches any float argument approximately equal to
7016 // rhs, up to the specified max absolute error bound, where two NANs are
7017 // considered unequal. The max absolute error bound must be non-negative.
7018 inline internal::FloatingEqMatcher<float> FloatNear(
7019 float rhs, float max_abs_error) {
7020 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
7021 }
7022
7023 // Creates a matcher that matches any float argument approximately equal to
7024 // rhs, up to the specified max absolute error bound, including NaN values when
7025 // rhs is NaN. The max absolute error bound must be non-negative.
7026 inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
7027 float rhs, float max_abs_error) {
7028 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
7029 }
7030
7031 // Creates a matcher that matches a pointer (raw or smart) that points
7032 // to a value that matches inner_matcher.
7033 template <typename InnerMatcher>
7034 inline internal::PointeeMatcher<InnerMatcher> Pointee(
7035 const InnerMatcher& inner_matcher) {
7036 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
7037 }
7038
7039 #if GTEST_HAS_RTTI
7040 // Creates a matcher that matches a pointer or reference that matches
7041 // inner_matcher when dynamic_cast<To> is applied.
7042 // The result of dynamic_cast<To> is forwarded to the inner matcher.
7043 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
7044 // If To is a reference and the cast fails, this matcher returns false
7045 // immediately.
7046 template <typename To>
7047 inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
7048 WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
7049 return MakePolymorphicMatcher(
7050 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
7051 }
7052 #endif // GTEST_HAS_RTTI
7053
7054 // Creates a matcher that matches an object whose given field matches
7055 // 'matcher'. For example,
7056 // Field(&Foo::number, Ge(5))
7057 // matches a Foo object x if and only if x.number >= 5.
7058 template <typename Class, typename FieldType, typename FieldMatcher>
7059 inline PolymorphicMatcher<
7060 internal::FieldMatcher<Class, FieldType> > Field(
7061 FieldType Class::*field, const FieldMatcher& matcher) {
7062 return MakePolymorphicMatcher(
7063 internal::FieldMatcher<Class, FieldType>(
7064 field, MatcherCast<const FieldType&>(matcher)));
7065 // The call to MatcherCast() is required for supporting inner
7066 // matchers of compatible types. For example, it allows
7067 // Field(&Foo::bar, m)
7068 // to compile where bar is an int32 and m is a matcher for int64.
7069 }
7070
7071 // Same as Field() but also takes the name of the field to provide better error
7072 // messages.
7073 template <typename Class, typename FieldType, typename FieldMatcher>
7074 inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
7075 const std::string& field_name, FieldType Class::*field,
7076 const FieldMatcher& matcher) {
7077 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
7078 field_name, field, MatcherCast<const FieldType&>(matcher)));
7079 }
7080
7081 // Creates a matcher that matches an object whose given property
7082 // matches 'matcher'. For example,
7083 // Property(&Foo::str, StartsWith("hi"))
7084 // matches a Foo object x if and only if x.str() starts with "hi".
7085 template <typename Class, typename PropertyType, typename PropertyMatcher>
7086 inline PolymorphicMatcher<internal::PropertyMatcher<
7087 Class, PropertyType, PropertyType (Class::*)() const> >
7088 Property(PropertyType (Class::*property)() const,
7089 const PropertyMatcher& matcher) {
7090 return MakePolymorphicMatcher(
7091 internal::PropertyMatcher<Class, PropertyType,
7092 PropertyType (Class::*)() const>(
7093 property, MatcherCast<const PropertyType&>(matcher)));
7094 // The call to MatcherCast() is required for supporting inner
7095 // matchers of compatible types. For example, it allows
7096 // Property(&Foo::bar, m)
7097 // to compile where bar() returns an int32 and m is a matcher for int64.
7098 }
7099
7100 // Same as Property() above, but also takes the name of the property to provide
7101 // better error messages.
7102 template <typename Class, typename PropertyType, typename PropertyMatcher>
7103 inline PolymorphicMatcher<internal::PropertyMatcher<
7104 Class, PropertyType, PropertyType (Class::*)() const> >
7105 Property(const std::string& property_name,
7106 PropertyType (Class::*property)() const,
7107 const PropertyMatcher& matcher) {
7108 return MakePolymorphicMatcher(
7109 internal::PropertyMatcher<Class, PropertyType,
7110 PropertyType (Class::*)() const>(
7111 property_name, property, MatcherCast<const PropertyType&>(matcher)));
7112 }
7113
7114 // The same as above but for reference-qualified member functions.
7115 template <typename Class, typename PropertyType, typename PropertyMatcher>
7116 inline PolymorphicMatcher<internal::PropertyMatcher<
7117 Class, PropertyType, PropertyType (Class::*)() const &> >
7118 Property(PropertyType (Class::*property)() const &,
7119 const PropertyMatcher& matcher) {
7120 return MakePolymorphicMatcher(
7121 internal::PropertyMatcher<Class, PropertyType,
7122 PropertyType (Class::*)() const&>(
7123 property, MatcherCast<const PropertyType&>(matcher)));
7124 }
7125
7126 // Three-argument form for reference-qualified member functions.
7127 template <typename Class, typename PropertyType, typename PropertyMatcher>
7128 inline PolymorphicMatcher<internal::PropertyMatcher<
7129 Class, PropertyType, PropertyType (Class::*)() const &> >
7130 Property(const std::string& property_name,
7131 PropertyType (Class::*property)() const &,
7132 const PropertyMatcher& matcher) {
7133 return MakePolymorphicMatcher(
7134 internal::PropertyMatcher<Class, PropertyType,
7135 PropertyType (Class::*)() const&>(
7136 property_name, property, MatcherCast<const PropertyType&>(matcher)));
7137 }
7138
7139 // Creates a matcher that matches an object if and only if the result of
7140 // applying a callable to x matches 'matcher'. For example,
7141 // ResultOf(f, StartsWith("hi"))
7142 // matches a Foo object x if and only if f(x) starts with "hi".
7143 // `callable` parameter can be a function, function pointer, or a functor. It is
7144 // required to keep no state affecting the results of the calls on it and make
7145 // no assumptions about how many calls will be made. Any state it keeps must be
7146 // protected from the concurrent access.
7147 template <typename Callable, typename InnerMatcher>
7148 internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
7149 Callable callable, InnerMatcher matcher) {
7150 return internal::ResultOfMatcher<Callable, InnerMatcher>(
7151 std::move(callable), std::move(matcher));
7152 }
7153
7154 // String matchers.
7155
7156 // Matches a string equal to str.
7157 template <typename T = std::string>
7158 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
7159 const internal::StringLike<T>& str) {
7160 return MakePolymorphicMatcher(
7161 internal::StrEqualityMatcher<std::string>(std::string(str), true, true));
7162 }
7163
7164 // Matches a string not equal to str.
7165 template <typename T = std::string>
7166 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
7167 const internal::StringLike<T>& str) {
7168 return MakePolymorphicMatcher(
7169 internal::StrEqualityMatcher<std::string>(std::string(str), false, true));
7170 }
7171
7172 // Matches a string equal to str, ignoring case.
7173 template <typename T = std::string>
7174 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
7175 const internal::StringLike<T>& str) {
7176 return MakePolymorphicMatcher(
7177 internal::StrEqualityMatcher<std::string>(std::string(str), true, false));
7178 }
7179
7180 // Matches a string not equal to str, ignoring case.
7181 template <typename T = std::string>
7182 PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
7183 const internal::StringLike<T>& str) {
7184 return MakePolymorphicMatcher(internal::StrEqualityMatcher<std::string>(
7185 std::string(str), false, false));
7186 }
7187
7188 // Creates a matcher that matches any string, std::string, or C string
7189 // that contains the given substring.
7190 template <typename T = std::string>
7191 PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
7192 const internal::StringLike<T>& substring) {
7193 return MakePolymorphicMatcher(
7194 internal::HasSubstrMatcher<std::string>(std::string(substring)));
7195 }
7196
7197 // Matches a string that starts with 'prefix' (case-sensitive).
7198 template <typename T = std::string>
7199 PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
7200 const internal::StringLike<T>& prefix) {
7201 return MakePolymorphicMatcher(
7202 internal::StartsWithMatcher<std::string>(std::string(prefix)));
7203 }
7204
7205 // Matches a string that ends with 'suffix' (case-sensitive).
7206 template <typename T = std::string>
7207 PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
7208 const internal::StringLike<T>& suffix) {
7209 return MakePolymorphicMatcher(
7210 internal::EndsWithMatcher<std::string>(std::string(suffix)));
7211 }
7212
7213 #if GTEST_HAS_STD_WSTRING
7214 // Wide string matchers.
7215
7216 // Matches a string equal to str.
7217 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
7218 const std::wstring& str) {
7219 return MakePolymorphicMatcher(
7220 internal::StrEqualityMatcher<std::wstring>(str, true, true));
7221 }
7222
7223 // Matches a string not equal to str.
7224 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
7225 const std::wstring& str) {
7226 return MakePolymorphicMatcher(
7227 internal::StrEqualityMatcher<std::wstring>(str, false, true));
7228 }
7229
7230 // Matches a string equal to str, ignoring case.
7231 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
7232 StrCaseEq(const std::wstring& str) {
7233 return MakePolymorphicMatcher(
7234 internal::StrEqualityMatcher<std::wstring>(str, true, false));
7235 }
7236
7237 // Matches a string not equal to str, ignoring case.
7238 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
7239 StrCaseNe(const std::wstring& str) {
7240 return MakePolymorphicMatcher(
7241 internal::StrEqualityMatcher<std::wstring>(str, false, false));
7242 }
7243
7244 // Creates a matcher that matches any ::wstring, std::wstring, or C wide string
7245 // that contains the given substring.
7246 inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
7247 const std::wstring& substring) {
7248 return MakePolymorphicMatcher(
7249 internal::HasSubstrMatcher<std::wstring>(substring));
7250 }
7251
7252 // Matches a string that starts with 'prefix' (case-sensitive).
7253 inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
7254 StartsWith(const std::wstring& prefix) {
7255 return MakePolymorphicMatcher(
7256 internal::StartsWithMatcher<std::wstring>(prefix));
7257 }
7258
7259 // Matches a string that ends with 'suffix' (case-sensitive).
7260 inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
7261 const std::wstring& suffix) {
7262 return MakePolymorphicMatcher(
7263 internal::EndsWithMatcher<std::wstring>(suffix));
7264 }
7265
7266 #endif // GTEST_HAS_STD_WSTRING
7267
7268 // Creates a polymorphic matcher that matches a 2-tuple where the
7269 // first field == the second field.
7270 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
7271
7272 // Creates a polymorphic matcher that matches a 2-tuple where the
7273 // first field >= the second field.
7274 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
7275
7276 // Creates a polymorphic matcher that matches a 2-tuple where the
7277 // first field > the second field.
7278 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
7279
7280 // Creates a polymorphic matcher that matches a 2-tuple where the
7281 // first field <= the second field.
7282 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
7283
7284 // Creates a polymorphic matcher that matches a 2-tuple where the
7285 // first field < the second field.
7286 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
7287
7288 // Creates a polymorphic matcher that matches a 2-tuple where the
7289 // first field != the second field.
7290 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
7291
7292 // Creates a polymorphic matcher that matches a 2-tuple where
7293 // FloatEq(first field) matches the second field.
7294 inline internal::FloatingEq2Matcher<float> FloatEq() {
7295 return internal::FloatingEq2Matcher<float>();
7296 }
7297
7298 // Creates a polymorphic matcher that matches a 2-tuple where
7299 // DoubleEq(first field) matches the second field.
7300 inline internal::FloatingEq2Matcher<double> DoubleEq() {
7301 return internal::FloatingEq2Matcher<double>();
7302 }
7303
7304 // Creates a polymorphic matcher that matches a 2-tuple where
7305 // FloatEq(first field) matches the second field with NaN equality.
7306 inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
7307 return internal::FloatingEq2Matcher<float>(true);
7308 }
7309
7310 // Creates a polymorphic matcher that matches a 2-tuple where
7311 // DoubleEq(first field) matches the second field with NaN equality.
7312 inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
7313 return internal::FloatingEq2Matcher<double>(true);
7314 }
7315
7316 // Creates a polymorphic matcher that matches a 2-tuple where
7317 // FloatNear(first field, max_abs_error) matches the second field.
7318 inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
7319 return internal::FloatingEq2Matcher<float>(max_abs_error);
7320 }
7321
7322 // Creates a polymorphic matcher that matches a 2-tuple where
7323 // DoubleNear(first field, max_abs_error) matches the second field.
7324 inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
7325 return internal::FloatingEq2Matcher<double>(max_abs_error);
7326 }
7327
7328 // Creates a polymorphic matcher that matches a 2-tuple where
7329 // FloatNear(first field, max_abs_error) matches the second field with NaN
7330 // equality.
7331 inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
7332 float max_abs_error) {
7333 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
7334 }
7335
7336 // Creates a polymorphic matcher that matches a 2-tuple where
7337 // DoubleNear(first field, max_abs_error) matches the second field with NaN
7338 // equality.
7339 inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
7340 double max_abs_error) {
7341 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
7342 }
7343
7344 // Creates a matcher that matches any value of type T that m doesn't
7345 // match.
7346 template <typename InnerMatcher>
7347 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
7348 return internal::NotMatcher<InnerMatcher>(m);
7349 }
7350
7351 // Returns a matcher that matches anything that satisfies the given
7352 // predicate. The predicate can be any unary function or functor
7353 // whose return type can be implicitly converted to bool.
7354 template <typename Predicate>
7355 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
7356 Truly(Predicate pred) {
7357 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
7358 }
7359
7360 // Returns a matcher that matches the container size. The container must
7361 // support both size() and size_type which all STL-like containers provide.
7362 // Note that the parameter 'size' can be a value of type size_type as well as
7363 // matcher. For instance:
7364 // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
7365 // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
7366 template <typename SizeMatcher>
7367 inline internal::SizeIsMatcher<SizeMatcher>
7368 SizeIs(const SizeMatcher& size_matcher) {
7369 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
7370 }
7371
7372 // Returns a matcher that matches the distance between the container's begin()
7373 // iterator and its end() iterator, i.e. the size of the container. This matcher
7374 // can be used instead of SizeIs with containers such as std::forward_list which
7375 // do not implement size(). The container must provide const_iterator (with
7376 // valid iterator_traits), begin() and end().
7377 template <typename DistanceMatcher>
7378 inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
7379 BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
7380 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
7381 }
7382
7383 // Returns a matcher that matches an equal container.
7384 // This matcher behaves like Eq(), but in the event of mismatch lists the
7385 // values that are included in one container but not the other. (Duplicate
7386 // values and order differences are not explained.)
7387 template <typename Container>
7388 inline PolymorphicMatcher<internal::ContainerEqMatcher<
7389 typename std::remove_const<Container>::type>>
7390 ContainerEq(const Container& rhs) {
7391 return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));
7392 }
7393
7394 // Returns a matcher that matches a container that, when sorted using
7395 // the given comparator, matches container_matcher.
7396 template <typename Comparator, typename ContainerMatcher>
7397 inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
7398 WhenSortedBy(const Comparator& comparator,
7399 const ContainerMatcher& container_matcher) {
7400 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
7401 comparator, container_matcher);
7402 }
7403
7404 // Returns a matcher that matches a container that, when sorted using
7405 // the < operator, matches container_matcher.
7406 template <typename ContainerMatcher>
7407 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
7408 WhenSorted(const ContainerMatcher& container_matcher) {
7409 return
7410 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
7411 internal::LessComparator(), container_matcher);
7412 }
7413
7414 // Matches an STL-style container or a native array that contains the
7415 // same number of elements as in rhs, where its i-th element and rhs's
7416 // i-th element (as a pair) satisfy the given pair matcher, for all i.
7417 // TupleMatcher must be able to be safely cast to Matcher<std::tuple<const
7418 // T1&, const T2&> >, where T1 and T2 are the types of elements in the
7419 // LHS container and the RHS container respectively.
7420 template <typename TupleMatcher, typename Container>
7421 inline internal::PointwiseMatcher<TupleMatcher,
7422 typename std::remove_const<Container>::type>
7423 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
7424 return internal::PointwiseMatcher<TupleMatcher, Container>(tuple_matcher,
7425 rhs);
7426 }
7427
7428
7429 // Supports the Pointwise(m, {a, b, c}) syntax.
7430 template <typename TupleMatcher, typename T>
7431 inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
7432 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
7433 return Pointwise(tuple_matcher, std::vector<T>(rhs));
7434 }
7435
7436
7437 // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
7438 // container or a native array that contains the same number of
7439 // elements as in rhs, where in some permutation of the container, its
7440 // i-th element and rhs's i-th element (as a pair) satisfy the given
7441 // pair matcher, for all i. Tuple2Matcher must be able to be safely
7442 // cast to Matcher<std::tuple<const T1&, const T2&> >, where T1 and T2 are
7443 // the types of elements in the LHS container and the RHS container
7444 // respectively.
7445 //
7446 // This is like Pointwise(pair_matcher, rhs), except that the element
7447 // order doesn't matter.
7448 template <typename Tuple2Matcher, typename RhsContainer>
7449 inline internal::UnorderedElementsAreArrayMatcher<
7450 typename internal::BoundSecondMatcher<
7451 Tuple2Matcher,
7452 typename internal::StlContainerView<
7453 typename std::remove_const<RhsContainer>::type>::type::value_type>>
7454 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
7455 const RhsContainer& rhs_container) {
7456 // RhsView allows the same code to handle RhsContainer being a
7457 // STL-style container and it being a native C-style array.
7458 typedef typename internal::StlContainerView<RhsContainer> RhsView;
7459 typedef typename RhsView::type RhsStlContainer;
7460 typedef typename RhsStlContainer::value_type Second;
7461 const RhsStlContainer& rhs_stl_container =
7462 RhsView::ConstReference(rhs_container);
7463
7464 // Create a matcher for each element in rhs_container.
7465 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
7466 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
7467 it != rhs_stl_container.end(); ++it) {
7468 matchers.push_back(
7469 internal::MatcherBindSecond(tuple2_matcher, *it));
7470 }
7471
7472 // Delegate the work to UnorderedElementsAreArray().
7473 return UnorderedElementsAreArray(matchers);
7474 }
7475
7476
7477 // Supports the UnorderedPointwise(m, {a, b, c}) syntax.
7478 template <typename Tuple2Matcher, typename T>
7479 inline internal::UnorderedElementsAreArrayMatcher<
7480 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
7481 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
7482 std::initializer_list<T> rhs) {
7483 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
7484 }
7485
7486
7487 // Matches an STL-style container or a native array that contains at
7488 // least one element matching the given value or matcher.
7489 //
7490 // Examples:
7491 // ::std::set<int> page_ids;
7492 // page_ids.insert(3);
7493 // page_ids.insert(1);
7494 // EXPECT_THAT(page_ids, Contains(1));
7495 // EXPECT_THAT(page_ids, Contains(Gt(2)));
7496 // EXPECT_THAT(page_ids, Not(Contains(4)));
7497 //
7498 // ::std::map<int, size_t> page_lengths;
7499 // page_lengths[1] = 100;
7500 // EXPECT_THAT(page_lengths,
7501 // Contains(::std::pair<const int, size_t>(1, 100)));
7502 //
7503 // const char* user_ids[] = { "joe", "mike", "tom" };
7504 // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
7505 template <typename M>
7506 inline internal::ContainsMatcher<M> Contains(M matcher) {
7507 return internal::ContainsMatcher<M>(matcher);
7508 }
7509
7510 // IsSupersetOf(iterator_first, iterator_last)
7511 // IsSupersetOf(pointer, count)
7512 // IsSupersetOf(array)
7513 // IsSupersetOf(container)
7514 // IsSupersetOf({e1, e2, ..., en})
7515 //
7516 // IsSupersetOf() verifies that a surjective partial mapping onto a collection
7517 // of matchers exists. In other words, a container matches
7518 // IsSupersetOf({e1, ..., en}) if and only if there is a permutation
7519 // {y1, ..., yn} of some of the container's elements where y1 matches e1,
7520 // ..., and yn matches en. Obviously, the size of the container must be >= n
7521 // in order to have a match. Examples:
7522 //
7523 // - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
7524 // 1 matches Ne(0).
7525 // - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
7526 // both Eq(1) and Lt(2). The reason is that different matchers must be used
7527 // for elements in different slots of the container.
7528 // - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
7529 // Eq(1) and (the second) 1 matches Lt(2).
7530 // - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
7531 // Gt(1) and 3 matches (the second) Gt(1).
7532 //
7533 // The matchers can be specified as an array, a pointer and count, a container,
7534 // an initializer list, or an STL iterator range. In each of these cases, the
7535 // underlying matchers can be either values or matchers.
7536
7537 template <typename Iter>
7538 inline internal::UnorderedElementsAreArrayMatcher<
7539 typename ::std::iterator_traits<Iter>::value_type>
7540 IsSupersetOf(Iter first, Iter last) {
7541 typedef typename ::std::iterator_traits<Iter>::value_type T;
7542 return internal::UnorderedElementsAreArrayMatcher<T>(
7543 internal::UnorderedMatcherRequire::Superset, first, last);
7544 }
7545
7546 template <typename T>
7547 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
7548 const T* pointer, size_t count) {
7549 return IsSupersetOf(pointer, pointer + count);
7550 }
7551
7552 template <typename T, size_t N>
7553 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
7554 const T (&array)[N]) {
7555 return IsSupersetOf(array, N);
7556 }
7557
7558 template <typename Container>
7559 inline internal::UnorderedElementsAreArrayMatcher<
7560 typename Container::value_type>
7561 IsSupersetOf(const Container& container) {
7562 return IsSupersetOf(container.begin(), container.end());
7563 }
7564
7565 template <typename T>
7566 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
7567 ::std::initializer_list<T> xs) {
7568 return IsSupersetOf(xs.begin(), xs.end());
7569 }
7570
7571 // IsSubsetOf(iterator_first, iterator_last)
7572 // IsSubsetOf(pointer, count)
7573 // IsSubsetOf(array)
7574 // IsSubsetOf(container)
7575 // IsSubsetOf({e1, e2, ..., en})
7576 //
7577 // IsSubsetOf() verifies that an injective mapping onto a collection of matchers
7578 // exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
7579 // only if there is a subset of matchers {m1, ..., mk} which would match the
7580 // container using UnorderedElementsAre. Obviously, the size of the container
7581 // must be <= n in order to have a match. Examples:
7582 //
7583 // - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
7584 // - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
7585 // matches Lt(0).
7586 // - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
7587 // match Gt(0). The reason is that different matchers must be used for
7588 // elements in different slots of the container.
7589 //
7590 // The matchers can be specified as an array, a pointer and count, a container,
7591 // an initializer list, or an STL iterator range. In each of these cases, the
7592 // underlying matchers can be either values or matchers.
7593
7594 template <typename Iter>
7595 inline internal::UnorderedElementsAreArrayMatcher<
7596 typename ::std::iterator_traits<Iter>::value_type>
7597 IsSubsetOf(Iter first, Iter last) {
7598 typedef typename ::std::iterator_traits<Iter>::value_type T;
7599 return internal::UnorderedElementsAreArrayMatcher<T>(
7600 internal::UnorderedMatcherRequire::Subset, first, last);
7601 }
7602
7603 template <typename T>
7604 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
7605 const T* pointer, size_t count) {
7606 return IsSubsetOf(pointer, pointer + count);
7607 }
7608
7609 template <typename T, size_t N>
7610 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
7611 const T (&array)[N]) {
7612 return IsSubsetOf(array, N);
7613 }
7614
7615 template <typename Container>
7616 inline internal::UnorderedElementsAreArrayMatcher<
7617 typename Container::value_type>
7618 IsSubsetOf(const Container& container) {
7619 return IsSubsetOf(container.begin(), container.end());
7620 }
7621
7622 template <typename T>
7623 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
7624 ::std::initializer_list<T> xs) {
7625 return IsSubsetOf(xs.begin(), xs.end());
7626 }
7627
7628 // Matches an STL-style container or a native array that contains only
7629 // elements matching the given value or matcher.
7630 //
7631 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
7632 // the messages are different.
7633 //
7634 // Examples:
7635 // ::std::set<int> page_ids;
7636 // // Each(m) matches an empty container, regardless of what m is.
7637 // EXPECT_THAT(page_ids, Each(Eq(1)));
7638 // EXPECT_THAT(page_ids, Each(Eq(77)));
7639 //
7640 // page_ids.insert(3);
7641 // EXPECT_THAT(page_ids, Each(Gt(0)));
7642 // EXPECT_THAT(page_ids, Not(Each(Gt(4))));
7643 // page_ids.insert(1);
7644 // EXPECT_THAT(page_ids, Not(Each(Lt(2))));
7645 //
7646 // ::std::map<int, size_t> page_lengths;
7647 // page_lengths[1] = 100;
7648 // page_lengths[2] = 200;
7649 // page_lengths[3] = 300;
7650 // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
7651 // EXPECT_THAT(page_lengths, Each(Key(Le(3))));
7652 //
7653 // const char* user_ids[] = { "joe", "mike", "tom" };
7654 // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
7655 template <typename M>
7656 inline internal::EachMatcher<M> Each(M matcher) {
7657 return internal::EachMatcher<M>(matcher);
7658 }
7659
7660 // Key(inner_matcher) matches an std::pair whose 'first' field matches
7661 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
7662 // std::map that contains at least one element whose key is >= 5.
7663 template <typename M>
7664 inline internal::KeyMatcher<M> Key(M inner_matcher) {
7665 return internal::KeyMatcher<M>(inner_matcher);
7666 }
7667
7668 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
7669 // matches first_matcher and whose 'second' field matches second_matcher. For
7670 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
7671 // to match a std::map<int, string> that contains exactly one element whose key
7672 // is >= 5 and whose value equals "foo".
7673 template <typename FirstMatcher, typename SecondMatcher>
7674 inline internal::PairMatcher<FirstMatcher, SecondMatcher>
7675 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
7676 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
7677 first_matcher, second_matcher);
7678 }
7679
7680 namespace no_adl {
7681 // FieldsAre(matchers...) matches piecewise the fields of compatible structs.
7682 // These include those that support `get<I>(obj)`, and when structured bindings
7683 // are enabled any class that supports them.
7684 // In particular, `std::tuple`, `std::pair`, `std::array` and aggregate types.
7685 template <typename... M>
7686 internal::FieldsAreMatcher<typename std::decay<M>::type...> FieldsAre(
7687 M&&... matchers) {
7688 return internal::FieldsAreMatcher<typename std::decay<M>::type...>(
7689 std::forward<M>(matchers)...);
7690 }
7691
7692 // Creates a matcher that matches a pointer (raw or smart) that matches
7693 // inner_matcher.
7694 template <typename InnerMatcher>
7695 inline internal::PointerMatcher<InnerMatcher> Pointer(
7696 const InnerMatcher& inner_matcher) {
7697 return internal::PointerMatcher<InnerMatcher>(inner_matcher);
7698 }
7699
7700 // Creates a matcher that matches an object that has an address that matches
7701 // inner_matcher.
7702 template <typename InnerMatcher>
7703 inline internal::AddressMatcher<InnerMatcher> Address(
7704 const InnerMatcher& inner_matcher) {
7705 return internal::AddressMatcher<InnerMatcher>(inner_matcher);
7706 }
7707 } // namespace no_adl
7708
7709 // Returns a predicate that is satisfied by anything that matches the
7710 // given matcher.
7711 template <typename M>
7712 inline internal::MatcherAsPredicate<M> Matches(M matcher) {
7713 return internal::MatcherAsPredicate<M>(matcher);
7714 }
7715
7716 // Returns true if and only if the value matches the matcher.
7717 template <typename T, typename M>
7718 inline bool Value(const T& value, M matcher) {
7719 return testing::Matches(matcher)(value);
7720 }
7721
7722 // Matches the value against the given matcher and explains the match
7723 // result to listener.
7724 template <typename T, typename M>
7725 inline bool ExplainMatchResult(
7726 M matcher, const T& value, MatchResultListener* listener) {
7727 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
7728 }
7729
7730 // Returns a string representation of the given matcher. Useful for description
7731 // strings of matchers defined using MATCHER_P* macros that accept matchers as
7732 // their arguments. For example:
7733 //
7734 // MATCHER_P(XAndYThat, matcher,
7735 // "X that " + DescribeMatcher<int>(matcher, negation) +
7736 // " and Y that " + DescribeMatcher<double>(matcher, negation)) {
7737 // return ExplainMatchResult(matcher, arg.x(), result_listener) &&
7738 // ExplainMatchResult(matcher, arg.y(), result_listener);
7739 // }
7740 template <typename T, typename M>
7741 std::string DescribeMatcher(const M& matcher, bool negation = false) {
7742 ::std::stringstream ss;
7743 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
7744 if (negation) {
7745 monomorphic_matcher.DescribeNegationTo(&ss);
7746 } else {
7747 monomorphic_matcher.DescribeTo(&ss);
7748 }
7749 return ss.str();
7750 }
7751
7752 template <typename... Args>
7753 internal::ElementsAreMatcher<
7754 std::tuple<typename std::decay<const Args&>::type...>>
7755 ElementsAre(const Args&... matchers) {
7756 return internal::ElementsAreMatcher<
7757 std::tuple<typename std::decay<const Args&>::type...>>(
7758 std::make_tuple(matchers...));
7759 }
7760
7761 template <typename... Args>
7762 internal::UnorderedElementsAreMatcher<
7763 std::tuple<typename std::decay<const Args&>::type...>>
7764 UnorderedElementsAre(const Args&... matchers) {
7765 return internal::UnorderedElementsAreMatcher<
7766 std::tuple<typename std::decay<const Args&>::type...>>(
7767 std::make_tuple(matchers...));
7768 }
7769
7770 // Define variadic matcher versions.
7771 template <typename... Args>
7772 internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(
7773 const Args&... matchers) {
7774 return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(
7775 matchers...);
7776 }
7777
7778 template <typename... Args>
7779 internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(
7780 const Args&... matchers) {
7781 return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(
7782 matchers...);
7783 }
7784
7785 // AnyOfArray(array)
7786 // AnyOfArray(pointer, count)
7787 // AnyOfArray(container)
7788 // AnyOfArray({ e1, e2, ..., en })
7789 // AnyOfArray(iterator_first, iterator_last)
7790 //
7791 // AnyOfArray() verifies whether a given value matches any member of a
7792 // collection of matchers.
7793 //
7794 // AllOfArray(array)
7795 // AllOfArray(pointer, count)
7796 // AllOfArray(container)
7797 // AllOfArray({ e1, e2, ..., en })
7798 // AllOfArray(iterator_first, iterator_last)
7799 //
7800 // AllOfArray() verifies whether a given value matches all members of a
7801 // collection of matchers.
7802 //
7803 // The matchers can be specified as an array, a pointer and count, a container,
7804 // an initializer list, or an STL iterator range. In each of these cases, the
7805 // underlying matchers can be either values or matchers.
7806
7807 template <typename Iter>
7808 inline internal::AnyOfArrayMatcher<
7809 typename ::std::iterator_traits<Iter>::value_type>
7810 AnyOfArray(Iter first, Iter last) {
7811 return internal::AnyOfArrayMatcher<
7812 typename ::std::iterator_traits<Iter>::value_type>(first, last);
7813 }
7814
7815 template <typename Iter>
7816 inline internal::AllOfArrayMatcher<
7817 typename ::std::iterator_traits<Iter>::value_type>
7818 AllOfArray(Iter first, Iter last) {
7819 return internal::AllOfArrayMatcher<
7820 typename ::std::iterator_traits<Iter>::value_type>(first, last);
7821 }
7822
7823 template <typename T>
7824 inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T* ptr, size_t count) {
7825 return AnyOfArray(ptr, ptr + count);
7826 }
7827
7828 template <typename T>
7829 inline internal::AllOfArrayMatcher<T> AllOfArray(const T* ptr, size_t count) {
7830 return AllOfArray(ptr, ptr + count);
7831 }
7832
7833 template <typename T, size_t N>
7834 inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T (&array)[N]) {
7835 return AnyOfArray(array, N);
7836 }
7837
7838 template <typename T, size_t N>
7839 inline internal::AllOfArrayMatcher<T> AllOfArray(const T (&array)[N]) {
7840 return AllOfArray(array, N);
7841 }
7842
7843 template <typename Container>
7844 inline internal::AnyOfArrayMatcher<typename Container::value_type> AnyOfArray(
7845 const Container& container) {
7846 return AnyOfArray(container.begin(), container.end());
7847 }
7848
7849 template <typename Container>
7850 inline internal::AllOfArrayMatcher<typename Container::value_type> AllOfArray(
7851 const Container& container) {
7852 return AllOfArray(container.begin(), container.end());
7853 }
7854
7855 template <typename T>
7856 inline internal::AnyOfArrayMatcher<T> AnyOfArray(
7857 ::std::initializer_list<T> xs) {
7858 return AnyOfArray(xs.begin(), xs.end());
7859 }
7860
7861 template <typename T>
7862 inline internal::AllOfArrayMatcher<T> AllOfArray(
7863 ::std::initializer_list<T> xs) {
7864 return AllOfArray(xs.begin(), xs.end());
7865 }
7866
7867 // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected
7868 // fields of it matches a_matcher. C++ doesn't support default
7869 // arguments for function templates, so we have to overload it.
7870 template <size_t... k, typename InnerMatcher>
7871 internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...> Args(
7872 InnerMatcher&& matcher) {
7873 return internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...>(
7874 std::forward<InnerMatcher>(matcher));
7875 }
7876
7877 // AllArgs(m) is a synonym of m. This is useful in
7878 //
7879 // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
7880 //
7881 // which is easier to read than
7882 //
7883 // EXPECT_CALL(foo, Bar(_, _)).With(Eq());
7884 template <typename InnerMatcher>
7885 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
7886
7887 // Returns a matcher that matches the value of an optional<> type variable.
7888 // The matcher implementation only uses '!arg' and requires that the optional<>
7889 // type has a 'value_type' member type and that '*arg' is of type 'value_type'
7890 // and is printable using 'PrintToString'. It is compatible with
7891 // std::optional/std::experimental::optional.
7892 // Note that to compare an optional type variable against nullopt you should
7893 // use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the
7894 // optional value contains an optional itself.
7895 template <typename ValueMatcher>
7896 inline internal::OptionalMatcher<ValueMatcher> Optional(
7897 const ValueMatcher& value_matcher) {
7898 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
7899 }
7900
7901 // Returns a matcher that matches the value of a absl::any type variable.
7902 template <typename T>
7903 PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
7904 const Matcher<const T&>& matcher) {
7905 return MakePolymorphicMatcher(
7906 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
7907 }
7908
7909 // Returns a matcher that matches the value of a variant<> type variable.
7910 // The matcher implementation uses ADL to find the holds_alternative and get
7911 // functions.
7912 // It is compatible with std::variant.
7913 template <typename T>
7914 PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
7915 const Matcher<const T&>& matcher) {
7916 return MakePolymorphicMatcher(
7917 internal::variant_matcher::VariantMatcher<T>(matcher));
7918 }
7919
7920 #if GTEST_HAS_EXCEPTIONS
7921
7922 // Anything inside the `internal` namespace is internal to the implementation
7923 // and must not be used in user code!
7924 namespace internal {
7925
7926 class WithWhatMatcherImpl {
7927 public:
7928 WithWhatMatcherImpl(Matcher<std::string> matcher)
7929 : matcher_(std::move(matcher)) {}
7930
7931 void DescribeTo(std::ostream* os) const {
7932 *os << "contains .what() that ";
7933 matcher_.DescribeTo(os);
7934 }
7935
7936 void DescribeNegationTo(std::ostream* os) const {
7937 *os << "contains .what() that does not ";
7938 matcher_.DescribeTo(os);
7939 }
7940
7941 template <typename Err>
7942 bool MatchAndExplain(const Err& err, MatchResultListener* listener) const {
7943 *listener << "which contains .what() that ";
7944 return matcher_.MatchAndExplain(err.what(), listener);
7945 }
7946
7947 private:
7948 const Matcher<std::string> matcher_;
7949 };
7950
7951 inline PolymorphicMatcher<WithWhatMatcherImpl> WithWhat(
7952 Matcher<std::string> m) {
7953 return MakePolymorphicMatcher(WithWhatMatcherImpl(std::move(m)));
7954 }
7955
7956 template <typename Err>
7957 class ExceptionMatcherImpl {
7958 class NeverThrown {
7959 public:
7960 const char* what() const noexcept {
7961 return "this exception should never be thrown";
7962 }
7963 };
7964
7965 // If the matchee raises an exception of a wrong type, we'd like to
7966 // catch it and print its message and type. To do that, we add an additional
7967 // catch clause:
7968 //
7969 // try { ... }
7970 // catch (const Err&) { /* an expected exception */ }
7971 // catch (const std::exception&) { /* exception of a wrong type */ }
7972 //
7973 // However, if the `Err` itself is `std::exception`, we'd end up with two
7974 // identical `catch` clauses:
7975 //
7976 // try { ... }
7977 // catch (const std::exception&) { /* an expected exception */ }
7978 // catch (const std::exception&) { /* exception of a wrong type */ }
7979 //
7980 // This can cause a warning or an error in some compilers. To resolve
7981 // the issue, we use a fake error type whenever `Err` is `std::exception`:
7982 //
7983 // try { ... }
7984 // catch (const std::exception&) { /* an expected exception */ }
7985 // catch (const NeverThrown&) { /* exception of a wrong type */ }
7986 using DefaultExceptionType = typename std::conditional<
7987 std::is_same<typename std::remove_cv<
7988 typename std::remove_reference<Err>::type>::type,
7989 std::exception>::value,
7990 const NeverThrown&, const std::exception&>::type;
7991
7992 public:
7993 ExceptionMatcherImpl(Matcher<const Err&> matcher)
7994 : matcher_(std::move(matcher)) {}
7995
7996 void DescribeTo(std::ostream* os) const {
7997 *os << "throws an exception which is a " << GetTypeName<Err>();
7998 *os << " which ";
7999 matcher_.DescribeTo(os);
8000 }
8001
8002 void DescribeNegationTo(std::ostream* os) const {
8003 *os << "throws an exception which is not a " << GetTypeName<Err>();
8004 *os << " which ";
8005 matcher_.DescribeNegationTo(os);
8006 }
8007
8008 template <typename T>
8009 bool MatchAndExplain(T&& x, MatchResultListener* listener) const {
8010 try {
8011 (void)(std::forward<T>(x)());
8012 } catch (const Err& err) {
8013 *listener << "throws an exception which is a " << GetTypeName<Err>();
8014 *listener << " ";
8015 return matcher_.MatchAndExplain(err, listener);
8016 } catch (DefaultExceptionType err) {
8017 #if GTEST_HAS_RTTI
8018 *listener << "throws an exception of type " << GetTypeName(typeid(err));
8019 *listener << " ";
8020 #else
8021 *listener << "throws an std::exception-derived type ";
8022 #endif
8023 *listener << "with description \"" << err.what() << "\"";
8024 return false;
8025 } catch (...) {
8026 *listener << "throws an exception of an unknown type";
8027 return false;
8028 }
8029
8030 *listener << "does not throw any exception";
8031 return false;
8032 }
8033
8034 private:
8035 const Matcher<const Err&> matcher_;
8036 };
8037
8038 } // namespace internal
8039
8040 // Throws()
8041 // Throws(exceptionMatcher)
8042 // ThrowsMessage(messageMatcher)
8043 //
8044 // This matcher accepts a callable and verifies that when invoked, it throws
8045 // an exception with the given type and properties.
8046 //
8047 // Examples:
8048 //
8049 // EXPECT_THAT(
8050 // []() { throw std::runtime_error("message"); },
8051 // Throws<std::runtime_error>());
8052 //
8053 // EXPECT_THAT(
8054 // []() { throw std::runtime_error("message"); },
8055 // ThrowsMessage<std::runtime_error>(HasSubstr("message")));
8056 //
8057 // EXPECT_THAT(
8058 // []() { throw std::runtime_error("message"); },
8059 // Throws<std::runtime_error>(
8060 // Property(&std::runtime_error::what, HasSubstr("message"))));
8061
8062 template <typename Err>
8063 PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws() {
8064 return MakePolymorphicMatcher(
8065 internal::ExceptionMatcherImpl<Err>(A<const Err&>()));
8066 }
8067
8068 template <typename Err, typename ExceptionMatcher>
8069 PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws(
8070 const ExceptionMatcher& exception_matcher) {
8071 // Using matcher cast allows users to pass a matcher of a more broad type.
8072 // For example user may want to pass Matcher<std::exception>
8073 // to Throws<std::runtime_error>, or Matcher<int64> to Throws<int32>.
8074 return MakePolymorphicMatcher(internal::ExceptionMatcherImpl<Err>(
8075 SafeMatcherCast<const Err&>(exception_matcher)));
8076 }
8077
8078 template <typename Err, typename MessageMatcher>
8079 PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
8080 MessageMatcher&& message_matcher) {
8081 static_assert(std::is_base_of<std::exception, Err>::value,
8082 "expected an std::exception-derived type");
8083 return Throws<Err>(internal::WithWhat(
8084 MatcherCast<std::string>(std::forward<MessageMatcher>(message_matcher))));
8085 }
8086
8087 #endif // GTEST_HAS_EXCEPTIONS
8088
8089 // These macros allow using matchers to check values in Google Test
8090 // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
8091 // succeed if and only if the value matches the matcher. If the assertion
8092 // fails, the value and the description of the matcher will be printed.
8093 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
8094 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
8095 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
8096 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
8097
8098 // MATCHER* macroses itself are listed below.
8099 #define MATCHER(name, description) \
8100 class name##Matcher \
8101 : public ::testing::internal::MatcherBaseImpl<name##Matcher> { \
8102 public: \
8103 template <typename arg_type> \
8104 class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
8105 public: \
8106 gmock_Impl() {} \
8107 bool MatchAndExplain( \
8108 const arg_type& arg, \
8109 ::testing::MatchResultListener* result_listener) const override; \
8110 void DescribeTo(::std::ostream* gmock_os) const override { \
8111 *gmock_os << FormatDescription(false); \
8112 } \
8113 void DescribeNegationTo(::std::ostream* gmock_os) const override { \
8114 *gmock_os << FormatDescription(true); \
8115 } \
8116 \
8117 private: \
8118 ::std::string FormatDescription(bool negation) const { \
8119 ::std::string gmock_description = (description); \
8120 if (!gmock_description.empty()) { \
8121 return gmock_description; \
8122 } \
8123 return ::testing::internal::FormatMatcherDescription(negation, #name, \
8124 {}); \
8125 } \
8126 }; \
8127 }; \
8128 GTEST_ATTRIBUTE_UNUSED_ inline name##Matcher name() { return {}; } \
8129 template <typename arg_type> \
8130 bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \
8131 const arg_type& arg, \
8132 ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) \
8133 const
8134
8135 #define MATCHER_P(name, p0, description) \
8136 GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (p0))
8137 #define MATCHER_P2(name, p0, p1, description) \
8138 GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (p0, p1))
8139 #define MATCHER_P3(name, p0, p1, p2, description) \
8140 GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (p0, p1, p2))
8141 #define MATCHER_P4(name, p0, p1, p2, p3, description) \
8142 GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, (p0, p1, p2, p3))
8143 #define MATCHER_P5(name, p0, p1, p2, p3, p4, description) \
8144 GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \
8145 (p0, p1, p2, p3, p4))
8146 #define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \
8147 GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description, \
8148 (p0, p1, p2, p3, p4, p5))
8149 #define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \
8150 GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description, \
8151 (p0, p1, p2, p3, p4, p5, p6))
8152 #define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \
8153 GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description, \
8154 (p0, p1, p2, p3, p4, p5, p6, p7))
8155 #define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \
8156 GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description, \
8157 (p0, p1, p2, p3, p4, p5, p6, p7, p8))
8158 #define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \
8159 GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description, \
8160 (p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))
8161
8162 #define GMOCK_INTERNAL_MATCHER(name, full_name, description, args) \
8163 template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
8164 class full_name : public ::testing::internal::MatcherBaseImpl< \
8165 full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \
8166 public: \
8167 using full_name::MatcherBaseImpl::MatcherBaseImpl; \
8168 template <typename arg_type> \
8169 class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
8170 public: \
8171 explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) \
8172 : GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {} \
8173 bool MatchAndExplain( \
8174 const arg_type& arg, \
8175 ::testing::MatchResultListener* result_listener) const override; \
8176 void DescribeTo(::std::ostream* gmock_os) const override { \
8177 *gmock_os << FormatDescription(false); \
8178 } \
8179 void DescribeNegationTo(::std::ostream* gmock_os) const override { \
8180 *gmock_os << FormatDescription(true); \
8181 } \
8182 GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
8183 \
8184 private: \
8185 ::std::string FormatDescription(bool negation) const { \
8186 ::std::string gmock_description = (description); \
8187 if (!gmock_description.empty()) { \
8188 return gmock_description; \
8189 } \
8190 return ::testing::internal::FormatMatcherDescription( \
8191 negation, #name, \
8192 ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \
8193 ::std::tuple<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
8194 GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args)))); \
8195 } \
8196 }; \
8197 }; \
8198 template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
8199 inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name( \
8200 GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) { \
8201 return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
8202 GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args)); \
8203 } \
8204 template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
8205 template <typename arg_type> \
8206 bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>::gmock_Impl< \
8207 arg_type>::MatchAndExplain(const arg_type& arg, \
8208 ::testing::MatchResultListener* \
8209 result_listener GTEST_ATTRIBUTE_UNUSED_) \
8210 const
8211
8212 #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \
8213 GMOCK_PP_TAIL( \
8214 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args))
8215 #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \
8216 , typename arg##_type
8217
8218 #define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \
8219 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args))
8220 #define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \
8221 , arg##_type
8222
8223 #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \
8224 GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH( \
8225 GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args))
8226 #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \
8227 , arg##_type gmock_p##i
8228
8229 #define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \
8230 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args))
8231 #define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \
8232 , arg(::std::forward<arg##_type>(gmock_p##i))
8233
8234 #define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
8235 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args)
8236 #define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \
8237 const arg##_type arg;
8238
8239 #define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \
8240 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args))
8241 #define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg
8242
8243 #define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \
8244 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))
8245 #define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg_unused) \
8246 , gmock_p##i
8247
8248 // To prevent ADL on certain functions we put them on a separate namespace.
8249 using namespace no_adl; // NOLINT
8250
8251 } // namespace testing
8252
8253 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
8254
8255 // Include any custom callback matchers added by the local installation.
8256 // We must include this header at the end to make sure it can use the
8257 // declarations from this file.
8258 // Copyright 2015, Google Inc.
8259 // All rights reserved.
8260 //
8261 // Redistribution and use in source and binary forms, with or without
8262 // modification, are permitted provided that the following conditions are
8263 // met:
8264 //
8265 // * Redistributions of source code must retain the above copyright
8266 // notice, this list of conditions and the following disclaimer.
8267 // * Redistributions in binary form must reproduce the above
8268 // copyright notice, this list of conditions and the following disclaimer
8269 // in the documentation and/or other materials provided with the
8270 // distribution.
8271 // * Neither the name of Google Inc. nor the names of its
8272 // contributors may be used to endorse or promote products derived from
8273 // this software without specific prior written permission.
8274 //
8275 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8276 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8277 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8278 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8279 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8280 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8281 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8282 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8283 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8284 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8285 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8286 //
8287 // Injection point for custom user configurations. See README for details
8288 //
8289 // GOOGLETEST_CM0002 DO NOT DELETE
8290
8291 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
8292 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
8293 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
8294
8295 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
8296
8297 #if GTEST_HAS_EXCEPTIONS
8298 # include <stdexcept> // NOLINT
8299 #endif
8300
8301 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
8302 /* class A needs to have dll-interface to be used by clients of class B */)
8303
8304 namespace testing {
8305
8306 // An abstract handle of an expectation.
8307 class Expectation;
8308
8309 // A set of expectation handles.
8310 class ExpectationSet;
8311
8312 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
8313 // and MUST NOT BE USED IN USER CODE!!!
8314 namespace internal {
8315
8316 // Implements a mock function.
8317 template <typename F> class FunctionMocker;
8318
8319 // Base class for expectations.
8320 class ExpectationBase;
8321
8322 // Implements an expectation.
8323 template <typename F> class TypedExpectation;
8324
8325 // Helper class for testing the Expectation class template.
8326 class ExpectationTester;
8327
8328 // Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
8329 template <typename MockClass>
8330 class NiceMockImpl;
8331 template <typename MockClass>
8332 class StrictMockImpl;
8333 template <typename MockClass>
8334 class NaggyMockImpl;
8335
8336 // Protects the mock object registry (in class Mock), all function
8337 // mockers, and all expectations.
8338 //
8339 // The reason we don't use more fine-grained protection is: when a
8340 // mock function Foo() is called, it needs to consult its expectations
8341 // to see which one should be picked. If another thread is allowed to
8342 // call a mock function (either Foo() or a different one) at the same
8343 // time, it could affect the "retired" attributes of Foo()'s
8344 // expectations when InSequence() is used, and thus affect which
8345 // expectation gets picked. Therefore, we sequence all mock function
8346 // calls to ensure the integrity of the mock objects' states.
8347 GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
8348
8349 // Untyped base class for ActionResultHolder<R>.
8350 class UntypedActionResultHolderBase;
8351
8352 // Abstract base class of FunctionMocker. This is the
8353 // type-agnostic part of the function mocker interface. Its pure
8354 // virtual methods are implemented by FunctionMocker.
8355 class GTEST_API_ UntypedFunctionMockerBase {
8356 public:
8357 UntypedFunctionMockerBase();
8358 virtual ~UntypedFunctionMockerBase();
8359
8360 // Verifies that all expectations on this mock function have been
8361 // satisfied. Reports one or more Google Test non-fatal failures
8362 // and returns false if not.
8363 bool VerifyAndClearExpectationsLocked()
8364 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
8365
8366 // Clears the ON_CALL()s set on this mock function.
8367 virtual void ClearDefaultActionsLocked()
8368 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
8369
8370 // In all of the following Untyped* functions, it's the caller's
8371 // responsibility to guarantee the correctness of the arguments'
8372 // types.
8373
8374 // Performs the default action with the given arguments and returns
8375 // the action's result. The call description string will be used in
8376 // the error message to describe the call in the case the default
8377 // action fails.
8378 // L = *
8379 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
8380 void* untyped_args, const std::string& call_description) const = 0;
8381
8382 // Performs the given action with the given arguments and returns
8383 // the action's result.
8384 // L = *
8385 virtual UntypedActionResultHolderBase* UntypedPerformAction(
8386 const void* untyped_action, void* untyped_args) const = 0;
8387
8388 // Writes a message that the call is uninteresting (i.e. neither
8389 // explicitly expected nor explicitly unexpected) to the given
8390 // ostream.
8391 virtual void UntypedDescribeUninterestingCall(
8392 const void* untyped_args,
8393 ::std::ostream* os) const
8394 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
8395
8396 // Returns the expectation that matches the given function arguments
8397 // (or NULL is there's no match); when a match is found,
8398 // untyped_action is set to point to the action that should be
8399 // performed (or NULL if the action is "do default"), and
8400 // is_excessive is modified to indicate whether the call exceeds the
8401 // expected number.
8402 virtual const ExpectationBase* UntypedFindMatchingExpectation(
8403 const void* untyped_args,
8404 const void** untyped_action, bool* is_excessive,
8405 ::std::ostream* what, ::std::ostream* why)
8406 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
8407
8408 // Prints the given function arguments to the ostream.
8409 virtual void UntypedPrintArgs(const void* untyped_args,
8410 ::std::ostream* os) const = 0;
8411
8412 // Sets the mock object this mock method belongs to, and registers
8413 // this information in the global mock registry. Will be called
8414 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
8415 // method.
8416 void RegisterOwner(const void* mock_obj)
8417 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8418
8419 // Sets the mock object this mock method belongs to, and sets the
8420 // name of the mock function. Will be called upon each invocation
8421 // of this mock function.
8422 void SetOwnerAndName(const void* mock_obj, const char* name)
8423 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8424
8425 // Returns the mock object this mock method belongs to. Must be
8426 // called after RegisterOwner() or SetOwnerAndName() has been
8427 // called.
8428 const void* MockObject() const
8429 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8430
8431 // Returns the name of this mock method. Must be called after
8432 // SetOwnerAndName() has been called.
8433 const char* Name() const
8434 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8435
8436 // Returns the result of invoking this mock function with the given
8437 // arguments. This function can be safely called from multiple
8438 // threads concurrently. The caller is responsible for deleting the
8439 // result.
8440 UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
8441 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
8442
8443 protected:
8444 typedef std::vector<const void*> UntypedOnCallSpecs;
8445
8446 using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
8447
8448 // Returns an Expectation object that references and co-owns exp,
8449 // which must be an expectation on this mock function.
8450 Expectation GetHandleOf(ExpectationBase* exp);
8451
8452 // Address of the mock object this mock method belongs to. Only
8453 // valid after this mock method has been called or
8454 // ON_CALL/EXPECT_CALL has been invoked on it.
8455 const void* mock_obj_; // Protected by g_gmock_mutex.
8456
8457 // Name of the function being mocked. Only valid after this mock
8458 // method has been called.
8459 const char* name_; // Protected by g_gmock_mutex.
8460
8461 // All default action specs for this function mocker.
8462 UntypedOnCallSpecs untyped_on_call_specs_;
8463
8464 // All expectations for this function mocker.
8465 //
8466 // It's undefined behavior to interleave expectations (EXPECT_CALLs
8467 // or ON_CALLs) and mock function calls. Also, the order of
8468 // expectations is important. Therefore it's a logic race condition
8469 // to read/write untyped_expectations_ concurrently. In order for
8470 // tools like tsan to catch concurrent read/write accesses to
8471 // untyped_expectations, we deliberately leave accesses to it
8472 // unprotected.
8473 UntypedExpectations untyped_expectations_;
8474 }; // class UntypedFunctionMockerBase
8475
8476 // Untyped base class for OnCallSpec<F>.
8477 class UntypedOnCallSpecBase {
8478 public:
8479 // The arguments are the location of the ON_CALL() statement.
8480 UntypedOnCallSpecBase(const char* a_file, int a_line)
8481 : file_(a_file), line_(a_line), last_clause_(kNone) {}
8482
8483 // Where in the source file was the default action spec defined?
8484 const char* file() const { return file_; }
8485 int line() const { return line_; }
8486
8487 protected:
8488 // Gives each clause in the ON_CALL() statement a name.
8489 enum Clause {
8490 // Do not change the order of the enum members! The run-time
8491 // syntax checking relies on it.
8492 kNone,
8493 kWith,
8494 kWillByDefault
8495 };
8496
8497 // Asserts that the ON_CALL() statement has a certain property.
8498 void AssertSpecProperty(bool property,
8499 const std::string& failure_message) const {
8500 Assert(property, file_, line_, failure_message);
8501 }
8502
8503 // Expects that the ON_CALL() statement has a certain property.
8504 void ExpectSpecProperty(bool property,
8505 const std::string& failure_message) const {
8506 Expect(property, file_, line_, failure_message);
8507 }
8508
8509 const char* file_;
8510 int line_;
8511
8512 // The last clause in the ON_CALL() statement as seen so far.
8513 // Initially kNone and changes as the statement is parsed.
8514 Clause last_clause_;
8515 }; // class UntypedOnCallSpecBase
8516
8517 // This template class implements an ON_CALL spec.
8518 template <typename F>
8519 class OnCallSpec : public UntypedOnCallSpecBase {
8520 public:
8521 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
8522 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
8523
8524 // Constructs an OnCallSpec object from the information inside
8525 // the parenthesis of an ON_CALL() statement.
8526 OnCallSpec(const char* a_file, int a_line,
8527 const ArgumentMatcherTuple& matchers)
8528 : UntypedOnCallSpecBase(a_file, a_line),
8529 matchers_(matchers),
8530 // By default, extra_matcher_ should match anything. However,
8531 // we cannot initialize it with _ as that causes ambiguity between
8532 // Matcher's copy and move constructor for some argument types.
8533 extra_matcher_(A<const ArgumentTuple&>()) {}
8534
8535 // Implements the .With() clause.
8536 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
8537 // Makes sure this is called at most once.
8538 ExpectSpecProperty(last_clause_ < kWith,
8539 ".With() cannot appear "
8540 "more than once in an ON_CALL().");
8541 last_clause_ = kWith;
8542
8543 extra_matcher_ = m;
8544 return *this;
8545 }
8546
8547 // Implements the .WillByDefault() clause.
8548 OnCallSpec& WillByDefault(const Action<F>& action) {
8549 ExpectSpecProperty(last_clause_ < kWillByDefault,
8550 ".WillByDefault() must appear "
8551 "exactly once in an ON_CALL().");
8552 last_clause_ = kWillByDefault;
8553
8554 ExpectSpecProperty(!action.IsDoDefault(),
8555 "DoDefault() cannot be used in ON_CALL().");
8556 action_ = action;
8557 return *this;
8558 }
8559
8560 // Returns true if and only if the given arguments match the matchers.
8561 bool Matches(const ArgumentTuple& args) const {
8562 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
8563 }
8564
8565 // Returns the action specified by the user.
8566 const Action<F>& GetAction() const {
8567 AssertSpecProperty(last_clause_ == kWillByDefault,
8568 ".WillByDefault() must appear exactly "
8569 "once in an ON_CALL().");
8570 return action_;
8571 }
8572
8573 private:
8574 // The information in statement
8575 //
8576 // ON_CALL(mock_object, Method(matchers))
8577 // .With(multi-argument-matcher)
8578 // .WillByDefault(action);
8579 //
8580 // is recorded in the data members like this:
8581 //
8582 // source file that contains the statement => file_
8583 // line number of the statement => line_
8584 // matchers => matchers_
8585 // multi-argument-matcher => extra_matcher_
8586 // action => action_
8587 ArgumentMatcherTuple matchers_;
8588 Matcher<const ArgumentTuple&> extra_matcher_;
8589 Action<F> action_;
8590 }; // class OnCallSpec
8591
8592 // Possible reactions on uninteresting calls.
8593 enum CallReaction {
8594 kAllow,
8595 kWarn,
8596 kFail,
8597 };
8598
8599 } // namespace internal
8600
8601 // Utilities for manipulating mock objects.
8602 class GTEST_API_ Mock {
8603 public:
8604 // The following public methods can be called concurrently.
8605
8606 // Tells Google Mock to ignore mock_obj when checking for leaked
8607 // mock objects.
8608 static void AllowLeak(const void* mock_obj)
8609 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8610
8611 // Verifies and clears all expectations on the given mock object.
8612 // If the expectations aren't satisfied, generates one or more
8613 // Google Test non-fatal failures and returns false.
8614 static bool VerifyAndClearExpectations(void* mock_obj)
8615 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8616
8617 // Verifies all expectations on the given mock object and clears its
8618 // default actions and expectations. Returns true if and only if the
8619 // verification was successful.
8620 static bool VerifyAndClear(void* mock_obj)
8621 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8622
8623 // Returns whether the mock was created as a naggy mock (default)
8624 static bool IsNaggy(void* mock_obj)
8625 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8626 // Returns whether the mock was created as a nice mock
8627 static bool IsNice(void* mock_obj)
8628 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8629 // Returns whether the mock was created as a strict mock
8630 static bool IsStrict(void* mock_obj)
8631 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8632
8633 private:
8634 friend class internal::UntypedFunctionMockerBase;
8635
8636 // Needed for a function mocker to register itself (so that we know
8637 // how to clear a mock object).
8638 template <typename F>
8639 friend class internal::FunctionMocker;
8640
8641 template <typename MockClass>
8642 friend class internal::NiceMockImpl;
8643 template <typename MockClass>
8644 friend class internal::NaggyMockImpl;
8645 template <typename MockClass>
8646 friend class internal::StrictMockImpl;
8647
8648 // Tells Google Mock to allow uninteresting calls on the given mock
8649 // object.
8650 static void AllowUninterestingCalls(uintptr_t mock_obj)
8651 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8652
8653 // Tells Google Mock to warn the user about uninteresting calls on
8654 // the given mock object.
8655 static void WarnUninterestingCalls(uintptr_t mock_obj)
8656 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8657
8658 // Tells Google Mock to fail uninteresting calls on the given mock
8659 // object.
8660 static void FailUninterestingCalls(uintptr_t mock_obj)
8661 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8662
8663 // Tells Google Mock the given mock object is being destroyed and
8664 // its entry in the call-reaction table should be removed.
8665 static void UnregisterCallReaction(uintptr_t mock_obj)
8666 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8667
8668 // Returns the reaction Google Mock will have on uninteresting calls
8669 // made on the given mock object.
8670 static internal::CallReaction GetReactionOnUninterestingCalls(
8671 const void* mock_obj)
8672 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8673
8674 // Verifies that all expectations on the given mock object have been
8675 // satisfied. Reports one or more Google Test non-fatal failures
8676 // and returns false if not.
8677 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
8678 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
8679
8680 // Clears all ON_CALL()s set on the given mock object.
8681 static void ClearDefaultActionsLocked(void* mock_obj)
8682 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
8683
8684 // Registers a mock object and a mock method it owns.
8685 static void Register(
8686 const void* mock_obj,
8687 internal::UntypedFunctionMockerBase* mocker)
8688 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8689
8690 // Tells Google Mock where in the source code mock_obj is used in an
8691 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
8692 // information helps the user identify which object it is.
8693 static void RegisterUseByOnCallOrExpectCall(
8694 const void* mock_obj, const char* file, int line)
8695 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
8696
8697 // Unregisters a mock method; removes the owning mock object from
8698 // the registry when the last mock method associated with it has
8699 // been unregistered. This is called only in the destructor of
8700 // FunctionMocker.
8701 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
8702 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
8703 }; // class Mock
8704
8705 // An abstract handle of an expectation. Useful in the .After()
8706 // clause of EXPECT_CALL() for setting the (partial) order of
8707 // expectations. The syntax:
8708 //
8709 // Expectation e1 = EXPECT_CALL(...)...;
8710 // EXPECT_CALL(...).After(e1)...;
8711 //
8712 // sets two expectations where the latter can only be matched after
8713 // the former has been satisfied.
8714 //
8715 // Notes:
8716 // - This class is copyable and has value semantics.
8717 // - Constness is shallow: a const Expectation object itself cannot
8718 // be modified, but the mutable methods of the ExpectationBase
8719 // object it references can be called via expectation_base().
8720
8721 class GTEST_API_ Expectation {
8722 public:
8723 // Constructs a null object that doesn't reference any expectation.
8724 Expectation();
8725 Expectation(Expectation&&) = default;
8726 Expectation(const Expectation&) = default;
8727 Expectation& operator=(Expectation&&) = default;
8728 Expectation& operator=(const Expectation&) = default;
8729 ~Expectation();
8730
8731 // This single-argument ctor must not be explicit, in order to support the
8732 // Expectation e = EXPECT_CALL(...);
8733 // syntax.
8734 //
8735 // A TypedExpectation object stores its pre-requisites as
8736 // Expectation objects, and needs to call the non-const Retire()
8737 // method on the ExpectationBase objects they reference. Therefore
8738 // Expectation must receive a *non-const* reference to the
8739 // ExpectationBase object.
8740 Expectation(internal::ExpectationBase& exp); // NOLINT
8741
8742 // The compiler-generated copy ctor and operator= work exactly as
8743 // intended, so we don't need to define our own.
8744
8745 // Returns true if and only if rhs references the same expectation as this
8746 // object does.
8747 bool operator==(const Expectation& rhs) const {
8748 return expectation_base_ == rhs.expectation_base_;
8749 }
8750
8751 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
8752
8753 private:
8754 friend class ExpectationSet;
8755 friend class Sequence;
8756 friend class ::testing::internal::ExpectationBase;
8757 friend class ::testing::internal::UntypedFunctionMockerBase;
8758
8759 template <typename F>
8760 friend class ::testing::internal::FunctionMocker;
8761
8762 template <typename F>
8763 friend class ::testing::internal::TypedExpectation;
8764
8765 // This comparator is needed for putting Expectation objects into a set.
8766 class Less {
8767 public:
8768 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
8769 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
8770 }
8771 };
8772
8773 typedef ::std::set<Expectation, Less> Set;
8774
8775 Expectation(
8776 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
8777
8778 // Returns the expectation this object references.
8779 const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
8780 return expectation_base_;
8781 }
8782
8783 // A shared_ptr that co-owns the expectation this handle references.
8784 std::shared_ptr<internal::ExpectationBase> expectation_base_;
8785 };
8786
8787 // A set of expectation handles. Useful in the .After() clause of
8788 // EXPECT_CALL() for setting the (partial) order of expectations. The
8789 // syntax:
8790 //
8791 // ExpectationSet es;
8792 // es += EXPECT_CALL(...)...;
8793 // es += EXPECT_CALL(...)...;
8794 // EXPECT_CALL(...).After(es)...;
8795 //
8796 // sets three expectations where the last one can only be matched
8797 // after the first two have both been satisfied.
8798 //
8799 // This class is copyable and has value semantics.
8800 class ExpectationSet {
8801 public:
8802 // A bidirectional iterator that can read a const element in the set.
8803 typedef Expectation::Set::const_iterator const_iterator;
8804
8805 // An object stored in the set. This is an alias of Expectation.
8806 typedef Expectation::Set::value_type value_type;
8807
8808 // Constructs an empty set.
8809 ExpectationSet() {}
8810
8811 // This single-argument ctor must not be explicit, in order to support the
8812 // ExpectationSet es = EXPECT_CALL(...);
8813 // syntax.
8814 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
8815 *this += Expectation(exp);
8816 }
8817
8818 // This single-argument ctor implements implicit conversion from
8819 // Expectation and thus must not be explicit. This allows either an
8820 // Expectation or an ExpectationSet to be used in .After().
8821 ExpectationSet(const Expectation& e) { // NOLINT
8822 *this += e;
8823 }
8824
8825 // The compiler-generator ctor and operator= works exactly as
8826 // intended, so we don't need to define our own.
8827
8828 // Returns true if and only if rhs contains the same set of Expectation
8829 // objects as this does.
8830 bool operator==(const ExpectationSet& rhs) const {
8831 return expectations_ == rhs.expectations_;
8832 }
8833
8834 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
8835
8836 // Implements the syntax
8837 // expectation_set += EXPECT_CALL(...);
8838 ExpectationSet& operator+=(const Expectation& e) {
8839 expectations_.insert(e);
8840 return *this;
8841 }
8842
8843 int size() const { return static_cast<int>(expectations_.size()); }
8844
8845 const_iterator begin() const { return expectations_.begin(); }
8846 const_iterator end() const { return expectations_.end(); }
8847
8848 private:
8849 Expectation::Set expectations_;
8850 };
8851
8852
8853 // Sequence objects are used by a user to specify the relative order
8854 // in which the expectations should match. They are copyable (we rely
8855 // on the compiler-defined copy constructor and assignment operator).
8856 class GTEST_API_ Sequence {
8857 public:
8858 // Constructs an empty sequence.
8859 Sequence() : last_expectation_(new Expectation) {}
8860
8861 // Adds an expectation to this sequence. The caller must ensure
8862 // that no other thread is accessing this Sequence object.
8863 void AddExpectation(const Expectation& expectation) const;
8864
8865 private:
8866 // The last expectation in this sequence.
8867 std::shared_ptr<Expectation> last_expectation_;
8868 }; // class Sequence
8869
8870 // An object of this type causes all EXPECT_CALL() statements
8871 // encountered in its scope to be put in an anonymous sequence. The
8872 // work is done in the constructor and destructor. You should only
8873 // create an InSequence object on the stack.
8874 //
8875 // The sole purpose for this class is to support easy definition of
8876 // sequential expectations, e.g.
8877 //
8878 // {
8879 // InSequence dummy; // The name of the object doesn't matter.
8880 //
8881 // // The following expectations must match in the order they appear.
8882 // EXPECT_CALL(a, Bar())...;
8883 // EXPECT_CALL(a, Baz())...;
8884 // ...
8885 // EXPECT_CALL(b, Xyz())...;
8886 // }
8887 //
8888 // You can create InSequence objects in multiple threads, as long as
8889 // they are used to affect different mock objects. The idea is that
8890 // each thread can create and set up its own mocks as if it's the only
8891 // thread. However, for clarity of your tests we recommend you to set
8892 // up mocks in the main thread unless you have a good reason not to do
8893 // so.
8894 class GTEST_API_ InSequence {
8895 public:
8896 InSequence();
8897 ~InSequence();
8898 private:
8899 bool sequence_created_;
8900
8901 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
8902 } GTEST_ATTRIBUTE_UNUSED_;
8903
8904 namespace internal {
8905
8906 // Points to the implicit sequence introduced by a living InSequence
8907 // object (if any) in the current thread or NULL.
8908 GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
8909
8910 // Base class for implementing expectations.
8911 //
8912 // There are two reasons for having a type-agnostic base class for
8913 // Expectation:
8914 //
8915 // 1. We need to store collections of expectations of different
8916 // types (e.g. all pre-requisites of a particular expectation, all
8917 // expectations in a sequence). Therefore these expectation objects
8918 // must share a common base class.
8919 //
8920 // 2. We can avoid binary code bloat by moving methods not depending
8921 // on the template argument of Expectation to the base class.
8922 //
8923 // This class is internal and mustn't be used by user code directly.
8924 class GTEST_API_ ExpectationBase {
8925 public:
8926 // source_text is the EXPECT_CALL(...) source that created this Expectation.
8927 ExpectationBase(const char* file, int line, const std::string& source_text);
8928
8929 virtual ~ExpectationBase();
8930
8931 // Where in the source file was the expectation spec defined?
8932 const char* file() const { return file_; }
8933 int line() const { return line_; }
8934 const char* source_text() const { return source_text_.c_str(); }
8935 // Returns the cardinality specified in the expectation spec.
8936 const Cardinality& cardinality() const { return cardinality_; }
8937
8938 // Describes the source file location of this expectation.
8939 void DescribeLocationTo(::std::ostream* os) const {
8940 *os << FormatFileLocation(file(), line()) << " ";
8941 }
8942
8943 // Describes how many times a function call matching this
8944 // expectation has occurred.
8945 void DescribeCallCountTo(::std::ostream* os) const
8946 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
8947
8948 // If this mock method has an extra matcher (i.e. .With(matcher)),
8949 // describes it to the ostream.
8950 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
8951
8952 protected:
8953 friend class ::testing::Expectation;
8954 friend class UntypedFunctionMockerBase;
8955
8956 enum Clause {
8957 // Don't change the order of the enum members!
8958 kNone,
8959 kWith,
8960 kTimes,
8961 kInSequence,
8962 kAfter,
8963 kWillOnce,
8964 kWillRepeatedly,
8965 kRetiresOnSaturation
8966 };
8967
8968 typedef std::vector<const void*> UntypedActions;
8969
8970 // Returns an Expectation object that references and co-owns this
8971 // expectation.
8972 virtual Expectation GetHandle() = 0;
8973
8974 // Asserts that the EXPECT_CALL() statement has the given property.
8975 void AssertSpecProperty(bool property,
8976 const std::string& failure_message) const {
8977 Assert(property, file_, line_, failure_message);
8978 }
8979
8980 // Expects that the EXPECT_CALL() statement has the given property.
8981 void ExpectSpecProperty(bool property,
8982 const std::string& failure_message) const {
8983 Expect(property, file_, line_, failure_message);
8984 }
8985
8986 // Explicitly specifies the cardinality of this expectation. Used
8987 // by the subclasses to implement the .Times() clause.
8988 void SpecifyCardinality(const Cardinality& cardinality);
8989
8990 // Returns true if and only if the user specified the cardinality
8991 // explicitly using a .Times().
8992 bool cardinality_specified() const { return cardinality_specified_; }
8993
8994 // Sets the cardinality of this expectation spec.
8995 void set_cardinality(const Cardinality& a_cardinality) {
8996 cardinality_ = a_cardinality;
8997 }
8998
8999 // The following group of methods should only be called after the
9000 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
9001 // the current thread.
9002
9003 // Retires all pre-requisites of this expectation.
9004 void RetireAllPreRequisites()
9005 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
9006
9007 // Returns true if and only if this expectation is retired.
9008 bool is_retired() const
9009 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9010 g_gmock_mutex.AssertHeld();
9011 return retired_;
9012 }
9013
9014 // Retires this expectation.
9015 void Retire()
9016 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9017 g_gmock_mutex.AssertHeld();
9018 retired_ = true;
9019 }
9020
9021 // Returns true if and only if this expectation is satisfied.
9022 bool IsSatisfied() const
9023 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9024 g_gmock_mutex.AssertHeld();
9025 return cardinality().IsSatisfiedByCallCount(call_count_);
9026 }
9027
9028 // Returns true if and only if this expectation is saturated.
9029 bool IsSaturated() const
9030 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9031 g_gmock_mutex.AssertHeld();
9032 return cardinality().IsSaturatedByCallCount(call_count_);
9033 }
9034
9035 // Returns true if and only if this expectation is over-saturated.
9036 bool IsOverSaturated() const
9037 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9038 g_gmock_mutex.AssertHeld();
9039 return cardinality().IsOverSaturatedByCallCount(call_count_);
9040 }
9041
9042 // Returns true if and only if all pre-requisites of this expectation are
9043 // satisfied.
9044 bool AllPrerequisitesAreSatisfied() const
9045 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
9046
9047 // Adds unsatisfied pre-requisites of this expectation to 'result'.
9048 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
9049 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
9050
9051 // Returns the number this expectation has been invoked.
9052 int call_count() const
9053 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9054 g_gmock_mutex.AssertHeld();
9055 return call_count_;
9056 }
9057
9058 // Increments the number this expectation has been invoked.
9059 void IncrementCallCount()
9060 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9061 g_gmock_mutex.AssertHeld();
9062 call_count_++;
9063 }
9064
9065 // Checks the action count (i.e. the number of WillOnce() and
9066 // WillRepeatedly() clauses) against the cardinality if this hasn't
9067 // been done before. Prints a warning if there are too many or too
9068 // few actions.
9069 void CheckActionCountIfNotDone() const
9070 GTEST_LOCK_EXCLUDED_(mutex_);
9071
9072 friend class ::testing::Sequence;
9073 friend class ::testing::internal::ExpectationTester;
9074
9075 template <typename Function>
9076 friend class TypedExpectation;
9077
9078 // Implements the .Times() clause.
9079 void UntypedTimes(const Cardinality& a_cardinality);
9080
9081 // This group of fields are part of the spec and won't change after
9082 // an EXPECT_CALL() statement finishes.
9083 const char* file_; // The file that contains the expectation.
9084 int line_; // The line number of the expectation.
9085 const std::string source_text_; // The EXPECT_CALL(...) source text.
9086 // True if and only if the cardinality is specified explicitly.
9087 bool cardinality_specified_;
9088 Cardinality cardinality_; // The cardinality of the expectation.
9089 // The immediate pre-requisites (i.e. expectations that must be
9090 // satisfied before this expectation can be matched) of this
9091 // expectation. We use std::shared_ptr in the set because we want an
9092 // Expectation object to be co-owned by its FunctionMocker and its
9093 // successors. This allows multiple mock objects to be deleted at
9094 // different times.
9095 ExpectationSet immediate_prerequisites_;
9096
9097 // This group of fields are the current state of the expectation,
9098 // and can change as the mock function is called.
9099 int call_count_; // How many times this expectation has been invoked.
9100 bool retired_; // True if and only if this expectation has retired.
9101 UntypedActions untyped_actions_;
9102 bool extra_matcher_specified_;
9103 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
9104 bool retires_on_saturation_;
9105 Clause last_clause_;
9106 mutable bool action_count_checked_; // Under mutex_.
9107 mutable Mutex mutex_; // Protects action_count_checked_.
9108 }; // class ExpectationBase
9109
9110 // Impements an expectation for the given function type.
9111 template <typename F>
9112 class TypedExpectation : public ExpectationBase {
9113 public:
9114 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
9115 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
9116 typedef typename Function<F>::Result Result;
9117
9118 TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
9119 const std::string& a_source_text,
9120 const ArgumentMatcherTuple& m)
9121 : ExpectationBase(a_file, a_line, a_source_text),
9122 owner_(owner),
9123 matchers_(m),
9124 // By default, extra_matcher_ should match anything. However,
9125 // we cannot initialize it with _ as that causes ambiguity between
9126 // Matcher's copy and move constructor for some argument types.
9127 extra_matcher_(A<const ArgumentTuple&>()),
9128 repeated_action_(DoDefault()) {}
9129
9130 ~TypedExpectation() override {
9131 // Check the validity of the action count if it hasn't been done
9132 // yet (for example, if the expectation was never used).
9133 CheckActionCountIfNotDone();
9134 for (UntypedActions::const_iterator it = untyped_actions_.begin();
9135 it != untyped_actions_.end(); ++it) {
9136 delete static_cast<const Action<F>*>(*it);
9137 }
9138 }
9139
9140 // Implements the .With() clause.
9141 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
9142 if (last_clause_ == kWith) {
9143 ExpectSpecProperty(false,
9144 ".With() cannot appear "
9145 "more than once in an EXPECT_CALL().");
9146 } else {
9147 ExpectSpecProperty(last_clause_ < kWith,
9148 ".With() must be the first "
9149 "clause in an EXPECT_CALL().");
9150 }
9151 last_clause_ = kWith;
9152
9153 extra_matcher_ = m;
9154 extra_matcher_specified_ = true;
9155 return *this;
9156 }
9157
9158 // Implements the .Times() clause.
9159 TypedExpectation& Times(const Cardinality& a_cardinality) {
9160 ExpectationBase::UntypedTimes(a_cardinality);
9161 return *this;
9162 }
9163
9164 // Implements the .Times() clause.
9165 TypedExpectation& Times(int n) {
9166 return Times(Exactly(n));
9167 }
9168
9169 // Implements the .InSequence() clause.
9170 TypedExpectation& InSequence(const Sequence& s) {
9171 ExpectSpecProperty(last_clause_ <= kInSequence,
9172 ".InSequence() cannot appear after .After(),"
9173 " .WillOnce(), .WillRepeatedly(), or "
9174 ".RetiresOnSaturation().");
9175 last_clause_ = kInSequence;
9176
9177 s.AddExpectation(GetHandle());
9178 return *this;
9179 }
9180 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
9181 return InSequence(s1).InSequence(s2);
9182 }
9183 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
9184 const Sequence& s3) {
9185 return InSequence(s1, s2).InSequence(s3);
9186 }
9187 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
9188 const Sequence& s3, const Sequence& s4) {
9189 return InSequence(s1, s2, s3).InSequence(s4);
9190 }
9191 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
9192 const Sequence& s3, const Sequence& s4,
9193 const Sequence& s5) {
9194 return InSequence(s1, s2, s3, s4).InSequence(s5);
9195 }
9196
9197 // Implements that .After() clause.
9198 TypedExpectation& After(const ExpectationSet& s) {
9199 ExpectSpecProperty(last_clause_ <= kAfter,
9200 ".After() cannot appear after .WillOnce(),"
9201 " .WillRepeatedly(), or "
9202 ".RetiresOnSaturation().");
9203 last_clause_ = kAfter;
9204
9205 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
9206 immediate_prerequisites_ += *it;
9207 }
9208 return *this;
9209 }
9210 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
9211 return After(s1).After(s2);
9212 }
9213 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
9214 const ExpectationSet& s3) {
9215 return After(s1, s2).After(s3);
9216 }
9217 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
9218 const ExpectationSet& s3, const ExpectationSet& s4) {
9219 return After(s1, s2, s3).After(s4);
9220 }
9221 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
9222 const ExpectationSet& s3, const ExpectationSet& s4,
9223 const ExpectationSet& s5) {
9224 return After(s1, s2, s3, s4).After(s5);
9225 }
9226
9227 // Implements the .WillOnce() clause.
9228 TypedExpectation& WillOnce(const Action<F>& action) {
9229 ExpectSpecProperty(last_clause_ <= kWillOnce,
9230 ".WillOnce() cannot appear after "
9231 ".WillRepeatedly() or .RetiresOnSaturation().");
9232 last_clause_ = kWillOnce;
9233
9234 untyped_actions_.push_back(new Action<F>(action));
9235 if (!cardinality_specified()) {
9236 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
9237 }
9238 return *this;
9239 }
9240
9241 // Implements the .WillRepeatedly() clause.
9242 TypedExpectation& WillRepeatedly(const Action<F>& action) {
9243 if (last_clause_ == kWillRepeatedly) {
9244 ExpectSpecProperty(false,
9245 ".WillRepeatedly() cannot appear "
9246 "more than once in an EXPECT_CALL().");
9247 } else {
9248 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
9249 ".WillRepeatedly() cannot appear "
9250 "after .RetiresOnSaturation().");
9251 }
9252 last_clause_ = kWillRepeatedly;
9253 repeated_action_specified_ = true;
9254
9255 repeated_action_ = action;
9256 if (!cardinality_specified()) {
9257 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
9258 }
9259
9260 // Now that no more action clauses can be specified, we check
9261 // whether their count makes sense.
9262 CheckActionCountIfNotDone();
9263 return *this;
9264 }
9265
9266 // Implements the .RetiresOnSaturation() clause.
9267 TypedExpectation& RetiresOnSaturation() {
9268 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
9269 ".RetiresOnSaturation() cannot appear "
9270 "more than once.");
9271 last_clause_ = kRetiresOnSaturation;
9272 retires_on_saturation_ = true;
9273
9274 // Now that no more action clauses can be specified, we check
9275 // whether their count makes sense.
9276 CheckActionCountIfNotDone();
9277 return *this;
9278 }
9279
9280 // Returns the matchers for the arguments as specified inside the
9281 // EXPECT_CALL() macro.
9282 const ArgumentMatcherTuple& matchers() const {
9283 return matchers_;
9284 }
9285
9286 // Returns the matcher specified by the .With() clause.
9287 const Matcher<const ArgumentTuple&>& extra_matcher() const {
9288 return extra_matcher_;
9289 }
9290
9291 // Returns the action specified by the .WillRepeatedly() clause.
9292 const Action<F>& repeated_action() const { return repeated_action_; }
9293
9294 // If this mock method has an extra matcher (i.e. .With(matcher)),
9295 // describes it to the ostream.
9296 void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
9297 if (extra_matcher_specified_) {
9298 *os << " Expected args: ";
9299 extra_matcher_.DescribeTo(os);
9300 *os << "\n";
9301 }
9302 }
9303
9304 private:
9305 template <typename Function>
9306 friend class FunctionMocker;
9307
9308 // Returns an Expectation object that references and co-owns this
9309 // expectation.
9310 Expectation GetHandle() override { return owner_->GetHandleOf(this); }
9311
9312 // The following methods will be called only after the EXPECT_CALL()
9313 // statement finishes and when the current thread holds
9314 // g_gmock_mutex.
9315
9316 // Returns true if and only if this expectation matches the given arguments.
9317 bool Matches(const ArgumentTuple& args) const
9318 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9319 g_gmock_mutex.AssertHeld();
9320 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
9321 }
9322
9323 // Returns true if and only if this expectation should handle the given
9324 // arguments.
9325 bool ShouldHandleArguments(const ArgumentTuple& args) const
9326 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9327 g_gmock_mutex.AssertHeld();
9328
9329 // In case the action count wasn't checked when the expectation
9330 // was defined (e.g. if this expectation has no WillRepeatedly()
9331 // or RetiresOnSaturation() clause), we check it when the
9332 // expectation is used for the first time.
9333 CheckActionCountIfNotDone();
9334 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
9335 }
9336
9337 // Describes the result of matching the arguments against this
9338 // expectation to the given ostream.
9339 void ExplainMatchResultTo(
9340 const ArgumentTuple& args,
9341 ::std::ostream* os) const
9342 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9343 g_gmock_mutex.AssertHeld();
9344
9345 if (is_retired()) {
9346 *os << " Expected: the expectation is active\n"
9347 << " Actual: it is retired\n";
9348 } else if (!Matches(args)) {
9349 if (!TupleMatches(matchers_, args)) {
9350 ExplainMatchFailureTupleTo(matchers_, args, os);
9351 }
9352 StringMatchResultListener listener;
9353 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
9354 *os << " Expected args: ";
9355 extra_matcher_.DescribeTo(os);
9356 *os << "\n Actual: don't match";
9357
9358 internal::PrintIfNotEmpty(listener.str(), os);
9359 *os << "\n";
9360 }
9361 } else if (!AllPrerequisitesAreSatisfied()) {
9362 *os << " Expected: all pre-requisites are satisfied\n"
9363 << " Actual: the following immediate pre-requisites "
9364 << "are not satisfied:\n";
9365 ExpectationSet unsatisfied_prereqs;
9366 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
9367 int i = 0;
9368 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
9369 it != unsatisfied_prereqs.end(); ++it) {
9370 it->expectation_base()->DescribeLocationTo(os);
9371 *os << "pre-requisite #" << i++ << "\n";
9372 }
9373 *os << " (end of pre-requisites)\n";
9374 } else {
9375 // This line is here just for completeness' sake. It will never
9376 // be executed as currently the ExplainMatchResultTo() function
9377 // is called only when the mock function call does NOT match the
9378 // expectation.
9379 *os << "The call matches the expectation.\n";
9380 }
9381 }
9382
9383 // Returns the action that should be taken for the current invocation.
9384 const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
9385 const ArgumentTuple& args) const
9386 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9387 g_gmock_mutex.AssertHeld();
9388 const int count = call_count();
9389 Assert(count >= 1, __FILE__, __LINE__,
9390 "call_count() is <= 0 when GetCurrentAction() is "
9391 "called - this should never happen.");
9392
9393 const int action_count = static_cast<int>(untyped_actions_.size());
9394 if (action_count > 0 && !repeated_action_specified_ &&
9395 count > action_count) {
9396 // If there is at least one WillOnce() and no WillRepeatedly(),
9397 // we warn the user when the WillOnce() clauses ran out.
9398 ::std::stringstream ss;
9399 DescribeLocationTo(&ss);
9400 ss << "Actions ran out in " << source_text() << "...\n"
9401 << "Called " << count << " times, but only "
9402 << action_count << " WillOnce()"
9403 << (action_count == 1 ? " is" : "s are") << " specified - ";
9404 mocker->DescribeDefaultActionTo(args, &ss);
9405 Log(kWarning, ss.str(), 1);
9406 }
9407
9408 return count <= action_count
9409 ? *static_cast<const Action<F>*>(
9410 untyped_actions_[static_cast<size_t>(count - 1)])
9411 : repeated_action();
9412 }
9413
9414 // Given the arguments of a mock function call, if the call will
9415 // over-saturate this expectation, returns the default action;
9416 // otherwise, returns the next action in this expectation. Also
9417 // describes *what* happened to 'what', and explains *why* Google
9418 // Mock does it to 'why'. This method is not const as it calls
9419 // IncrementCallCount(). A return value of NULL means the default
9420 // action.
9421 const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
9422 const ArgumentTuple& args,
9423 ::std::ostream* what,
9424 ::std::ostream* why)
9425 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9426 g_gmock_mutex.AssertHeld();
9427 if (IsSaturated()) {
9428 // We have an excessive call.
9429 IncrementCallCount();
9430 *what << "Mock function called more times than expected - ";
9431 mocker->DescribeDefaultActionTo(args, what);
9432 DescribeCallCountTo(why);
9433
9434 return nullptr;
9435 }
9436
9437 IncrementCallCount();
9438 RetireAllPreRequisites();
9439
9440 if (retires_on_saturation_ && IsSaturated()) {
9441 Retire();
9442 }
9443
9444 // Must be done after IncrementCount()!
9445 *what << "Mock function call matches " << source_text() <<"...\n";
9446 return &(GetCurrentAction(mocker, args));
9447 }
9448
9449 // All the fields below won't change once the EXPECT_CALL()
9450 // statement finishes.
9451 FunctionMocker<F>* const owner_;
9452 ArgumentMatcherTuple matchers_;
9453 Matcher<const ArgumentTuple&> extra_matcher_;
9454 Action<F> repeated_action_;
9455
9456 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
9457 }; // class TypedExpectation
9458
9459 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
9460 // specifying the default behavior of, or expectation on, a mock
9461 // function.
9462
9463 // Note: class MockSpec really belongs to the ::testing namespace.
9464 // However if we define it in ::testing, MSVC will complain when
9465 // classes in ::testing::internal declare it as a friend class
9466 // template. To workaround this compiler bug, we define MockSpec in
9467 // ::testing::internal and import it into ::testing.
9468
9469 // Logs a message including file and line number information.
9470 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
9471 const char* file, int line,
9472 const std::string& message);
9473
9474 template <typename F>
9475 class MockSpec {
9476 public:
9477 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
9478 typedef typename internal::Function<F>::ArgumentMatcherTuple
9479 ArgumentMatcherTuple;
9480
9481 // Constructs a MockSpec object, given the function mocker object
9482 // that the spec is associated with.
9483 MockSpec(internal::FunctionMocker<F>* function_mocker,
9484 const ArgumentMatcherTuple& matchers)
9485 : function_mocker_(function_mocker), matchers_(matchers) {}
9486
9487 // Adds a new default action spec to the function mocker and returns
9488 // the newly created spec.
9489 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
9490 const char* file, int line, const char* obj, const char* call) {
9491 LogWithLocation(internal::kInfo, file, line,
9492 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
9493 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
9494 }
9495
9496 // Adds a new expectation spec to the function mocker and returns
9497 // the newly created spec.
9498 internal::TypedExpectation<F>& InternalExpectedAt(
9499 const char* file, int line, const char* obj, const char* call) {
9500 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
9501 call + ")");
9502 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
9503 return function_mocker_->AddNewExpectation(
9504 file, line, source_text, matchers_);
9505 }
9506
9507 // This operator overload is used to swallow the superfluous parameter list
9508 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
9509 // explanation.
9510 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
9511 return *this;
9512 }
9513
9514 private:
9515 template <typename Function>
9516 friend class internal::FunctionMocker;
9517
9518 // The function mocker that owns this spec.
9519 internal::FunctionMocker<F>* const function_mocker_;
9520 // The argument matchers specified in the spec.
9521 ArgumentMatcherTuple matchers_;
9522 }; // class MockSpec
9523
9524 // Wrapper type for generically holding an ordinary value or lvalue reference.
9525 // If T is not a reference type, it must be copyable or movable.
9526 // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
9527 // T is a move-only value type (which means that it will always be copyable
9528 // if the current platform does not support move semantics).
9529 //
9530 // The primary template defines handling for values, but function header
9531 // comments describe the contract for the whole template (including
9532 // specializations).
9533 template <typename T>
9534 class ReferenceOrValueWrapper {
9535 public:
9536 // Constructs a wrapper from the given value/reference.
9537 explicit ReferenceOrValueWrapper(T value)
9538 : value_(std::move(value)) {
9539 }
9540
9541 // Unwraps and returns the underlying value/reference, exactly as
9542 // originally passed. The behavior of calling this more than once on
9543 // the same object is unspecified.
9544 T Unwrap() { return std::move(value_); }
9545
9546 // Provides nondestructive access to the underlying value/reference.
9547 // Always returns a const reference (more precisely,
9548 // const std::add_lvalue_reference<T>::type). The behavior of calling this
9549 // after calling Unwrap on the same object is unspecified.
9550 const T& Peek() const {
9551 return value_;
9552 }
9553
9554 private:
9555 T value_;
9556 };
9557
9558 // Specialization for lvalue reference types. See primary template
9559 // for documentation.
9560 template <typename T>
9561 class ReferenceOrValueWrapper<T&> {
9562 public:
9563 // Workaround for debatable pass-by-reference lint warning (c-library-team
9564 // policy precludes NOLINT in this context)
9565 typedef T& reference;
9566 explicit ReferenceOrValueWrapper(reference ref)
9567 : value_ptr_(&ref) {}
9568 T& Unwrap() { return *value_ptr_; }
9569 const T& Peek() const { return *value_ptr_; }
9570
9571 private:
9572 T* value_ptr_;
9573 };
9574
9575 // C++ treats the void type specially. For example, you cannot define
9576 // a void-typed variable or pass a void value to a function.
9577 // ActionResultHolder<T> holds a value of type T, where T must be a
9578 // copyable type or void (T doesn't need to be default-constructable).
9579 // It hides the syntactic difference between void and other types, and
9580 // is used to unify the code for invoking both void-returning and
9581 // non-void-returning mock functions.
9582
9583 // Untyped base class for ActionResultHolder<T>.
9584 class UntypedActionResultHolderBase {
9585 public:
9586 virtual ~UntypedActionResultHolderBase() {}
9587
9588 // Prints the held value as an action's result to os.
9589 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
9590 };
9591
9592 // This generic definition is used when T is not void.
9593 template <typename T>
9594 class ActionResultHolder : public UntypedActionResultHolderBase {
9595 public:
9596 // Returns the held value. Must not be called more than once.
9597 T Unwrap() {
9598 return result_.Unwrap();
9599 }
9600
9601 // Prints the held value as an action's result to os.
9602 void PrintAsActionResult(::std::ostream* os) const override {
9603 *os << "\n Returns: ";
9604 // T may be a reference type, so we don't use UniversalPrint().
9605 UniversalPrinter<T>::Print(result_.Peek(), os);
9606 }
9607
9608 // Performs the given mock function's default action and returns the
9609 // result in a new-ed ActionResultHolder.
9610 template <typename F>
9611 static ActionResultHolder* PerformDefaultAction(
9612 const FunctionMocker<F>* func_mocker,
9613 typename Function<F>::ArgumentTuple&& args,
9614 const std::string& call_description) {
9615 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
9616 std::move(args), call_description)));
9617 }
9618
9619 // Performs the given action and returns the result in a new-ed
9620 // ActionResultHolder.
9621 template <typename F>
9622 static ActionResultHolder* PerformAction(
9623 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
9624 return new ActionResultHolder(
9625 Wrapper(action.Perform(std::move(args))));
9626 }
9627
9628 private:
9629 typedef ReferenceOrValueWrapper<T> Wrapper;
9630
9631 explicit ActionResultHolder(Wrapper result)
9632 : result_(std::move(result)) {
9633 }
9634
9635 Wrapper result_;
9636
9637 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
9638 };
9639
9640 // Specialization for T = void.
9641 template <>
9642 class ActionResultHolder<void> : public UntypedActionResultHolderBase {
9643 public:
9644 void Unwrap() { }
9645
9646 void PrintAsActionResult(::std::ostream* /* os */) const override {}
9647
9648 // Performs the given mock function's default action and returns ownership
9649 // of an empty ActionResultHolder*.
9650 template <typename F>
9651 static ActionResultHolder* PerformDefaultAction(
9652 const FunctionMocker<F>* func_mocker,
9653 typename Function<F>::ArgumentTuple&& args,
9654 const std::string& call_description) {
9655 func_mocker->PerformDefaultAction(std::move(args), call_description);
9656 return new ActionResultHolder;
9657 }
9658
9659 // Performs the given action and returns ownership of an empty
9660 // ActionResultHolder*.
9661 template <typename F>
9662 static ActionResultHolder* PerformAction(
9663 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
9664 action.Perform(std::move(args));
9665 return new ActionResultHolder;
9666 }
9667
9668 private:
9669 ActionResultHolder() {}
9670 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
9671 };
9672
9673 template <typename F>
9674 class FunctionMocker;
9675
9676 template <typename R, typename... Args>
9677 class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
9678 using F = R(Args...);
9679
9680 public:
9681 using Result = R;
9682 using ArgumentTuple = std::tuple<Args...>;
9683 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
9684
9685 FunctionMocker() {}
9686
9687 // There is no generally useful and implementable semantics of
9688 // copying a mock object, so copying a mock is usually a user error.
9689 // Thus we disallow copying function mockers. If the user really
9690 // wants to copy a mock object, they should implement their own copy
9691 // operation, for example:
9692 //
9693 // class MockFoo : public Foo {
9694 // public:
9695 // // Defines a copy constructor explicitly.
9696 // MockFoo(const MockFoo& src) {}
9697 // ...
9698 // };
9699 FunctionMocker(const FunctionMocker&) = delete;
9700 FunctionMocker& operator=(const FunctionMocker&) = delete;
9701
9702 // The destructor verifies that all expectations on this mock
9703 // function have been satisfied. If not, it will report Google Test
9704 // non-fatal failures for the violations.
9705 ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9706 MutexLock l(&g_gmock_mutex);
9707 VerifyAndClearExpectationsLocked();
9708 Mock::UnregisterLocked(this);
9709 ClearDefaultActionsLocked();
9710 }
9711
9712 // Returns the ON_CALL spec that matches this mock function with the
9713 // given arguments; returns NULL if no matching ON_CALL is found.
9714 // L = *
9715 const OnCallSpec<F>* FindOnCallSpec(
9716 const ArgumentTuple& args) const {
9717 for (UntypedOnCallSpecs::const_reverse_iterator it
9718 = untyped_on_call_specs_.rbegin();
9719 it != untyped_on_call_specs_.rend(); ++it) {
9720 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
9721 if (spec->Matches(args))
9722 return spec;
9723 }
9724
9725 return nullptr;
9726 }
9727
9728 // Performs the default action of this mock function on the given
9729 // arguments and returns the result. Asserts (or throws if
9730 // exceptions are enabled) with a helpful call descrption if there
9731 // is no valid return value. This method doesn't depend on the
9732 // mutable state of this object, and thus can be called concurrently
9733 // without locking.
9734 // L = *
9735 Result PerformDefaultAction(ArgumentTuple&& args,
9736 const std::string& call_description) const {
9737 const OnCallSpec<F>* const spec =
9738 this->FindOnCallSpec(args);
9739 if (spec != nullptr) {
9740 return spec->GetAction().Perform(std::move(args));
9741 }
9742 const std::string message =
9743 call_description +
9744 "\n The mock function has no default action "
9745 "set, and its return type has no default value set.";
9746 #if GTEST_HAS_EXCEPTIONS
9747 if (!DefaultValue<Result>::Exists()) {
9748 throw std::runtime_error(message);
9749 }
9750 #else
9751 Assert(DefaultValue<Result>::Exists(), "", -1, message);
9752 #endif
9753 return DefaultValue<Result>::Get();
9754 }
9755
9756 // Performs the default action with the given arguments and returns
9757 // the action's result. The call description string will be used in
9758 // the error message to describe the call in the case the default
9759 // action fails. The caller is responsible for deleting the result.
9760 // L = *
9761 UntypedActionResultHolderBase* UntypedPerformDefaultAction(
9762 void* untyped_args, // must point to an ArgumentTuple
9763 const std::string& call_description) const override {
9764 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
9765 return ResultHolder::PerformDefaultAction(this, std::move(*args),
9766 call_description);
9767 }
9768
9769 // Performs the given action with the given arguments and returns
9770 // the action's result. The caller is responsible for deleting the
9771 // result.
9772 // L = *
9773 UntypedActionResultHolderBase* UntypedPerformAction(
9774 const void* untyped_action, void* untyped_args) const override {
9775 // Make a copy of the action before performing it, in case the
9776 // action deletes the mock object (and thus deletes itself).
9777 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
9778 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
9779 return ResultHolder::PerformAction(action, std::move(*args));
9780 }
9781
9782 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
9783 // clears the ON_CALL()s set on this mock function.
9784 void ClearDefaultActionsLocked() override
9785 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9786 g_gmock_mutex.AssertHeld();
9787
9788 // Deleting our default actions may trigger other mock objects to be
9789 // deleted, for example if an action contains a reference counted smart
9790 // pointer to that mock object, and that is the last reference. So if we
9791 // delete our actions within the context of the global mutex we may deadlock
9792 // when this method is called again. Instead, make a copy of the set of
9793 // actions to delete, clear our set within the mutex, and then delete the
9794 // actions outside of the mutex.
9795 UntypedOnCallSpecs specs_to_delete;
9796 untyped_on_call_specs_.swap(specs_to_delete);
9797
9798 g_gmock_mutex.Unlock();
9799 for (UntypedOnCallSpecs::const_iterator it =
9800 specs_to_delete.begin();
9801 it != specs_to_delete.end(); ++it) {
9802 delete static_cast<const OnCallSpec<F>*>(*it);
9803 }
9804
9805 // Lock the mutex again, since the caller expects it to be locked when we
9806 // return.
9807 g_gmock_mutex.Lock();
9808 }
9809
9810 // Returns the result of invoking this mock function with the given
9811 // arguments. This function can be safely called from multiple
9812 // threads concurrently.
9813 Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9814 ArgumentTuple tuple(std::forward<Args>(args)...);
9815 std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
9816 this->UntypedInvokeWith(static_cast<void*>(&tuple))));
9817 return holder->Unwrap();
9818 }
9819
9820 MockSpec<F> With(Matcher<Args>... m) {
9821 return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
9822 }
9823
9824 protected:
9825 template <typename Function>
9826 friend class MockSpec;
9827
9828 typedef ActionResultHolder<Result> ResultHolder;
9829
9830 // Adds and returns a default action spec for this mock function.
9831 OnCallSpec<F>& AddNewOnCallSpec(
9832 const char* file, int line,
9833 const ArgumentMatcherTuple& m)
9834 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9835 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
9836 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
9837 untyped_on_call_specs_.push_back(on_call_spec);
9838 return *on_call_spec;
9839 }
9840
9841 // Adds and returns an expectation spec for this mock function.
9842 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
9843 const std::string& source_text,
9844 const ArgumentMatcherTuple& m)
9845 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9846 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
9847 TypedExpectation<F>* const expectation =
9848 new TypedExpectation<F>(this, file, line, source_text, m);
9849 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
9850 // See the definition of untyped_expectations_ for why access to
9851 // it is unprotected here.
9852 untyped_expectations_.push_back(untyped_expectation);
9853
9854 // Adds this expectation into the implicit sequence if there is one.
9855 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
9856 if (implicit_sequence != nullptr) {
9857 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
9858 }
9859
9860 return *expectation;
9861 }
9862
9863 private:
9864 template <typename Func> friend class TypedExpectation;
9865
9866 // Some utilities needed for implementing UntypedInvokeWith().
9867
9868 // Describes what default action will be performed for the given
9869 // arguments.
9870 // L = *
9871 void DescribeDefaultActionTo(const ArgumentTuple& args,
9872 ::std::ostream* os) const {
9873 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
9874
9875 if (spec == nullptr) {
9876 *os << (std::is_void<Result>::value ? "returning directly.\n"
9877 : "returning default value.\n");
9878 } else {
9879 *os << "taking default action specified at:\n"
9880 << FormatFileLocation(spec->file(), spec->line()) << "\n";
9881 }
9882 }
9883
9884 // Writes a message that the call is uninteresting (i.e. neither
9885 // explicitly expected nor explicitly unexpected) to the given
9886 // ostream.
9887 void UntypedDescribeUninterestingCall(const void* untyped_args,
9888 ::std::ostream* os) const override
9889 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9890 const ArgumentTuple& args =
9891 *static_cast<const ArgumentTuple*>(untyped_args);
9892 *os << "Uninteresting mock function call - ";
9893 DescribeDefaultActionTo(args, os);
9894 *os << " Function call: " << Name();
9895 UniversalPrint(args, os);
9896 }
9897
9898 // Returns the expectation that matches the given function arguments
9899 // (or NULL is there's no match); when a match is found,
9900 // untyped_action is set to point to the action that should be
9901 // performed (or NULL if the action is "do default"), and
9902 // is_excessive is modified to indicate whether the call exceeds the
9903 // expected number.
9904 //
9905 // Critical section: We must find the matching expectation and the
9906 // corresponding action that needs to be taken in an ATOMIC
9907 // transaction. Otherwise another thread may call this mock
9908 // method in the middle and mess up the state.
9909 //
9910 // However, performing the action has to be left out of the critical
9911 // section. The reason is that we have no control on what the
9912 // action does (it can invoke an arbitrary user function or even a
9913 // mock function) and excessive locking could cause a dead lock.
9914 const ExpectationBase* UntypedFindMatchingExpectation(
9915 const void* untyped_args, const void** untyped_action, bool* is_excessive,
9916 ::std::ostream* what, ::std::ostream* why) override
9917 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
9918 const ArgumentTuple& args =
9919 *static_cast<const ArgumentTuple*>(untyped_args);
9920 MutexLock l(&g_gmock_mutex);
9921 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
9922 if (exp == nullptr) { // A match wasn't found.
9923 this->FormatUnexpectedCallMessageLocked(args, what, why);
9924 return nullptr;
9925 }
9926
9927 // This line must be done before calling GetActionForArguments(),
9928 // which will increment the call count for *exp and thus affect
9929 // its saturation status.
9930 *is_excessive = exp->IsSaturated();
9931 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
9932 if (action != nullptr && action->IsDoDefault())
9933 action = nullptr; // Normalize "do default" to NULL.
9934 *untyped_action = action;
9935 return exp;
9936 }
9937
9938 // Prints the given function arguments to the ostream.
9939 void UntypedPrintArgs(const void* untyped_args,
9940 ::std::ostream* os) const override {
9941 const ArgumentTuple& args =
9942 *static_cast<const ArgumentTuple*>(untyped_args);
9943 UniversalPrint(args, os);
9944 }
9945
9946 // Returns the expectation that matches the arguments, or NULL if no
9947 // expectation matches them.
9948 TypedExpectation<F>* FindMatchingExpectationLocked(
9949 const ArgumentTuple& args) const
9950 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9951 g_gmock_mutex.AssertHeld();
9952 // See the definition of untyped_expectations_ for why access to
9953 // it is unprotected here.
9954 for (typename UntypedExpectations::const_reverse_iterator it =
9955 untyped_expectations_.rbegin();
9956 it != untyped_expectations_.rend(); ++it) {
9957 TypedExpectation<F>* const exp =
9958 static_cast<TypedExpectation<F>*>(it->get());
9959 if (exp->ShouldHandleArguments(args)) {
9960 return exp;
9961 }
9962 }
9963 return nullptr;
9964 }
9965
9966 // Returns a message that the arguments don't match any expectation.
9967 void FormatUnexpectedCallMessageLocked(
9968 const ArgumentTuple& args,
9969 ::std::ostream* os,
9970 ::std::ostream* why) const
9971 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9972 g_gmock_mutex.AssertHeld();
9973 *os << "\nUnexpected mock function call - ";
9974 DescribeDefaultActionTo(args, os);
9975 PrintTriedExpectationsLocked(args, why);
9976 }
9977
9978 // Prints a list of expectations that have been tried against the
9979 // current mock function call.
9980 void PrintTriedExpectationsLocked(
9981 const ArgumentTuple& args,
9982 ::std::ostream* why) const
9983 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
9984 g_gmock_mutex.AssertHeld();
9985 const size_t count = untyped_expectations_.size();
9986 *why << "Google Mock tried the following " << count << " "
9987 << (count == 1 ? "expectation, but it didn't match" :
9988 "expectations, but none matched")
9989 << ":\n";
9990 for (size_t i = 0; i < count; i++) {
9991 TypedExpectation<F>* const expectation =
9992 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
9993 *why << "\n";
9994 expectation->DescribeLocationTo(why);
9995 if (count > 1) {
9996 *why << "tried expectation #" << i << ": ";
9997 }
9998 *why << expectation->source_text() << "...\n";
9999 expectation->ExplainMatchResultTo(args, why);
10000 expectation->DescribeCallCountTo(why);
10001 }
10002 }
10003 }; // class FunctionMocker
10004
10005 // Reports an uninteresting call (whose description is in msg) in the
10006 // manner specified by 'reaction'.
10007 void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
10008
10009 } // namespace internal
10010
10011 namespace internal {
10012
10013 template <typename F>
10014 class MockFunction;
10015
10016 template <typename R, typename... Args>
10017 class MockFunction<R(Args...)> {
10018 public:
10019 MockFunction(const MockFunction&) = delete;
10020 MockFunction& operator=(const MockFunction&) = delete;
10021
10022 std::function<R(Args...)> AsStdFunction() {
10023 return [this](Args... args) -> R {
10024 return this->Call(std::forward<Args>(args)...);
10025 };
10026 }
10027
10028 // Implementation detail: the expansion of the MOCK_METHOD macro.
10029 R Call(Args... args) {
10030 mock_.SetOwnerAndName(this, "Call");
10031 return mock_.Invoke(std::forward<Args>(args)...);
10032 }
10033
10034 MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
10035 mock_.RegisterOwner(this);
10036 return mock_.With(std::move(m)...);
10037 }
10038
10039 MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
10040 return this->gmock_Call(::testing::A<Args>()...);
10041 }
10042
10043 protected:
10044 MockFunction() = default;
10045 ~MockFunction() = default;
10046
10047 private:
10048 FunctionMocker<R(Args...)> mock_;
10049 };
10050
10051 /*
10052 The SignatureOf<F> struct is a meta-function returning function signature
10053 corresponding to the provided F argument.
10054
10055 It makes use of MockFunction easier by allowing it to accept more F arguments
10056 than just function signatures.
10057
10058 Specializations provided here cover only a signature type itself and
10059 std::function. However, if need be it can be easily extended to cover also other
10060 types (like for example boost::function).
10061 */
10062
10063 template <typename F>
10064 struct SignatureOf;
10065
10066 template <typename R, typename... Args>
10067 struct SignatureOf<R(Args...)> {
10068 using type = R(Args...);
10069 };
10070
10071 template <typename F>
10072 struct SignatureOf<std::function<F>> : SignatureOf<F> {};
10073
10074 template <typename F>
10075 using SignatureOfT = typename SignatureOf<F>::type;
10076
10077 } // namespace internal
10078
10079 // A MockFunction<F> type has one mock method whose type is
10080 // internal::SignatureOfT<F>. It is useful when you just want your
10081 // test code to emit some messages and have Google Mock verify the
10082 // right messages are sent (and perhaps at the right times). For
10083 // example, if you are exercising code:
10084 //
10085 // Foo(1);
10086 // Foo(2);
10087 // Foo(3);
10088 //
10089 // and want to verify that Foo(1) and Foo(3) both invoke
10090 // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
10091 //
10092 // TEST(FooTest, InvokesBarCorrectly) {
10093 // MyMock mock;
10094 // MockFunction<void(string check_point_name)> check;
10095 // {
10096 // InSequence s;
10097 //
10098 // EXPECT_CALL(mock, Bar("a"));
10099 // EXPECT_CALL(check, Call("1"));
10100 // EXPECT_CALL(check, Call("2"));
10101 // EXPECT_CALL(mock, Bar("a"));
10102 // }
10103 // Foo(1);
10104 // check.Call("1");
10105 // Foo(2);
10106 // check.Call("2");
10107 // Foo(3);
10108 // }
10109 //
10110 // The expectation spec says that the first Bar("a") must happen
10111 // before check point "1", the second Bar("a") must happen after check
10112 // point "2", and nothing should happen between the two check
10113 // points. The explicit check points make it easy to tell which
10114 // Bar("a") is called by which call to Foo().
10115 //
10116 // MockFunction<F> can also be used to exercise code that accepts
10117 // std::function<internal::SignatureOfT<F>> callbacks. To do so, use
10118 // AsStdFunction() method to create std::function proxy forwarding to
10119 // original object's Call. Example:
10120 //
10121 // TEST(FooTest, RunsCallbackWithBarArgument) {
10122 // MockFunction<int(string)> callback;
10123 // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
10124 // Foo(callback.AsStdFunction());
10125 // }
10126 //
10127 // The internal::SignatureOfT<F> indirection allows to use other types
10128 // than just function signature type. This is typically useful when
10129 // providing a mock for a predefined std::function type. Example:
10130 //
10131 // using FilterPredicate = std::function<bool(string)>;
10132 // void MyFilterAlgorithm(FilterPredicate predicate);
10133 //
10134 // TEST(FooTest, FilterPredicateAlwaysAccepts) {
10135 // MockFunction<FilterPredicate> predicateMock;
10136 // EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
10137 // MyFilterAlgorithm(predicateMock.AsStdFunction());
10138 // }
10139 template <typename F>
10140 class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
10141 using Base = internal::MockFunction<internal::SignatureOfT<F>>;
10142
10143 public:
10144 using Base::Base;
10145 };
10146
10147 // The style guide prohibits "using" statements in a namespace scope
10148 // inside a header file. However, the MockSpec class template is
10149 // meant to be defined in the ::testing namespace. The following line
10150 // is just a trick for working around a bug in MSVC 8.0, which cannot
10151 // handle it if we define MockSpec in ::testing.
10152 using internal::MockSpec;
10153
10154 // Const(x) is a convenient function for obtaining a const reference
10155 // to x. This is useful for setting expectations on an overloaded
10156 // const mock method, e.g.
10157 //
10158 // class MockFoo : public FooInterface {
10159 // public:
10160 // MOCK_METHOD0(Bar, int());
10161 // MOCK_CONST_METHOD0(Bar, int&());
10162 // };
10163 //
10164 // MockFoo foo;
10165 // // Expects a call to non-const MockFoo::Bar().
10166 // EXPECT_CALL(foo, Bar());
10167 // // Expects a call to const MockFoo::Bar().
10168 // EXPECT_CALL(Const(foo), Bar());
10169 template <typename T>
10170 inline const T& Const(const T& x) { return x; }
10171
10172 // Constructs an Expectation object that references and co-owns exp.
10173 inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
10174 : expectation_base_(exp.GetHandle().expectation_base()) {}
10175
10176 } // namespace testing
10177
10178 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
10179
10180 // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
10181 // required to avoid compile errors when the name of the method used in call is
10182 // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
10183 // tests in internal/gmock-spec-builders_test.cc for more details.
10184 //
10185 // This macro supports statements both with and without parameter matchers. If
10186 // the parameter list is omitted, gMock will accept any parameters, which allows
10187 // tests to be written that don't need to encode the number of method
10188 // parameter. This technique may only be used for non-overloaded methods.
10189 //
10190 // // These are the same:
10191 // ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
10192 // ON_CALL(mock, NoArgsMethod).WillByDefault(...);
10193 //
10194 // // As are these:
10195 // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
10196 // ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
10197 //
10198 // // Can also specify args if you want, of course:
10199 // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
10200 //
10201 // // Overloads work as long as you specify parameters:
10202 // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
10203 // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
10204 //
10205 // // Oops! Which overload did you want?
10206 // ON_CALL(mock, OverloadedMethod).WillByDefault(...);
10207 // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
10208 //
10209 // How this works: The mock class uses two overloads of the gmock_Method
10210 // expectation setter method plus an operator() overload on the MockSpec object.
10211 // In the matcher list form, the macro expands to:
10212 //
10213 // // This statement:
10214 // ON_CALL(mock, TwoArgsMethod(_, 45))...
10215 //
10216 // // ...expands to:
10217 // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
10218 // |-------------v---------------||------------v-------------|
10219 // invokes first overload swallowed by operator()
10220 //
10221 // // ...which is essentially:
10222 // mock.gmock_TwoArgsMethod(_, 45)...
10223 //
10224 // Whereas the form without a matcher list:
10225 //
10226 // // This statement:
10227 // ON_CALL(mock, TwoArgsMethod)...
10228 //
10229 // // ...expands to:
10230 // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
10231 // |-----------------------v--------------------------|
10232 // invokes second overload
10233 //
10234 // // ...which is essentially:
10235 // mock.gmock_TwoArgsMethod(_, _)...
10236 //
10237 // The WithoutMatchers() argument is used to disambiguate overloads and to
10238 // block the caller from accidentally invoking the second overload directly. The
10239 // second argument is an internal type derived from the method signature. The
10240 // failure to disambiguate two overloads of this method in the ON_CALL statement
10241 // is how we block callers from setting expectations on overloaded methods.
10242 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
10243 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
10244 nullptr) \
10245 .Setter(__FILE__, __LINE__, #mock_expr, #call)
10246
10247 #define ON_CALL(obj, call) \
10248 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
10249
10250 #define EXPECT_CALL(obj, call) \
10251 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
10252
10253 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
10254
10255 namespace testing {
10256 namespace internal {
10257 template <typename T>
10258 using identity_t = T;
10259
10260 template <typename Pattern>
10261 struct ThisRefAdjuster {
10262 template <typename T>
10263 using AdjustT = typename std::conditional<
10264 std::is_const<typename std::remove_reference<Pattern>::type>::value,
10265 typename std::conditional<std::is_lvalue_reference<Pattern>::value,
10266 const T&, const T&&>::type,
10267 typename std::conditional<std::is_lvalue_reference<Pattern>::value, T&,
10268 T&&>::type>::type;
10269
10270 template <typename MockType>
10271 static AdjustT<MockType> Adjust(const MockType& mock) {
10272 return static_cast<AdjustT<MockType>>(const_cast<MockType&>(mock));
10273 }
10274 };
10275
10276 } // namespace internal
10277
10278 // The style guide prohibits "using" statements in a namespace scope
10279 // inside a header file. However, the FunctionMocker class template
10280 // is meant to be defined in the ::testing namespace. The following
10281 // line is just a trick for working around a bug in MSVC 8.0, which
10282 // cannot handle it if we define FunctionMocker in ::testing.
10283 using internal::FunctionMocker;
10284 } // namespace testing
10285
10286 #define MOCK_METHOD(...) \
10287 GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__)
10288
10289 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \
10290 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10291
10292 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \
10293 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10294
10295 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \
10296 GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ())
10297
10298 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \
10299 GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \
10300 GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \
10301 GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
10302 GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \
10303 GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
10304 GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
10305 GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \
10306 GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \
10307 GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \
10308 GMOCK_INTERNAL_GET_CALLTYPE(_Spec), GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \
10309 (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)))
10310
10311 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \
10312 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10313
10314 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \
10315 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10316
10317 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \
10318 GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
10319
10320 #define GMOCK_INTERNAL_WRONG_ARITY(...) \
10321 static_assert( \
10322 false, \
10323 "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \
10324 "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \
10325 "enclosed in parentheses. If _Ret is a type with unprotected commas, " \
10326 "it must also be enclosed in parentheses.")
10327
10328 #define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \
10329 static_assert( \
10330 GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \
10331 GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.")
10332
10333 #define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \
10334 static_assert( \
10335 std::is_function<__VA_ARGS__>::value, \
10336 "Signature must be a function type, maybe return type contains " \
10337 "unprotected comma."); \
10338 static_assert( \
10339 ::testing::tuple_size<typename ::testing::internal::Function< \
10340 __VA_ARGS__>::ArgumentTuple>::value == _N, \
10341 "This method does not take " GMOCK_PP_STRINGIZE( \
10342 _N) " arguments. Parenthesize all types with unprotected commas.")
10343
10344 #define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
10345 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec)
10346
10347 #define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \
10348 _Override, _Final, _NoexceptSpec, \
10349 _CallType, _RefSpec, _Signature) \
10350 typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \
10351 _Signature)>::Result \
10352 GMOCK_INTERNAL_EXPAND(_CallType) \
10353 _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \
10354 GMOCK_PP_IF(_Constness, const, ) _RefSpec _NoexceptSpec \
10355 GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \
10356 GMOCK_MOCKER_(_N, _Constness, _MethodName) \
10357 .SetOwnerAndName(this, #_MethodName); \
10358 return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
10359 .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \
10360 } \
10361 ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
10362 GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \
10363 GMOCK_PP_IF(_Constness, const, ) _RefSpec { \
10364 GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \
10365 return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
10366 .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \
10367 } \
10368 ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
10369 const ::testing::internal::WithoutMatchers&, \
10370 GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \
10371 GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \
10372 return ::testing::internal::ThisRefAdjuster<GMOCK_PP_IF( \
10373 _Constness, const, ) int _RefSpec>::Adjust(*this) \
10374 .gmock_##_MethodName(GMOCK_PP_REPEAT( \
10375 GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \
10376 } \
10377 mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \
10378 GMOCK_MOCKER_(_N, _Constness, _MethodName)
10379
10380 #define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__
10381
10382 // Five Valid modifiers.
10383 #define GMOCK_INTERNAL_HAS_CONST(_Tuple) \
10384 GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple))
10385
10386 #define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \
10387 GMOCK_PP_HAS_COMMA( \
10388 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple))
10389
10390 #define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \
10391 GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple))
10392
10393 #define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \
10394 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple)
10395
10396 #define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \
10397 GMOCK_PP_IF( \
10398 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \
10399 _elem, )
10400
10401 #define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \
10402 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple)
10403
10404 #define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \
10405 GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \
10406 GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
10407
10408 #define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \
10409 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple)
10410
10411 #define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \
10412 static_assert( \
10413 (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \
10414 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \
10415 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \
10416 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \
10417 GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \
10418 GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \
10419 GMOCK_PP_STRINGIZE( \
10420 _elem) " cannot be recognized as a valid specification modifier.");
10421
10422 // Modifiers implementation.
10423 #define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \
10424 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem)
10425
10426 #define GMOCK_INTERNAL_DETECT_CONST_I_const ,
10427
10428 #define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \
10429 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem)
10430
10431 #define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override ,
10432
10433 #define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \
10434 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem)
10435
10436 #define GMOCK_INTERNAL_DETECT_FINAL_I_final ,
10437
10438 #define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \
10439 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem)
10440
10441 #define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept ,
10442
10443 #define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \
10444 GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem)
10445
10446 #define GMOCK_INTERNAL_DETECT_REF_I_ref ,
10447
10448 #define GMOCK_INTERNAL_UNPACK_ref(x) x
10449
10450 #define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \
10451 GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \
10452 GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \
10453 (_elem)
10454
10455 // TODO(iserna): GMOCK_INTERNAL_IS_CALLTYPE and
10456 // GMOCK_INTERNAL_GET_VALUE_CALLTYPE needed more expansions to work on windows
10457 // maybe they can be simplified somehow.
10458 #define GMOCK_INTERNAL_IS_CALLTYPE(_arg) \
10459 GMOCK_INTERNAL_IS_CALLTYPE_I( \
10460 GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
10461 #define GMOCK_INTERNAL_IS_CALLTYPE_I(_arg) GMOCK_PP_IS_ENCLOSED_PARENS(_arg)
10462
10463 #define GMOCK_INTERNAL_GET_VALUE_CALLTYPE(_arg) \
10464 GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I( \
10465 GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
10466 #define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \
10467 GMOCK_PP_IDENTITY _arg
10468
10469 #define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype
10470
10471 // Note: The use of `identity_t` here allows _Ret to represent return types that
10472 // would normally need to be specified in a different way. For example, a method
10473 // returning a function pointer must be written as
10474 //
10475 // fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...)
10476 //
10477 // But we only support placing the return type at the beginning. To handle this,
10478 // we wrap all calls in identity_t, so that a declaration will be expanded to
10479 //
10480 // identity_t<fn_ptr_return_t (*)(fn_ptr_args_t...)> method(method_args_t...)
10481 //
10482 // This allows us to work around the syntactic oddities of function/method
10483 // types.
10484 #define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \
10485 ::testing::internal::identity_t<GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), \
10486 GMOCK_PP_REMOVE_PARENS, \
10487 GMOCK_PP_IDENTITY)(_Ret)>( \
10488 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args))
10489
10490 #define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \
10491 GMOCK_PP_COMMA_IF(_i) \
10492 GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \
10493 GMOCK_PP_IDENTITY) \
10494 (_elem)
10495
10496 #define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
10497 GMOCK_PP_COMMA_IF(_i) \
10498 GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
10499 gmock_a##_i
10500
10501 #define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
10502 GMOCK_PP_COMMA_IF(_i) \
10503 ::std::forward<GMOCK_INTERNAL_ARG_O( \
10504 _i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i)
10505
10506 #define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
10507 GMOCK_PP_COMMA_IF(_i) \
10508 GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
10509 gmock_a##_i
10510
10511 #define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \
10512 GMOCK_PP_COMMA_IF(_i) \
10513 gmock_a##_i
10514
10515 #define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
10516 GMOCK_PP_COMMA_IF(_i) \
10517 ::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>()
10518
10519 #define GMOCK_INTERNAL_ARG_O(_i, ...) \
10520 typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type
10521
10522 #define GMOCK_INTERNAL_MATCHER_O(_i, ...) \
10523 const ::testing::Matcher<typename ::testing::internal::Function< \
10524 __VA_ARGS__>::template Arg<_i>::type>&
10525
10526 #define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__)
10527 #define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__)
10528 #define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__)
10529 #define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__)
10530 #define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__)
10531 #define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__)
10532 #define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__)
10533 #define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__)
10534 #define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__)
10535 #define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__)
10536 #define MOCK_METHOD10(m, ...) \
10537 GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__)
10538
10539 #define MOCK_CONST_METHOD0(m, ...) \
10540 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__)
10541 #define MOCK_CONST_METHOD1(m, ...) \
10542 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__)
10543 #define MOCK_CONST_METHOD2(m, ...) \
10544 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__)
10545 #define MOCK_CONST_METHOD3(m, ...) \
10546 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__)
10547 #define MOCK_CONST_METHOD4(m, ...) \
10548 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__)
10549 #define MOCK_CONST_METHOD5(m, ...) \
10550 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__)
10551 #define MOCK_CONST_METHOD6(m, ...) \
10552 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__)
10553 #define MOCK_CONST_METHOD7(m, ...) \
10554 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__)
10555 #define MOCK_CONST_METHOD8(m, ...) \
10556 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__)
10557 #define MOCK_CONST_METHOD9(m, ...) \
10558 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__)
10559 #define MOCK_CONST_METHOD10(m, ...) \
10560 GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__)
10561
10562 #define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__)
10563 #define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__)
10564 #define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__)
10565 #define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__)
10566 #define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__)
10567 #define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__)
10568 #define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__)
10569 #define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__)
10570 #define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__)
10571 #define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__)
10572 #define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__)
10573
10574 #define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__)
10575 #define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__)
10576 #define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__)
10577 #define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__)
10578 #define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__)
10579 #define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__)
10580 #define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__)
10581 #define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__)
10582 #define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__)
10583 #define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__)
10584 #define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__)
10585
10586 #define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
10587 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__)
10588 #define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
10589 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__)
10590 #define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
10591 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__)
10592 #define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
10593 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__)
10594 #define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
10595 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__)
10596 #define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
10597 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__)
10598 #define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
10599 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__)
10600 #define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
10601 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__)
10602 #define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
10603 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__)
10604 #define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
10605 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__)
10606 #define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
10607 GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__)
10608
10609 #define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
10610 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__)
10611 #define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
10612 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__)
10613 #define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
10614 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__)
10615 #define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
10616 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__)
10617 #define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
10618 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__)
10619 #define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
10620 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__)
10621 #define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
10622 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__)
10623 #define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
10624 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__)
10625 #define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
10626 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__)
10627 #define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
10628 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__)
10629 #define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
10630 GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__)
10631
10632 #define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
10633 MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10634 #define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
10635 MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10636 #define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
10637 MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10638 #define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
10639 MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10640 #define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
10641 MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10642 #define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
10643 MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10644 #define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
10645 MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10646 #define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
10647 MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10648 #define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
10649 MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10650 #define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
10651 MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10652 #define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
10653 MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10654
10655 #define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
10656 MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10657 #define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
10658 MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10659 #define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
10660 MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10661 #define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
10662 MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10663 #define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
10664 MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10665 #define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
10666 MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10667 #define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
10668 MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10669 #define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
10670 MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10671 #define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
10672 MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10673 #define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
10674 MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10675 #define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
10676 MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
10677
10678 #define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \
10679 GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
10680 args_num, ::testing::internal::identity_t<__VA_ARGS__>); \
10681 GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
10682 args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \
10683 (::testing::internal::identity_t<__VA_ARGS__>))
10684
10685 #define GMOCK_MOCKER_(arity, constness, Method) \
10686 GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
10687
10688 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_
10689 // Copyright 2007, Google Inc.
10690 // All rights reserved.
10691 //
10692 // Redistribution and use in source and binary forms, with or without
10693 // modification, are permitted provided that the following conditions are
10694 // met:
10695 //
10696 // * Redistributions of source code must retain the above copyright
10697 // notice, this list of conditions and the following disclaimer.
10698 // * Redistributions in binary form must reproduce the above
10699 // copyright notice, this list of conditions and the following disclaimer
10700 // in the documentation and/or other materials provided with the
10701 // distribution.
10702 // * Neither the name of Google Inc. nor the names of its
10703 // contributors may be used to endorse or promote products derived from
10704 // this software without specific prior written permission.
10705 //
10706 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10707 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10708 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10709 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10710 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10711 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10712 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10713 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10714 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10715 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10716 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10717
10718
10719 // Google Mock - a framework for writing C++ mock classes.
10720 //
10721 // This file implements some commonly used variadic actions.
10722
10723 // GOOGLETEST_CM0002 DO NOT DELETE
10724
10725 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
10726 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
10727
10728 #include <memory>
10729 #include <utility>
10730
10731
10732 // Include any custom callback actions added by the local installation.
10733 // GOOGLETEST_CM0002 DO NOT DELETE
10734
10735 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
10736 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
10737
10738 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
10739
10740 // Sometimes you want to give an action explicit template parameters
10741 // that cannot be inferred from its value parameters. ACTION() and
10742 // ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that
10743 // and can be viewed as an extension to ACTION() and ACTION_P*().
10744 //
10745 // The syntax:
10746 //
10747 // ACTION_TEMPLATE(ActionName,
10748 // HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
10749 // AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
10750 //
10751 // defines an action template that takes m explicit template
10752 // parameters and n value parameters. name_i is the name of the i-th
10753 // template parameter, and kind_i specifies whether it's a typename,
10754 // an integral constant, or a template. p_i is the name of the i-th
10755 // value parameter.
10756 //
10757 // Example:
10758 //
10759 // // DuplicateArg<k, T>(output) converts the k-th argument of the mock
10760 // // function to type T and copies it to *output.
10761 // ACTION_TEMPLATE(DuplicateArg,
10762 // HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
10763 // AND_1_VALUE_PARAMS(output)) {
10764 // *output = T(::std::get<k>(args));
10765 // }
10766 // ...
10767 // int n;
10768 // EXPECT_CALL(mock, Foo(_, _))
10769 // .WillOnce(DuplicateArg<1, unsigned char>(&n));
10770 //
10771 // To create an instance of an action template, write:
10772 //
10773 // ActionName<t1, ..., t_m>(v1, ..., v_n)
10774 //
10775 // where the ts are the template arguments and the vs are the value
10776 // arguments. The value argument types are inferred by the compiler.
10777 // If you want to explicitly specify the value argument types, you can
10778 // provide additional template arguments:
10779 //
10780 // ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
10781 //
10782 // where u_i is the desired type of v_i.
10783 //
10784 // ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
10785 // number of value parameters, but not on the number of template
10786 // parameters. Without the restriction, the meaning of the following
10787 // is unclear:
10788 //
10789 // OverloadedAction<int, bool>(x);
10790 //
10791 // Are we using a single-template-parameter action where 'bool' refers
10792 // to the type of x, or are we using a two-template-parameter action
10793 // where the compiler is asked to infer the type of x?
10794 //
10795 // Implementation notes:
10796 //
10797 // GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
10798 // GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
10799 // implementing ACTION_TEMPLATE. The main trick we use is to create
10800 // new macro invocations when expanding a macro. For example, we have
10801 //
10802 // #define ACTION_TEMPLATE(name, template_params, value_params)
10803 // ... GMOCK_INTERNAL_DECL_##template_params ...
10804 //
10805 // which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
10806 // to expand to
10807 //
10808 // ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
10809 //
10810 // Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
10811 // preprocessor will continue to expand it to
10812 //
10813 // ... typename T ...
10814 //
10815 // This technique conforms to the C++ standard and is portable. It
10816 // allows us to implement action templates using O(N) code, where N is
10817 // the maximum number of template/value parameters supported. Without
10818 // using it, we'd have to devote O(N^2) amount of code to implement all
10819 // combinations of m and n.
10820
10821 // Declares the template parameters.
10822 #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
10823 #define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
10824 name1) kind0 name0, kind1 name1
10825 #define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10826 kind2, name2) kind0 name0, kind1 name1, kind2 name2
10827 #define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10828 kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
10829 kind3 name3
10830 #define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10831 kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
10832 kind2 name2, kind3 name3, kind4 name4
10833 #define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10834 kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
10835 kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
10836 #define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10837 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10838 name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
10839 kind5 name5, kind6 name6
10840 #define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10841 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10842 kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
10843 kind4 name4, kind5 name5, kind6 name6, kind7 name7
10844 #define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10845 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10846 kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
10847 kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
10848 kind8 name8
10849 #define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
10850 name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10851 name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
10852 kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
10853 kind6 name6, kind7 name7, kind8 name8, kind9 name9
10854
10855 // Lists the template parameters.
10856 #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
10857 #define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
10858 name1) name0, name1
10859 #define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10860 kind2, name2) name0, name1, name2
10861 #define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10862 kind2, name2, kind3, name3) name0, name1, name2, name3
10863 #define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10864 kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
10865 name4
10866 #define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10867 kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
10868 name2, name3, name4, name5
10869 #define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10870 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10871 name6) name0, name1, name2, name3, name4, name5, name6
10872 #define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10873 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10874 kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
10875 #define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
10876 kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
10877 kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
10878 name6, name7, name8
10879 #define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
10880 name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
10881 name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
10882 name3, name4, name5, name6, name7, name8, name9
10883
10884 // Declares the types of value parameters.
10885 #define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
10886 #define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
10887 #define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \
10888 typename p0##_type, typename p1##_type
10889 #define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \
10890 typename p0##_type, typename p1##_type, typename p2##_type
10891 #define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
10892 typename p0##_type, typename p1##_type, typename p2##_type, \
10893 typename p3##_type
10894 #define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
10895 typename p0##_type, typename p1##_type, typename p2##_type, \
10896 typename p3##_type, typename p4##_type
10897 #define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
10898 typename p0##_type, typename p1##_type, typename p2##_type, \
10899 typename p3##_type, typename p4##_type, typename p5##_type
10900 #define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10901 p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
10902 typename p3##_type, typename p4##_type, typename p5##_type, \
10903 typename p6##_type
10904 #define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10905 p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
10906 typename p3##_type, typename p4##_type, typename p5##_type, \
10907 typename p6##_type, typename p7##_type
10908 #define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10909 p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
10910 typename p3##_type, typename p4##_type, typename p5##_type, \
10911 typename p6##_type, typename p7##_type, typename p8##_type
10912 #define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
10913 p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
10914 typename p2##_type, typename p3##_type, typename p4##_type, \
10915 typename p5##_type, typename p6##_type, typename p7##_type, \
10916 typename p8##_type, typename p9##_type
10917
10918 // Initializes the value parameters.
10919 #define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
10920 ()
10921 #define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
10922 (p0##_type gmock_p0) : p0(::std::move(gmock_p0))
10923 #define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
10924 (p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
10925 p1(::std::move(gmock_p1))
10926 #define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
10927 (p0##_type gmock_p0, p1##_type gmock_p1, \
10928 p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \
10929 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2))
10930 #define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
10931 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10932 p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \
10933 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10934 p3(::std::move(gmock_p3))
10935 #define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
10936 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10937 p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \
10938 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10939 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4))
10940 #define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
10941 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10942 p3##_type gmock_p3, p4##_type gmock_p4, \
10943 p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \
10944 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10945 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10946 p5(::std::move(gmock_p5))
10947 #define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
10948 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10949 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10950 p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \
10951 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10952 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10953 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6))
10954 #define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
10955 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10956 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10957 p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \
10958 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10959 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10960 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
10961 p7(::std::move(gmock_p7))
10962 #define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
10963 p7, p8)\
10964 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10965 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10966 p6##_type gmock_p6, p7##_type gmock_p7, \
10967 p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \
10968 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10969 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10970 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
10971 p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8))
10972 #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
10973 p7, p8, p9)\
10974 (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
10975 p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
10976 p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
10977 p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \
10978 p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
10979 p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
10980 p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
10981 p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \
10982 p9(::std::move(gmock_p9))
10983
10984 // Defines the copy constructor
10985 #define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \
10986 {} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134
10987 #define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default;
10988 #define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default;
10989 #define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default;
10990 #define GMOCK_INTERNAL_DEFN_COPY_AND_4_VALUE_PARAMS(...) = default;
10991 #define GMOCK_INTERNAL_DEFN_COPY_AND_5_VALUE_PARAMS(...) = default;
10992 #define GMOCK_INTERNAL_DEFN_COPY_AND_6_VALUE_PARAMS(...) = default;
10993 #define GMOCK_INTERNAL_DEFN_COPY_AND_7_VALUE_PARAMS(...) = default;
10994 #define GMOCK_INTERNAL_DEFN_COPY_AND_8_VALUE_PARAMS(...) = default;
10995 #define GMOCK_INTERNAL_DEFN_COPY_AND_9_VALUE_PARAMS(...) = default;
10996 #define GMOCK_INTERNAL_DEFN_COPY_AND_10_VALUE_PARAMS(...) = default;
10997
10998 // Declares the fields for storing the value parameters.
10999 #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
11000 #define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
11001 #define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
11002 p1##_type p1;
11003 #define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
11004 p1##_type p1; p2##_type p2;
11005 #define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
11006 p1##_type p1; p2##_type p2; p3##_type p3;
11007 #define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
11008 p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
11009 #define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
11010 p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
11011 p5##_type p5;
11012 #define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11013 p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
11014 p5##_type p5; p6##_type p6;
11015 #define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11016 p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
11017 p5##_type p5; p6##_type p6; p7##_type p7;
11018 #define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11019 p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
11020 p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
11021 #define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11022 p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
11023 p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
11024 p9##_type p9;
11025
11026 // Lists the value parameters.
11027 #define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
11028 #define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0
11029 #define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
11030 #define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
11031 #define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
11032 #define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
11033 p2, p3, p4
11034 #define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
11035 p1, p2, p3, p4, p5
11036 #define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11037 p6) p0, p1, p2, p3, p4, p5, p6
11038 #define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11039 p7) p0, p1, p2, p3, p4, p5, p6, p7
11040 #define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11041 p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
11042 #define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11043 p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
11044
11045 // Lists the value parameter types.
11046 #define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
11047 #define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
11048 #define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
11049 p1##_type
11050 #define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
11051 p1##_type, p2##_type
11052 #define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
11053 p0##_type, p1##_type, p2##_type, p3##_type
11054 #define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
11055 p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
11056 #define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
11057 p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
11058 #define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11059 p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
11060 p6##_type
11061 #define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11062 p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
11063 p5##_type, p6##_type, p7##_type
11064 #define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11065 p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
11066 p5##_type, p6##_type, p7##_type, p8##_type
11067 #define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11068 p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
11069 p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
11070
11071 // Declares the value parameters.
11072 #define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
11073 #define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
11074 #define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
11075 p1##_type p1
11076 #define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
11077 p1##_type p1, p2##_type p2
11078 #define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
11079 p1##_type p1, p2##_type p2, p3##_type p3
11080 #define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
11081 p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
11082 #define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
11083 p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
11084 p5##_type p5
11085 #define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
11086 p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
11087 p5##_type p5, p6##_type p6
11088 #define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11089 p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
11090 p5##_type p5, p6##_type p6, p7##_type p7
11091 #define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11092 p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
11093 p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
11094 #define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11095 p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
11096 p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
11097 p9##_type p9
11098
11099 // The suffix of the class template implementing the action template.
11100 #define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
11101 #define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P
11102 #define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2
11103 #define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3
11104 #define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4
11105 #define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5
11106 #define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
11107 #define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
11108 #define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11109 p7) P8
11110 #define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11111 p7, p8) P9
11112 #define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
11113 p7, p8, p9) P10
11114
11115 // The name of the class template implementing the action template.
11116 #define GMOCK_ACTION_CLASS_(name, value_params)\
11117 GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
11118
11119 #define ACTION_TEMPLATE(name, template_params, value_params) \
11120 template <GMOCK_INTERNAL_DECL_##template_params \
11121 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11122 class GMOCK_ACTION_CLASS_(name, value_params) { \
11123 public: \
11124 explicit GMOCK_ACTION_CLASS_(name, value_params)( \
11125 GMOCK_INTERNAL_DECL_##value_params) \
11126 GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
11127 = default; , \
11128 : impl_(std::make_shared<gmock_Impl>( \
11129 GMOCK_INTERNAL_LIST_##value_params)) { }) \
11130 GMOCK_ACTION_CLASS_(name, value_params)( \
11131 const GMOCK_ACTION_CLASS_(name, value_params)&) noexcept \
11132 GMOCK_INTERNAL_DEFN_COPY_##value_params \
11133 GMOCK_ACTION_CLASS_(name, value_params)( \
11134 GMOCK_ACTION_CLASS_(name, value_params)&&) noexcept \
11135 GMOCK_INTERNAL_DEFN_COPY_##value_params \
11136 template <typename F> \
11137 operator ::testing::Action<F>() const { \
11138 return GMOCK_PP_IF( \
11139 GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
11140 (::testing::internal::MakeAction<F, gmock_Impl>()), \
11141 (::testing::internal::MakeAction<F>(impl_))); \
11142 } \
11143 private: \
11144 class gmock_Impl { \
11145 public: \
11146 explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {} \
11147 template <typename function_type, typename return_type, \
11148 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
11149 return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
11150 GMOCK_INTERNAL_DEFN_##value_params \
11151 }; \
11152 GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
11153 , std::shared_ptr<const gmock_Impl> impl_;) \
11154 }; \
11155 template <GMOCK_INTERNAL_DECL_##template_params \
11156 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11157 GMOCK_ACTION_CLASS_(name, value_params)< \
11158 GMOCK_INTERNAL_LIST_##template_params \
11159 GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
11160 GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
11161 template <GMOCK_INTERNAL_DECL_##template_params \
11162 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11163 inline GMOCK_ACTION_CLASS_(name, value_params)< \
11164 GMOCK_INTERNAL_LIST_##template_params \
11165 GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
11166 GMOCK_INTERNAL_DECL_##value_params) { \
11167 return GMOCK_ACTION_CLASS_(name, value_params)< \
11168 GMOCK_INTERNAL_LIST_##template_params \
11169 GMOCK_INTERNAL_LIST_TYPE_##value_params>( \
11170 GMOCK_INTERNAL_LIST_##value_params); \
11171 } \
11172 template <GMOCK_INTERNAL_DECL_##template_params \
11173 GMOCK_INTERNAL_DECL_TYPE_##value_params> \
11174 template <typename function_type, typename return_type, typename args_type, \
11175 GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
11176 return_type GMOCK_ACTION_CLASS_(name, value_params)< \
11177 GMOCK_INTERNAL_LIST_##template_params \
11178 GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \
11179 GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
11180
11181 namespace testing {
11182
11183 // The ACTION*() macros trigger warning C4100 (unreferenced formal
11184 // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
11185 // the macro definition, as the warnings are generated when the macro
11186 // is expanded and macro expansion cannot contain #pragma. Therefore
11187 // we suppress them here.
11188 #ifdef _MSC_VER
11189 # pragma warning(push)
11190 # pragma warning(disable:4100)
11191 #endif
11192
11193 namespace internal {
11194
11195 // internal::InvokeArgument - a helper for InvokeArgument action.
11196 // The basic overloads are provided here for generic functors.
11197 // Overloads for other custom-callables are provided in the
11198 // internal/custom/gmock-generated-actions.h header.
11199 template <typename F, typename... Args>
11200 auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) {
11201 return f(args...);
11202 }
11203
11204 template <std::size_t index, typename... Params>
11205 struct InvokeArgumentAction {
11206 template <typename... Args>
11207 auto operator()(Args&&... args) const -> decltype(internal::InvokeArgument(
11208 std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
11209 std::declval<const Params&>()...)) {
11210 internal::FlatTuple<Args&&...> args_tuple(FlatTupleConstructTag{},
11211 std::forward<Args>(args)...);
11212 return params.Apply([&](const Params&... unpacked_params) {
11213 auto&& callable = args_tuple.template Get<index>();
11214 return internal::InvokeArgument(
11215 std::forward<decltype(callable)>(callable), unpacked_params...);
11216 });
11217 }
11218
11219 internal::FlatTuple<Params...> params;
11220 };
11221
11222 } // namespace internal
11223
11224 // The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
11225 // (0-based) argument, which must be a k-ary callable, of the mock
11226 // function, with arguments a1, a2, ..., a_k.
11227 //
11228 // Notes:
11229 //
11230 // 1. The arguments are passed by value by default. If you need to
11231 // pass an argument by reference, wrap it inside std::ref(). For
11232 // example,
11233 //
11234 // InvokeArgument<1>(5, string("Hello"), std::ref(foo))
11235 //
11236 // passes 5 and string("Hello") by value, and passes foo by
11237 // reference.
11238 //
11239 // 2. If the callable takes an argument by reference but std::ref() is
11240 // not used, it will receive the reference to a copy of the value,
11241 // instead of the original value. For example, when the 0-th
11242 // argument of the mock function takes a const string&, the action
11243 //
11244 // InvokeArgument<0>(string("Hello"))
11245 //
11246 // makes a copy of the temporary string("Hello") object and passes a
11247 // reference of the copy, instead of the original temporary object,
11248 // to the callable. This makes it easy for a user to define an
11249 // InvokeArgument action from temporary values and have it performed
11250 // later.
11251 template <std::size_t index, typename... Params>
11252 internal::InvokeArgumentAction<index, typename std::decay<Params>::type...>
11253 InvokeArgument(Params&&... params) {
11254 return {internal::FlatTuple<typename std::decay<Params>::type...>(
11255 internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)};
11256 }
11257
11258 #ifdef _MSC_VER
11259 # pragma warning(pop)
11260 #endif
11261
11262 } // namespace testing
11263
11264 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
11265 // Copyright 2013, Google Inc.
11266 // All rights reserved.
11267 //
11268 // Redistribution and use in source and binary forms, with or without
11269 // modification, are permitted provided that the following conditions are
11270 // met:
11271 //
11272 // * Redistributions of source code must retain the above copyright
11273 // notice, this list of conditions and the following disclaimer.
11274 // * Redistributions in binary form must reproduce the above
11275 // copyright notice, this list of conditions and the following disclaimer
11276 // in the documentation and/or other materials provided with the
11277 // distribution.
11278 // * Neither the name of Google Inc. nor the names of its
11279 // contributors may be used to endorse or promote products derived from
11280 // this software without specific prior written permission.
11281 //
11282 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11283 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11284 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11285 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11286 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11287 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11288 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11289 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11290 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11291 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11292 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11293
11294
11295 // Google Mock - a framework for writing C++ mock classes.
11296 //
11297 // This file implements some matchers that depend on gmock-matchers.h.
11298 //
11299 // Note that tests are implemented in gmock-matchers_test.cc rather than
11300 // gmock-more-matchers-test.cc.
11301
11302 // GOOGLETEST_CM0002 DO NOT DELETE
11303
11304 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
11305 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
11306
11307
11308 namespace testing {
11309
11310 // Silence C4100 (unreferenced formal
11311 // parameter) for MSVC
11312 #ifdef _MSC_VER
11313 # pragma warning(push)
11314 # pragma warning(disable:4100)
11315 #if (_MSC_VER == 1900)
11316 // and silence C4800 (C4800: 'int *const ': forcing value
11317 // to bool 'true' or 'false') for MSVC 14
11318 # pragma warning(disable:4800)
11319 #endif
11320 #endif
11321
11322 // Defines a matcher that matches an empty container. The container must
11323 // support both size() and empty(), which all STL-like containers provide.
11324 MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") {
11325 if (arg.empty()) {
11326 return true;
11327 }
11328 *result_listener << "whose size is " << arg.size();
11329 return false;
11330 }
11331
11332 // Define a matcher that matches a value that evaluates in boolean
11333 // context to true. Useful for types that define "explicit operator
11334 // bool" operators and so can't be compared for equality with true
11335 // and false.
11336 MATCHER(IsTrue, negation ? "is false" : "is true") {
11337 return static_cast<bool>(arg);
11338 }
11339
11340 // Define a matcher that matches a value that evaluates in boolean
11341 // context to false. Useful for types that define "explicit operator
11342 // bool" operators and so can't be compared for equality with true
11343 // and false.
11344 MATCHER(IsFalse, negation ? "is true" : "is false") {
11345 return !static_cast<bool>(arg);
11346 }
11347
11348 #ifdef _MSC_VER
11349 # pragma warning(pop)
11350 #endif
11351
11352
11353 } // namespace testing
11354
11355 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
11356 // Copyright 2008, Google Inc.
11357 // All rights reserved.
11358 //
11359 // Redistribution and use in source and binary forms, with or without
11360 // modification, are permitted provided that the following conditions are
11361 // met:
11362 //
11363 // * Redistributions of source code must retain the above copyright
11364 // notice, this list of conditions and the following disclaimer.
11365 // * Redistributions in binary form must reproduce the above
11366 // copyright notice, this list of conditions and the following disclaimer
11367 // in the documentation and/or other materials provided with the
11368 // distribution.
11369 // * Neither the name of Google Inc. nor the names of its
11370 // contributors may be used to endorse or promote products derived from
11371 // this software without specific prior written permission.
11372 //
11373 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11374 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11375 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11376 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11377 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11378 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11379 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11380 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11381 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11382 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11383 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11384
11385
11386 // Implements class templates NiceMock, NaggyMock, and StrictMock.
11387 //
11388 // Given a mock class MockFoo that is created using Google Mock,
11389 // NiceMock<MockFoo> is a subclass of MockFoo that allows
11390 // uninteresting calls (i.e. calls to mock methods that have no
11391 // EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo
11392 // that prints a warning when an uninteresting call occurs, and
11393 // StrictMock<MockFoo> is a subclass of MockFoo that treats all
11394 // uninteresting calls as errors.
11395 //
11396 // Currently a mock is naggy by default, so MockFoo and
11397 // NaggyMock<MockFoo> behave like the same. However, we will soon
11398 // switch the default behavior of mocks to be nice, as that in general
11399 // leads to more maintainable tests. When that happens, MockFoo will
11400 // stop behaving like NaggyMock<MockFoo> and start behaving like
11401 // NiceMock<MockFoo>.
11402 //
11403 // NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
11404 // their respective base class. Therefore you can write
11405 // NiceMock<MockFoo>(5, "a") to construct a nice mock where MockFoo
11406 // has a constructor that accepts (int, const char*), for example.
11407 //
11408 // A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,
11409 // and StrictMock<MockFoo> only works for mock methods defined using
11410 // the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class.
11411 // If a mock method is defined in a base class of MockFoo, the "nice"
11412 // or "strict" modifier may not affect it, depending on the compiler.
11413 // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
11414 // supported.
11415
11416 // GOOGLETEST_CM0002 DO NOT DELETE
11417
11418 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
11419 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
11420
11421 #include <cstdint>
11422 #include <type_traits>
11423
11424
11425 namespace testing {
11426 template <class MockClass>
11427 class NiceMock;
11428 template <class MockClass>
11429 class NaggyMock;
11430 template <class MockClass>
11431 class StrictMock;
11432
11433 namespace internal {
11434 template <typename T>
11435 std::true_type StrictnessModifierProbe(const NiceMock<T>&);
11436 template <typename T>
11437 std::true_type StrictnessModifierProbe(const NaggyMock<T>&);
11438 template <typename T>
11439 std::true_type StrictnessModifierProbe(const StrictMock<T>&);
11440 std::false_type StrictnessModifierProbe(...);
11441
11442 template <typename T>
11443 constexpr bool HasStrictnessModifier() {
11444 return decltype(StrictnessModifierProbe(std::declval<const T&>()))::value;
11445 }
11446
11447 // Base classes that register and deregister with testing::Mock to alter the
11448 // default behavior around uninteresting calls. Inheriting from one of these
11449 // classes first and then MockClass ensures the MockClass constructor is run
11450 // after registration, and that the MockClass destructor runs before
11451 // deregistration. This guarantees that MockClass's constructor and destructor
11452 // run with the same level of strictness as its instance methods.
11453
11454 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \
11455 (defined(_MSC_VER) || defined(__clang__))
11456 // We need to mark these classes with this declspec to ensure that
11457 // the empty base class optimization is performed.
11458 #define GTEST_INTERNAL_EMPTY_BASE_CLASS __declspec(empty_bases)
11459 #else
11460 #define GTEST_INTERNAL_EMPTY_BASE_CLASS
11461 #endif
11462
11463 template <typename Base>
11464 class NiceMockImpl {
11465 public:
11466 NiceMockImpl() {
11467 ::testing::Mock::AllowUninterestingCalls(reinterpret_cast<uintptr_t>(this));
11468 }
11469
11470 ~NiceMockImpl() {
11471 ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
11472 }
11473 };
11474
11475 template <typename Base>
11476 class NaggyMockImpl {
11477 public:
11478 NaggyMockImpl() {
11479 ::testing::Mock::WarnUninterestingCalls(reinterpret_cast<uintptr_t>(this));
11480 }
11481
11482 ~NaggyMockImpl() {
11483 ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
11484 }
11485 };
11486
11487 template <typename Base>
11488 class StrictMockImpl {
11489 public:
11490 StrictMockImpl() {
11491 ::testing::Mock::FailUninterestingCalls(reinterpret_cast<uintptr_t>(this));
11492 }
11493
11494 ~StrictMockImpl() {
11495 ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
11496 }
11497 };
11498
11499 } // namespace internal
11500
11501 template <class MockClass>
11502 class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
11503 : private internal::NiceMockImpl<MockClass>,
11504 public MockClass {
11505 public:
11506 static_assert(!internal::HasStrictnessModifier<MockClass>(),
11507 "Can't apply NiceMock to a class hierarchy that already has a "
11508 "strictness modifier. See "
11509 "https://google.github.io/googletest/"
11510 "gmock_cook_book.html#NiceStrictNaggy");
11511 NiceMock() : MockClass() {
11512 static_assert(sizeof(*this) == sizeof(MockClass),
11513 "The impl subclass shouldn't introduce any padding");
11514 }
11515
11516 // Ideally, we would inherit base class's constructors through a using
11517 // declaration, which would preserve their visibility. However, many existing
11518 // tests rely on the fact that current implementation reexports protected
11519 // constructors as public. These tests would need to be cleaned up first.
11520
11521 // Single argument constructor is special-cased so that it can be
11522 // made explicit.
11523 template <typename A>
11524 explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) {
11525 static_assert(sizeof(*this) == sizeof(MockClass),
11526 "The impl subclass shouldn't introduce any padding");
11527 }
11528
11529 template <typename TArg1, typename TArg2, typename... An>
11530 NiceMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
11531 : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
11532 std::forward<An>(args)...) {
11533 static_assert(sizeof(*this) == sizeof(MockClass),
11534 "The impl subclass shouldn't introduce any padding");
11535 }
11536
11537 private:
11538 GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
11539 };
11540
11541 template <class MockClass>
11542 class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
11543 : private internal::NaggyMockImpl<MockClass>,
11544 public MockClass {
11545 static_assert(!internal::HasStrictnessModifier<MockClass>(),
11546 "Can't apply NaggyMock to a class hierarchy that already has a "
11547 "strictness modifier. See "
11548 "https://google.github.io/googletest/"
11549 "gmock_cook_book.html#NiceStrictNaggy");
11550
11551 public:
11552 NaggyMock() : MockClass() {
11553 static_assert(sizeof(*this) == sizeof(MockClass),
11554 "The impl subclass shouldn't introduce any padding");
11555 }
11556
11557 // Ideally, we would inherit base class's constructors through a using
11558 // declaration, which would preserve their visibility. However, many existing
11559 // tests rely on the fact that current implementation reexports protected
11560 // constructors as public. These tests would need to be cleaned up first.
11561
11562 // Single argument constructor is special-cased so that it can be
11563 // made explicit.
11564 template <typename A>
11565 explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) {
11566 static_assert(sizeof(*this) == sizeof(MockClass),
11567 "The impl subclass shouldn't introduce any padding");
11568 }
11569
11570 template <typename TArg1, typename TArg2, typename... An>
11571 NaggyMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
11572 : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
11573 std::forward<An>(args)...) {
11574 static_assert(sizeof(*this) == sizeof(MockClass),
11575 "The impl subclass shouldn't introduce any padding");
11576 }
11577
11578 private:
11579 GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock);
11580 };
11581
11582 template <class MockClass>
11583 class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
11584 : private internal::StrictMockImpl<MockClass>,
11585 public MockClass {
11586 public:
11587 static_assert(
11588 !internal::HasStrictnessModifier<MockClass>(),
11589 "Can't apply StrictMock to a class hierarchy that already has a "
11590 "strictness modifier. See "
11591 "https://google.github.io/googletest/"
11592 "gmock_cook_book.html#NiceStrictNaggy");
11593 StrictMock() : MockClass() {
11594 static_assert(sizeof(*this) == sizeof(MockClass),
11595 "The impl subclass shouldn't introduce any padding");
11596 }
11597
11598 // Ideally, we would inherit base class's constructors through a using
11599 // declaration, which would preserve their visibility. However, many existing
11600 // tests rely on the fact that current implementation reexports protected
11601 // constructors as public. These tests would need to be cleaned up first.
11602
11603 // Single argument constructor is special-cased so that it can be
11604 // made explicit.
11605 template <typename A>
11606 explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) {
11607 static_assert(sizeof(*this) == sizeof(MockClass),
11608 "The impl subclass shouldn't introduce any padding");
11609 }
11610
11611 template <typename TArg1, typename TArg2, typename... An>
11612 StrictMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
11613 : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
11614 std::forward<An>(args)...) {
11615 static_assert(sizeof(*this) == sizeof(MockClass),
11616 "The impl subclass shouldn't introduce any padding");
11617 }
11618
11619 private:
11620 GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
11621 };
11622
11623 #undef GTEST_INTERNAL_EMPTY_BASE_CLASS
11624
11625 } // namespace testing
11626
11627 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
11628
11629 namespace testing {
11630
11631 // Declares Google Mock flags that we want a user to use programmatically.
11632 GMOCK_DECLARE_bool_(catch_leaked_mocks);
11633 GMOCK_DECLARE_string_(verbose);
11634 GMOCK_DECLARE_int32_(default_mock_behavior);
11635
11636 // Initializes Google Mock. This must be called before running the
11637 // tests. In particular, it parses the command line for the flags
11638 // that Google Mock recognizes. Whenever a Google Mock flag is seen,
11639 // it is removed from argv, and *argc is decremented.
11640 //
11641 // No value is returned. Instead, the Google Mock flag variables are
11642 // updated.
11643 //
11644 // Since Google Test is needed for Google Mock to work, this function
11645 // also initializes Google Test and parses its flags, if that hasn't
11646 // been done.
11647 GTEST_API_ void InitGoogleMock(int* argc, char** argv);
11648
11649 // This overloaded version can be used in Windows programs compiled in
11650 // UNICODE mode.
11651 GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv);
11652
11653 // This overloaded version can be used on Arduino/embedded platforms where
11654 // there is no argc/argv.
11655 GTEST_API_ void InitGoogleMock();
11656
11657 } // namespace testing
11658
11659 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
11660