1// Copyright 2007, Google Inc. 2// All rights reserved. 3// 4// Redistribution and use in source and binary forms, with or without 5// modification, are permitted provided that the following conditions are 6// met: 7// 8// * Redistributions of source code must retain the above copyright 9// notice, this list of conditions and the following disclaimer. 10// * Redistributions in binary form must reproduce the above 11// copyright notice, this list of conditions and the following disclaimer 12// in the documentation and/or other materials provided with the 13// distribution. 14// * Neither the name of Google Inc. nor the names of its 15// contributors may be used to endorse or promote products derived from 16// this software without specific prior written permission. 17// 18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 30// Google Mock - a framework for writing C++ mock classes. 31// 32// This file tests the built-in actions. 33 34#include "gmock/gmock-actions.h" 35 36#include <algorithm> 37#include <functional> 38#include <iterator> 39#include <memory> 40#include <sstream> 41#include <string> 42#include <tuple> 43#include <type_traits> 44#include <utility> 45#include <vector> 46 47#include "gmock/gmock.h" 48#include "gmock/internal/gmock-port.h" 49#include "gtest/gtest-spi.h" 50#include "gtest/gtest.h" 51#include "gtest/internal/gtest-port.h" 52 53// Silence C4100 (unreferenced formal parameter) and C4503 (decorated name 54// length exceeded) for MSVC. 55GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503) 56#if defined(_MSC_VER) && (_MSC_VER == 1900) 57// and silence C4800 (C4800: 'int *const ': forcing value 58// to bool 'true' or 'false') for MSVC 15 59GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800) 60#endif 61 62namespace testing { 63namespace { 64 65using ::testing::internal::BuiltInDefaultValue; 66 67TEST(TypeTraits, Negation) { 68 // Direct use with std types. 69 static_assert(std::is_base_of<std::false_type, 70 internal::negation<std::true_type>>::value, 71 ""); 72 73 static_assert(std::is_base_of<std::true_type, 74 internal::negation<std::false_type>>::value, 75 ""); 76 77 // With other types that fit the requirement of a value member that is 78 // convertible to bool. 79 static_assert(std::is_base_of< 80 std::true_type, 81 internal::negation<std::integral_constant<int, 0>>>::value, 82 ""); 83 84 static_assert(std::is_base_of< 85 std::false_type, 86 internal::negation<std::integral_constant<int, 1>>>::value, 87 ""); 88 89 static_assert(std::is_base_of< 90 std::false_type, 91 internal::negation<std::integral_constant<int, -1>>>::value, 92 ""); 93} 94 95// Weird false/true types that aren't actually bool constants (but should still 96// be legal according to [meta.logical] because `bool(T::value)` is valid), are 97// distinct from std::false_type and std::true_type, and are distinct from other 98// instantiations of the same template. 99// 100// These let us check finicky details mandated by the standard like 101// "std::conjunction should evaluate to a type that inherits from the first 102// false-y input". 103template <int> 104struct MyFalse : std::integral_constant<int, 0> {}; 105 106template <int> 107struct MyTrue : std::integral_constant<int, -1> {}; 108 109TEST(TypeTraits, Conjunction) { 110 // Base case: always true. 111 static_assert(std::is_base_of<std::true_type, internal::conjunction<>>::value, 112 ""); 113 114 // One predicate: inherits from that predicate, regardless of value. 115 static_assert( 116 std::is_base_of<MyFalse<0>, internal::conjunction<MyFalse<0>>>::value, 117 ""); 118 119 static_assert( 120 std::is_base_of<MyTrue<0>, internal::conjunction<MyTrue<0>>>::value, ""); 121 122 // Multiple predicates, with at least one false: inherits from that one. 123 static_assert( 124 std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>, 125 MyTrue<2>>>::value, 126 ""); 127 128 static_assert( 129 std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>, 130 MyFalse<2>>>::value, 131 ""); 132 133 // Short circuiting: in the case above, additional predicates need not even 134 // define a value member. 135 struct Empty {}; 136 static_assert( 137 std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>, 138 Empty>>::value, 139 ""); 140 141 // All predicates true: inherits from the last. 142 static_assert( 143 std::is_base_of<MyTrue<2>, internal::conjunction<MyTrue<0>, MyTrue<1>, 144 MyTrue<2>>>::value, 145 ""); 146} 147 148TEST(TypeTraits, Disjunction) { 149 // Base case: always false. 150 static_assert( 151 std::is_base_of<std::false_type, internal::disjunction<>>::value, ""); 152 153 // One predicate: inherits from that predicate, regardless of value. 154 static_assert( 155 std::is_base_of<MyFalse<0>, internal::disjunction<MyFalse<0>>>::value, 156 ""); 157 158 static_assert( 159 std::is_base_of<MyTrue<0>, internal::disjunction<MyTrue<0>>>::value, ""); 160 161 // Multiple predicates, with at least one true: inherits from that one. 162 static_assert( 163 std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>, 164 MyFalse<2>>>::value, 165 ""); 166 167 static_assert( 168 std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>, 169 MyTrue<2>>>::value, 170 ""); 171 172 // Short circuiting: in the case above, additional predicates need not even 173 // define a value member. 174 struct Empty {}; 175 static_assert( 176 std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>, 177 Empty>>::value, 178 ""); 179 180 // All predicates false: inherits from the last. 181 static_assert( 182 std::is_base_of<MyFalse<2>, internal::disjunction<MyFalse<0>, MyFalse<1>, 183 MyFalse<2>>>::value, 184 ""); 185} 186 187TEST(TypeTraits, IsInvocableRV) { 188 struct C { 189 int operator()() const { return 0; } 190 void operator()(int) & {} 191 std::string operator()(int) && { return ""; }; 192 }; 193 194 // The first overload is callable for const and non-const rvalues and lvalues. 195 // It can be used to obtain an int, cv void, or anything int is convertible 196 // to. 197 static_assert(internal::is_callable_r<int, C>::value, ""); 198 static_assert(internal::is_callable_r<int, C&>::value, ""); 199 static_assert(internal::is_callable_r<int, const C>::value, ""); 200 static_assert(internal::is_callable_r<int, const C&>::value, ""); 201 202 static_assert(internal::is_callable_r<void, C>::value, ""); 203 static_assert(internal::is_callable_r<const volatile void, C>::value, ""); 204 static_assert(internal::is_callable_r<char, C>::value, ""); 205 206 // It's possible to provide an int. If it's given to an lvalue, the result is 207 // void. Otherwise it is std::string (which is also treated as allowed for a 208 // void result type). 209 static_assert(internal::is_callable_r<void, C&, int>::value, ""); 210 static_assert(!internal::is_callable_r<int, C&, int>::value, ""); 211 static_assert(!internal::is_callable_r<std::string, C&, int>::value, ""); 212 static_assert(!internal::is_callable_r<void, const C&, int>::value, ""); 213 214 static_assert(internal::is_callable_r<std::string, C, int>::value, ""); 215 static_assert(internal::is_callable_r<void, C, int>::value, ""); 216 static_assert(!internal::is_callable_r<int, C, int>::value, ""); 217 218 // It's not possible to provide other arguments. 219 static_assert(!internal::is_callable_r<void, C, std::string>::value, ""); 220 static_assert(!internal::is_callable_r<void, C, int, int>::value, ""); 221 222 // In C++17 and above, where it's guaranteed that functions can return 223 // non-moveable objects, everything should work fine for non-moveable rsult 224 // types too. 225#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ 226 GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L 227 { 228 struct NonMoveable { 229 NonMoveable() = default; 230 NonMoveable(NonMoveable&&) = delete; 231 }; 232 233 static_assert(!std::is_move_constructible_v<NonMoveable>); 234 235 struct Callable { 236 NonMoveable operator()() { return NonMoveable(); } 237 }; 238 239 static_assert(internal::is_callable_r<NonMoveable, Callable>::value); 240 static_assert(internal::is_callable_r<void, Callable>::value); 241 static_assert( 242 internal::is_callable_r<const volatile void, Callable>::value); 243 244 static_assert(!internal::is_callable_r<int, Callable>::value); 245 static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value); 246 } 247#endif // C++17 and above 248 249 // Nothing should choke when we try to call other arguments besides directly 250 // callable objects, but they should not show up as callable. 251 static_assert(!internal::is_callable_r<void, int>::value, ""); 252 static_assert(!internal::is_callable_r<void, void (C::*)()>::value, ""); 253 static_assert(!internal::is_callable_r<void, void (C::*)(), C*>::value, ""); 254} 255 256// Tests that BuiltInDefaultValue<T*>::Get() returns NULL. 257TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { 258 EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr); 259 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr); 260 EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr); 261} 262 263// Tests that BuiltInDefaultValue<T*>::Exists() return true. 264TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) { 265 EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists()); 266 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists()); 267 EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists()); 268} 269 270// Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a 271// built-in numeric type. 272TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) { 273 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get()); 274 EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get()); 275 EXPECT_EQ(0, BuiltInDefaultValue<char>::Get()); 276#if GMOCK_WCHAR_T_IS_NATIVE_ 277#if !defined(__WCHAR_UNSIGNED__) 278 EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get()); 279#else 280 EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get()); 281#endif 282#endif 283 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT 284 EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT 285 EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT 286 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get()); 287 EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get()); 288 EXPECT_EQ(0, BuiltInDefaultValue<int>::Get()); 289 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT 290 EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT 291 EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT 292 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get()); // NOLINT 293 EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get()); // NOLINT 294 EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get()); // NOLINT 295 EXPECT_EQ(0, BuiltInDefaultValue<float>::Get()); 296 EXPECT_EQ(0, BuiltInDefaultValue<double>::Get()); 297} 298 299// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a 300// built-in numeric type. 301TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) { 302 EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists()); 303 EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists()); 304 EXPECT_TRUE(BuiltInDefaultValue<char>::Exists()); 305#if GMOCK_WCHAR_T_IS_NATIVE_ 306 EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists()); 307#endif 308 EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT 309 EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT 310 EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT 311 EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists()); 312 EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists()); 313 EXPECT_TRUE(BuiltInDefaultValue<int>::Exists()); 314 EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT 315 EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT 316 EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT 317 EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists()); // NOLINT 318 EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists()); // NOLINT 319 EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists()); // NOLINT 320 EXPECT_TRUE(BuiltInDefaultValue<float>::Exists()); 321 EXPECT_TRUE(BuiltInDefaultValue<double>::Exists()); 322} 323 324// Tests that BuiltInDefaultValue<bool>::Get() returns false. 325TEST(BuiltInDefaultValueTest, IsFalseForBool) { 326 EXPECT_FALSE(BuiltInDefaultValue<bool>::Get()); 327} 328 329// Tests that BuiltInDefaultValue<bool>::Exists() returns true. 330TEST(BuiltInDefaultValueTest, BoolExists) { 331 EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists()); 332} 333 334// Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a 335// string type. 336TEST(BuiltInDefaultValueTest, IsEmptyStringForString) { 337 EXPECT_EQ("", BuiltInDefaultValue<::std::string>::Get()); 338} 339 340// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a 341// string type. 342TEST(BuiltInDefaultValueTest, ExistsForString) { 343 EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists()); 344} 345 346// Tests that BuiltInDefaultValue<const T>::Get() returns the same 347// value as BuiltInDefaultValue<T>::Get() does. 348TEST(BuiltInDefaultValueTest, WorksForConstTypes) { 349 EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get()); 350 EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get()); 351 EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr); 352 EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get()); 353} 354 355// A type that's default constructible. 356class MyDefaultConstructible { 357 public: 358 MyDefaultConstructible() : value_(42) {} 359 360 int value() const { return value_; } 361 362 private: 363 int value_; 364}; 365 366// A type that's not default constructible. 367class MyNonDefaultConstructible { 368 public: 369 // Does not have a default ctor. 370 explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {} 371 372 int value() const { return value_; } 373 374 private: 375 int value_; 376}; 377 378TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) { 379 EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists()); 380} 381 382TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) { 383 EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value()); 384} 385 386TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) { 387 EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists()); 388} 389 390// Tests that BuiltInDefaultValue<T&>::Get() aborts the program. 391TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) { 392 EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, ""); 393 EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, ""); 394} 395 396TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) { 397 EXPECT_DEATH_IF_SUPPORTED( 398 { BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, ""); 399} 400 401// Tests that DefaultValue<T>::IsSet() is false initially. 402TEST(DefaultValueTest, IsInitiallyUnset) { 403 EXPECT_FALSE(DefaultValue<int>::IsSet()); 404 EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet()); 405 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet()); 406} 407 408// Tests that DefaultValue<T> can be set and then unset. 409TEST(DefaultValueTest, CanBeSetAndUnset) { 410 EXPECT_TRUE(DefaultValue<int>::Exists()); 411 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists()); 412 413 DefaultValue<int>::Set(1); 414 DefaultValue<const MyNonDefaultConstructible>::Set( 415 MyNonDefaultConstructible(42)); 416 417 EXPECT_EQ(1, DefaultValue<int>::Get()); 418 EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value()); 419 420 EXPECT_TRUE(DefaultValue<int>::Exists()); 421 EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists()); 422 423 DefaultValue<int>::Clear(); 424 DefaultValue<const MyNonDefaultConstructible>::Clear(); 425 426 EXPECT_FALSE(DefaultValue<int>::IsSet()); 427 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet()); 428 429 EXPECT_TRUE(DefaultValue<int>::Exists()); 430 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists()); 431} 432 433// Tests that DefaultValue<T>::Get() returns the 434// BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is 435// false. 436TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { 437 EXPECT_FALSE(DefaultValue<int>::IsSet()); 438 EXPECT_TRUE(DefaultValue<int>::Exists()); 439 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet()); 440 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists()); 441 442 EXPECT_EQ(0, DefaultValue<int>::Get()); 443 444 EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); }, 445 ""); 446} 447 448TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { 449 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); 450 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr); 451 DefaultValue<std::unique_ptr<int>>::SetFactory( 452 [] { return std::make_unique<int>(42); }); 453 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); 454 std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get(); 455 EXPECT_EQ(42, *i); 456} 457 458// Tests that DefaultValue<void>::Get() returns void. 459TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); } 460 461// Tests using DefaultValue with a reference type. 462 463// Tests that DefaultValue<T&>::IsSet() is false initially. 464TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) { 465 EXPECT_FALSE(DefaultValue<int&>::IsSet()); 466 EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet()); 467 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); 468} 469 470// Tests that DefaultValue<T&>::Exists is false initially. 471TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) { 472 EXPECT_FALSE(DefaultValue<int&>::Exists()); 473 EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists()); 474 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists()); 475} 476 477// Tests that DefaultValue<T&> can be set and then unset. 478TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) { 479 int n = 1; 480 DefaultValue<const int&>::Set(n); 481 MyNonDefaultConstructible x(42); 482 DefaultValue<MyNonDefaultConstructible&>::Set(x); 483 484 EXPECT_TRUE(DefaultValue<const int&>::Exists()); 485 EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists()); 486 487 EXPECT_EQ(&n, &(DefaultValue<const int&>::Get())); 488 EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get())); 489 490 DefaultValue<const int&>::Clear(); 491 DefaultValue<MyNonDefaultConstructible&>::Clear(); 492 493 EXPECT_FALSE(DefaultValue<const int&>::Exists()); 494 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists()); 495 496 EXPECT_FALSE(DefaultValue<const int&>::IsSet()); 497 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); 498} 499 500// Tests that DefaultValue<T&>::Get() returns the 501// BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is 502// false. 503TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { 504 EXPECT_FALSE(DefaultValue<int&>::IsSet()); 505 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); 506 507 EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, ""); 508 EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); }, 509 ""); 510} 511 512// Tests that ActionInterface can be implemented by defining the 513// Perform method. 514 515typedef int MyGlobalFunction(bool, int); 516 517class MyActionImpl : public ActionInterface<MyGlobalFunction> { 518 public: 519 int Perform(const std::tuple<bool, int>& args) override { 520 return std::get<0>(args) ? std::get<1>(args) : 0; 521 } 522}; 523 524TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) { 525 MyActionImpl my_action_impl; 526 (void)my_action_impl; 527} 528 529TEST(ActionInterfaceTest, MakeAction) { 530 Action<MyGlobalFunction> action = MakeAction(new MyActionImpl); 531 532 // When exercising the Perform() method of Action<F>, we must pass 533 // it a tuple whose size and type are compatible with F's argument 534 // types. For example, if F is int(), then Perform() takes a 535 // 0-tuple; if F is void(bool, int), then Perform() takes a 536 // std::tuple<bool, int>, and so on. 537 EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5))); 538} 539 540// Tests that Action<F> can be constructed from a pointer to 541// ActionInterface<F>. 542TEST(ActionTest, CanBeConstructedFromActionInterface) { 543 Action<MyGlobalFunction> action(new MyActionImpl); 544} 545 546// Tests that Action<F> delegates actual work to ActionInterface<F>. 547TEST(ActionTest, DelegatesWorkToActionInterface) { 548 const Action<MyGlobalFunction> action(new MyActionImpl); 549 550 EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5))); 551 EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1))); 552} 553 554// Tests that Action<F> can be copied. 555TEST(ActionTest, IsCopyable) { 556 Action<MyGlobalFunction> a1(new MyActionImpl); 557 Action<MyGlobalFunction> a2(a1); // Tests the copy constructor. 558 559 // a1 should continue to work after being copied from. 560 EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); 561 EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1))); 562 563 // a2 should work like the action it was copied from. 564 EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5))); 565 EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1))); 566 567 a2 = a1; // Tests the assignment operator. 568 569 // a1 should continue to work after being copied from. 570 EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); 571 EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1))); 572 573 // a2 should work like the action it was copied from. 574 EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5))); 575 EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1))); 576} 577 578// Tests that an Action<From> object can be converted to a 579// compatible Action<To> object. 580 581class IsNotZero : public ActionInterface<bool(int)> { // NOLINT 582 public: 583 bool Perform(const std::tuple<int>& arg) override { 584 return std::get<0>(arg) != 0; 585 } 586}; 587 588TEST(ActionTest, CanBeConvertedToOtherActionType) { 589 const Action<bool(int)> a1(new IsNotZero); // NOLINT 590 const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT 591 EXPECT_EQ(1, a2.Perform(std::make_tuple('a'))); 592 EXPECT_EQ(0, a2.Perform(std::make_tuple('\0'))); 593} 594 595// The following two classes are for testing MakePolymorphicAction(). 596 597// Implements a polymorphic action that returns the second of the 598// arguments it receives. 599class ReturnSecondArgumentAction { 600 public: 601 // We want to verify that MakePolymorphicAction() can work with a 602 // polymorphic action whose Perform() method template is either 603 // const or not. This lets us verify the non-const case. 604 template <typename Result, typename ArgumentTuple> 605 Result Perform(const ArgumentTuple& args) { 606 return std::get<1>(args); 607 } 608}; 609 610// Implements a polymorphic action that can be used in a nullary 611// function to return 0. 612class ReturnZeroFromNullaryFunctionAction { 613 public: 614 // For testing that MakePolymorphicAction() works when the 615 // implementation class' Perform() method template takes only one 616 // template parameter. 617 // 618 // We want to verify that MakePolymorphicAction() can work with a 619 // polymorphic action whose Perform() method template is either 620 // const or not. This lets us verify the const case. 621 template <typename Result> 622 Result Perform(const std::tuple<>&) const { 623 return 0; 624 } 625}; 626 627// These functions verify that MakePolymorphicAction() returns a 628// PolymorphicAction<T> where T is the argument's type. 629 630PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { 631 return MakePolymorphicAction(ReturnSecondArgumentAction()); 632} 633 634PolymorphicAction<ReturnZeroFromNullaryFunctionAction> 635ReturnZeroFromNullaryFunction() { 636 return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction()); 637} 638 639// Tests that MakePolymorphicAction() turns a polymorphic action 640// implementation class into a polymorphic action. 641TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) { 642 Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT 643 EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0))); 644} 645 646// Tests that MakePolymorphicAction() works when the implementation 647// class' Perform() method template has only one template parameter. 648TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) { 649 Action<int()> a1 = ReturnZeroFromNullaryFunction(); 650 EXPECT_EQ(0, a1.Perform(std::make_tuple())); 651 652 Action<void*()> a2 = ReturnZeroFromNullaryFunction(); 653 EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr); 654} 655 656// Tests that Return() works as an action for void-returning 657// functions. 658TEST(ReturnTest, WorksForVoid) { 659 const Action<void(int)> ret = Return(); // NOLINT 660 return ret.Perform(std::make_tuple(1)); 661} 662 663// Tests that Return(v) returns v. 664TEST(ReturnTest, ReturnsGivenValue) { 665 Action<int()> ret = Return(1); // NOLINT 666 EXPECT_EQ(1, ret.Perform(std::make_tuple())); 667 668 ret = Return(-5); 669 EXPECT_EQ(-5, ret.Perform(std::make_tuple())); 670} 671 672// Tests that Return("string literal") works. 673TEST(ReturnTest, AcceptsStringLiteral) { 674 Action<const char*()> a1 = Return("Hello"); 675 EXPECT_STREQ("Hello", a1.Perform(std::make_tuple())); 676 677 Action<std::string()> a2 = Return("world"); 678 EXPECT_EQ("world", a2.Perform(std::make_tuple())); 679} 680 681// Return(x) should work fine when the mock function's return type is a 682// reference-like wrapper for decltype(x), as when x is a std::string and the 683// mock function returns std::string_view. 684TEST(ReturnTest, SupportsReferenceLikeReturnType) { 685 // A reference wrapper for std::vector<int>, implicitly convertible from it. 686 struct Result { 687 const std::vector<int>* v; 688 Result(const std::vector<int>& vec) : v(&vec) {} // NOLINT 689 }; 690 691 // Set up an action for a mock function that returns the reference wrapper 692 // type, initializing it with an actual vector. 693 // 694 // The returned wrapper should be initialized with a copy of that vector 695 // that's embedded within the action itself (which should stay alive as long 696 // as the mock object is alive), rather than e.g. a reference to the temporary 697 // we feed to Return. This should work fine both for WillOnce and 698 // WillRepeatedly. 699 MockFunction<Result()> mock; 700 EXPECT_CALL(mock, Call) 701 .WillOnce(Return(std::vector<int>{17, 19, 23})) 702 .WillRepeatedly(Return(std::vector<int>{29, 31, 37})); 703 704 EXPECT_THAT(mock.AsStdFunction()(), 705 Field(&Result::v, Pointee(ElementsAre(17, 19, 23)))); 706 707 EXPECT_THAT(mock.AsStdFunction()(), 708 Field(&Result::v, Pointee(ElementsAre(29, 31, 37)))); 709} 710 711TEST(ReturnTest, PrefersConversionOperator) { 712 // Define types In and Out such that: 713 // 714 // * In is implicitly convertible to Out. 715 // * Out also has an explicit constructor from In. 716 // 717 struct In; 718 struct Out { 719 int x; 720 721 explicit Out(const int val) : x(val) {} 722 explicit Out(const In&) : x(0) {} 723 }; 724 725 struct In { 726 operator Out() const { return Out{19}; } // NOLINT 727 }; 728 729 // Assumption check: the C++ language rules are such that a function that 730 // returns Out which uses In a return statement will use the implicit 731 // conversion path rather than the explicit constructor. 732 EXPECT_THAT([]() -> Out { return In(); }(), Field(&Out::x, 19)); 733 734 // Return should work the same way: if the mock function's return type is Out 735 // and we feed Return an In value, then the Out should be created through the 736 // implicit conversion path rather than the explicit constructor. 737 MockFunction<Out()> mock; 738 EXPECT_CALL(mock, Call).WillOnce(Return(In())); 739 EXPECT_THAT(mock.AsStdFunction()(), Field(&Out::x, 19)); 740} 741 742// It should be possible to use Return(R) with a mock function result type U 743// that is convertible from const R& but *not* R (such as 744// std::reference_wrapper). This should work for both WillOnce and 745// WillRepeatedly. 746TEST(ReturnTest, ConversionRequiresConstLvalueReference) { 747 using R = int; 748 using U = std::reference_wrapper<const int>; 749 750 static_assert(std::is_convertible<const R&, U>::value, ""); 751 static_assert(!std::is_convertible<R, U>::value, ""); 752 753 MockFunction<U()> mock; 754 EXPECT_CALL(mock, Call).WillOnce(Return(17)).WillRepeatedly(Return(19)); 755 756 EXPECT_EQ(17, mock.AsStdFunction()()); 757 EXPECT_EQ(19, mock.AsStdFunction()()); 758} 759 760// Return(x) should not be usable with a mock function result type that's 761// implicitly convertible from decltype(x) but requires a non-const lvalue 762// reference to the input. It doesn't make sense for the conversion operator to 763// modify the input. 764TEST(ReturnTest, ConversionRequiresMutableLvalueReference) { 765 // Set up a type that is implicitly convertible from std::string&, but not 766 // std::string&& or `const std::string&`. 767 // 768 // Avoid asserting about conversion from std::string on MSVC, which seems to 769 // implement std::is_convertible incorrectly in this case. 770 struct S { 771 S(std::string&) {} // NOLINT 772 }; 773 774 static_assert(std::is_convertible<std::string&, S>::value, ""); 775#ifndef _MSC_VER 776 static_assert(!std::is_convertible<std::string&&, S>::value, ""); 777#endif 778 static_assert(!std::is_convertible<const std::string&, S>::value, ""); 779 780 // It shouldn't be possible to use the result of Return(std::string) in a 781 // context where an S is needed. 782 // 783 // Here too we disable the assertion for MSVC, since its incorrect 784 // implementation of is_convertible causes our SFINAE to be wrong. 785 using RA = decltype(Return(std::string())); 786 787 static_assert(!std::is_convertible<RA, Action<S()>>::value, ""); 788#ifndef _MSC_VER 789 static_assert(!std::is_convertible<RA, OnceAction<S()>>::value, ""); 790#endif 791} 792 793TEST(ReturnTest, MoveOnlyResultType) { 794 // Return should support move-only result types when used with WillOnce. 795 { 796 MockFunction<std::unique_ptr<int>()> mock; 797 EXPECT_CALL(mock, Call) 798 // NOLINTNEXTLINE 799 .WillOnce(Return(std::unique_ptr<int>(new int(17)))); 800 801 EXPECT_THAT(mock.AsStdFunction()(), Pointee(17)); 802 } 803 804 // The result of Return should not be convertible to Action (so it can't be 805 // used with WillRepeatedly). 806 static_assert(!std::is_convertible<decltype(Return(std::unique_ptr<int>())), 807 Action<std::unique_ptr<int>()>>::value, 808 ""); 809} 810 811// Tests that Return(v) is covariant. 812 813struct Base { 814 bool operator==(const Base&) { return true; } 815}; 816 817struct Derived : public Base { 818 bool operator==(const Derived&) { return true; } 819}; 820 821TEST(ReturnTest, IsCovariant) { 822 Base base; 823 Derived derived; 824 Action<Base*()> ret = Return(&base); 825 EXPECT_EQ(&base, ret.Perform(std::make_tuple())); 826 827 ret = Return(&derived); 828 EXPECT_EQ(&derived, ret.Perform(std::make_tuple())); 829} 830 831// Tests that the type of the value passed into Return is converted into T 832// when the action is cast to Action<T(...)> rather than when the action is 833// performed. See comments on testing::internal::ReturnAction in 834// gmock-actions.h for more information. 835class FromType { 836 public: 837 explicit FromType(bool* is_converted) : converted_(is_converted) {} 838 bool* converted() const { return converted_; } 839 840 private: 841 bool* const converted_; 842}; 843 844class ToType { 845 public: 846 // Must allow implicit conversion due to use in ImplicitCast_<T>. 847 ToType(const FromType& x) { *x.converted() = true; } // NOLINT 848}; 849 850TEST(ReturnTest, ConvertsArgumentWhenConverted) { 851 bool converted = false; 852 FromType x(&converted); 853 Action<ToType()> action(Return(x)); 854 EXPECT_TRUE(converted) << "Return must convert its argument in its own " 855 << "conversion operator."; 856 converted = false; 857 action.Perform(std::tuple<>()); 858 EXPECT_FALSE(converted) << "Action must NOT convert its argument " 859 << "when performed."; 860} 861 862// Tests that ReturnNull() returns NULL in a pointer-returning function. 863TEST(ReturnNullTest, WorksInPointerReturningFunction) { 864 const Action<int*()> a1 = ReturnNull(); 865 EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr); 866 867 const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT 868 EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr); 869} 870 871// Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning 872// functions. 873TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) { 874 const Action<std::unique_ptr<const int>()> a1 = ReturnNull(); 875 EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr); 876 877 const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull(); 878 EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr); 879} 880 881// Tests that ReturnRef(v) works for reference types. 882TEST(ReturnRefTest, WorksForReference) { 883 const int n = 0; 884 const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT 885 886 EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true))); 887} 888 889// Tests that ReturnRef(v) is covariant. 890TEST(ReturnRefTest, IsCovariant) { 891 Base base; 892 Derived derived; 893 Action<Base&()> a = ReturnRef(base); 894 EXPECT_EQ(&base, &a.Perform(std::make_tuple())); 895 896 a = ReturnRef(derived); 897 EXPECT_EQ(&derived, &a.Perform(std::make_tuple())); 898} 899 900template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))> 901bool CanCallReturnRef(T&&) { 902 return true; 903} 904bool CanCallReturnRef(Unused) { return false; } 905 906// Tests that ReturnRef(v) is working with non-temporaries (T&) 907TEST(ReturnRefTest, WorksForNonTemporary) { 908 int scalar_value = 123; 909 EXPECT_TRUE(CanCallReturnRef(scalar_value)); 910 911 std::string non_scalar_value("ABC"); 912 EXPECT_TRUE(CanCallReturnRef(non_scalar_value)); 913 914 const int const_scalar_value{321}; 915 EXPECT_TRUE(CanCallReturnRef(const_scalar_value)); 916 917 const std::string const_non_scalar_value("CBA"); 918 EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value)); 919} 920 921// Tests that ReturnRef(v) is not working with temporaries (T&&) 922TEST(ReturnRefTest, DoesNotWorkForTemporary) { 923 auto scalar_value = []() -> int { return 123; }; 924 EXPECT_FALSE(CanCallReturnRef(scalar_value())); 925 926 auto non_scalar_value = []() -> std::string { return "ABC"; }; 927 EXPECT_FALSE(CanCallReturnRef(non_scalar_value())); 928 929 // cannot use here callable returning "const scalar type", 930 // because such const for scalar return type is ignored 931 EXPECT_FALSE(CanCallReturnRef(static_cast<const int>(321))); 932 933 auto const_non_scalar_value = []() -> const std::string { return "CBA"; }; 934 EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value())); 935} 936 937// Tests that ReturnRefOfCopy(v) works for reference types. 938TEST(ReturnRefOfCopyTest, WorksForReference) { 939 int n = 42; 940 const Action<const int&()> ret = ReturnRefOfCopy(n); 941 942 EXPECT_NE(&n, &ret.Perform(std::make_tuple())); 943 EXPECT_EQ(42, ret.Perform(std::make_tuple())); 944 945 n = 43; 946 EXPECT_NE(&n, &ret.Perform(std::make_tuple())); 947 EXPECT_EQ(42, ret.Perform(std::make_tuple())); 948} 949 950// Tests that ReturnRefOfCopy(v) is covariant. 951TEST(ReturnRefOfCopyTest, IsCovariant) { 952 Base base; 953 Derived derived; 954 Action<Base&()> a = ReturnRefOfCopy(base); 955 EXPECT_NE(&base, &a.Perform(std::make_tuple())); 956 957 a = ReturnRefOfCopy(derived); 958 EXPECT_NE(&derived, &a.Perform(std::make_tuple())); 959} 960 961// Tests that ReturnRoundRobin(v) works with initializer lists 962TEST(ReturnRoundRobinTest, WorksForInitList) { 963 Action<int()> ret = ReturnRoundRobin({1, 2, 3}); 964 965 EXPECT_EQ(1, ret.Perform(std::make_tuple())); 966 EXPECT_EQ(2, ret.Perform(std::make_tuple())); 967 EXPECT_EQ(3, ret.Perform(std::make_tuple())); 968 EXPECT_EQ(1, ret.Perform(std::make_tuple())); 969 EXPECT_EQ(2, ret.Perform(std::make_tuple())); 970 EXPECT_EQ(3, ret.Perform(std::make_tuple())); 971} 972 973// Tests that ReturnRoundRobin(v) works with vectors 974TEST(ReturnRoundRobinTest, WorksForVector) { 975 std::vector<double> v = {4.4, 5.5, 6.6}; 976 Action<double()> ret = ReturnRoundRobin(v); 977 978 EXPECT_EQ(4.4, ret.Perform(std::make_tuple())); 979 EXPECT_EQ(5.5, ret.Perform(std::make_tuple())); 980 EXPECT_EQ(6.6, ret.Perform(std::make_tuple())); 981 EXPECT_EQ(4.4, ret.Perform(std::make_tuple())); 982 EXPECT_EQ(5.5, ret.Perform(std::make_tuple())); 983 EXPECT_EQ(6.6, ret.Perform(std::make_tuple())); 984} 985 986// Tests that DoDefault() does the default action for the mock method. 987 988class MockClass { 989 public: 990 MockClass() = default; 991 992 MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT 993 MOCK_METHOD0(Foo, MyNonDefaultConstructible()); 994 MOCK_METHOD0(MakeUnique, std::unique_ptr<int>()); 995 MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>()); 996 MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>()); 997 MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>)); 998 MOCK_METHOD2(TakeUnique, 999 int(const std::unique_ptr<int>&, std::unique_ptr<int>)); 1000 1001 private: 1002 MockClass(const MockClass&) = delete; 1003 MockClass& operator=(const MockClass&) = delete; 1004}; 1005 1006// Tests that DoDefault() returns the built-in default value for the 1007// return type by default. 1008TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) { 1009 MockClass mock; 1010 EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); 1011 EXPECT_EQ(0, mock.IntFunc(true)); 1012} 1013 1014// Tests that DoDefault() throws (when exceptions are enabled) or aborts 1015// the process when there is no built-in default value for the return type. 1016TEST(DoDefaultDeathTest, DiesForUnknowType) { 1017 MockClass mock; 1018 EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault()); 1019#if GTEST_HAS_EXCEPTIONS 1020 EXPECT_ANY_THROW(mock.Foo()); 1021#else 1022 EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, ""); 1023#endif 1024} 1025 1026// Tests that using DoDefault() inside a composite action leads to a 1027// run-time error. 1028 1029void VoidFunc(bool /* flag */) {} 1030 1031TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) { 1032 MockClass mock; 1033 EXPECT_CALL(mock, IntFunc(_)) 1034 .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault())); 1035 1036 // Ideally we should verify the error message as well. Sadly, 1037 // EXPECT_DEATH() can only capture stderr, while Google Mock's 1038 // errors are printed on stdout. Therefore we have to settle for 1039 // not verifying the message. 1040 EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, ""); 1041} 1042 1043// Tests that DoDefault() returns the default value set by 1044// DefaultValue<T>::Set() when it's not overridden by an ON_CALL(). 1045TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) { 1046 DefaultValue<int>::Set(1); 1047 MockClass mock; 1048 EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); 1049 EXPECT_EQ(1, mock.IntFunc(false)); 1050 DefaultValue<int>::Clear(); 1051} 1052 1053// Tests that DoDefault() does the action specified by ON_CALL(). 1054TEST(DoDefaultTest, DoesWhatOnCallSpecifies) { 1055 MockClass mock; 1056 ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2)); 1057 EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); 1058 EXPECT_EQ(2, mock.IntFunc(false)); 1059} 1060 1061// Tests that using DoDefault() in ON_CALL() leads to a run-time failure. 1062TEST(DoDefaultTest, CannotBeUsedInOnCall) { 1063 MockClass mock; 1064 EXPECT_NONFATAL_FAILURE( 1065 { // NOLINT 1066 ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault()); 1067 }, 1068 "DoDefault() cannot be used in ON_CALL()"); 1069} 1070 1071// Tests that SetArgPointee<N>(v) sets the variable pointed to by 1072// the N-th (0-based) argument to v. 1073TEST(SetArgPointeeTest, SetsTheNthPointee) { 1074 typedef void MyFunction(bool, int*, char*); 1075 Action<MyFunction> a = SetArgPointee<1>(2); 1076 1077 int n = 0; 1078 char ch = '\0'; 1079 a.Perform(std::make_tuple(true, &n, &ch)); 1080 EXPECT_EQ(2, n); 1081 EXPECT_EQ('\0', ch); 1082 1083 a = SetArgPointee<2>('a'); 1084 n = 0; 1085 ch = '\0'; 1086 a.Perform(std::make_tuple(true, &n, &ch)); 1087 EXPECT_EQ(0, n); 1088 EXPECT_EQ('a', ch); 1089} 1090 1091// Tests that SetArgPointee<N>() accepts a string literal. 1092TEST(SetArgPointeeTest, AcceptsStringLiteral) { 1093 typedef void MyFunction(std::string*, const char**); 1094 Action<MyFunction> a = SetArgPointee<0>("hi"); 1095 std::string str; 1096 const char* ptr = nullptr; 1097 a.Perform(std::make_tuple(&str, &ptr)); 1098 EXPECT_EQ("hi", str); 1099 EXPECT_TRUE(ptr == nullptr); 1100 1101 a = SetArgPointee<1>("world"); 1102 str = ""; 1103 a.Perform(std::make_tuple(&str, &ptr)); 1104 EXPECT_EQ("", str); 1105 EXPECT_STREQ("world", ptr); 1106} 1107 1108TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { 1109 typedef void MyFunction(const wchar_t**); 1110 Action<MyFunction> a = SetArgPointee<0>(L"world"); 1111 const wchar_t* ptr = nullptr; 1112 a.Perform(std::make_tuple(&ptr)); 1113 EXPECT_STREQ(L"world", ptr); 1114 1115#if GTEST_HAS_STD_WSTRING 1116 1117 typedef void MyStringFunction(std::wstring*); 1118 Action<MyStringFunction> a2 = SetArgPointee<0>(L"world"); 1119 std::wstring str = L""; 1120 a2.Perform(std::make_tuple(&str)); 1121 EXPECT_EQ(L"world", str); 1122 1123#endif 1124} 1125 1126// Tests that SetArgPointee<N>() accepts a char pointer. 1127TEST(SetArgPointeeTest, AcceptsCharPointer) { 1128 typedef void MyFunction(bool, std::string*, const char**); 1129 const char* const hi = "hi"; 1130 Action<MyFunction> a = SetArgPointee<1>(hi); 1131 std::string str; 1132 const char* ptr = nullptr; 1133 a.Perform(std::make_tuple(true, &str, &ptr)); 1134 EXPECT_EQ("hi", str); 1135 EXPECT_TRUE(ptr == nullptr); 1136 1137 char world_array[] = "world"; 1138 char* const world = world_array; 1139 a = SetArgPointee<2>(world); 1140 str = ""; 1141 a.Perform(std::make_tuple(true, &str, &ptr)); 1142 EXPECT_EQ("", str); 1143 EXPECT_EQ(world, ptr); 1144} 1145 1146TEST(SetArgPointeeTest, AcceptsWideCharPointer) { 1147 typedef void MyFunction(bool, const wchar_t**); 1148 const wchar_t* const hi = L"hi"; 1149 Action<MyFunction> a = SetArgPointee<1>(hi); 1150 const wchar_t* ptr = nullptr; 1151 a.Perform(std::make_tuple(true, &ptr)); 1152 EXPECT_EQ(hi, ptr); 1153 1154#if GTEST_HAS_STD_WSTRING 1155 1156 typedef void MyStringFunction(bool, std::wstring*); 1157 wchar_t world_array[] = L"world"; 1158 wchar_t* const world = world_array; 1159 Action<MyStringFunction> a2 = SetArgPointee<1>(world); 1160 std::wstring str; 1161 a2.Perform(std::make_tuple(true, &str)); 1162 EXPECT_EQ(world_array, str); 1163#endif 1164} 1165 1166// Tests that SetArgumentPointee<N>(v) sets the variable pointed to by 1167// the N-th (0-based) argument to v. 1168TEST(SetArgumentPointeeTest, SetsTheNthPointee) { 1169 typedef void MyFunction(bool, int*, char*); 1170 Action<MyFunction> a = SetArgumentPointee<1>(2); 1171 1172 int n = 0; 1173 char ch = '\0'; 1174 a.Perform(std::make_tuple(true, &n, &ch)); 1175 EXPECT_EQ(2, n); 1176 EXPECT_EQ('\0', ch); 1177 1178 a = SetArgumentPointee<2>('a'); 1179 n = 0; 1180 ch = '\0'; 1181 a.Perform(std::make_tuple(true, &n, &ch)); 1182 EXPECT_EQ(0, n); 1183 EXPECT_EQ('a', ch); 1184} 1185 1186// Sample functions and functors for testing Invoke() and etc. 1187int Nullary() { return 1; } 1188 1189class NullaryFunctor { 1190 public: 1191 int operator()() { return 2; } 1192}; 1193 1194bool g_done = false; 1195void VoidNullary() { g_done = true; } 1196 1197class VoidNullaryFunctor { 1198 public: 1199 void operator()() { g_done = true; } 1200}; 1201 1202short Short(short n) { return n; } // NOLINT 1203char Char(char ch) { return ch; } 1204 1205const char* CharPtr(const char* s) { return s; } 1206 1207bool Unary(int x) { return x < 0; } 1208 1209const char* Binary(const char* input, short n) { return input + n; } // NOLINT 1210 1211void VoidBinary(int, char) { g_done = true; } 1212 1213int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT 1214 1215int SumOf4(int a, int b, int c, int d) { return a + b + c + d; } 1216 1217class Foo { 1218 public: 1219 Foo() : value_(123) {} 1220 1221 int Nullary() const { return value_; } 1222 1223 private: 1224 int value_; 1225}; 1226 1227// Tests InvokeWithoutArgs(function). 1228TEST(InvokeWithoutArgsTest, Function) { 1229 // As an action that takes one argument. 1230 Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT 1231 EXPECT_EQ(1, a.Perform(std::make_tuple(2))); 1232 1233 // As an action that takes two arguments. 1234 Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT 1235 EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5))); 1236 1237 // As an action that returns void. 1238 Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT 1239 g_done = false; 1240 a3.Perform(std::make_tuple(1)); 1241 EXPECT_TRUE(g_done); 1242} 1243 1244// Tests InvokeWithoutArgs(functor). 1245TEST(InvokeWithoutArgsTest, Functor) { 1246 // As an action that takes no argument. 1247 Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT 1248 EXPECT_EQ(2, a.Perform(std::make_tuple())); 1249 1250 // As an action that takes three arguments. 1251 Action<int(int, double, char)> a2 = // NOLINT 1252 InvokeWithoutArgs(NullaryFunctor()); 1253 EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a'))); 1254 1255 // As an action that returns void. 1256 Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor()); 1257 g_done = false; 1258 a3.Perform(std::make_tuple()); 1259 EXPECT_TRUE(g_done); 1260} 1261 1262// Tests InvokeWithoutArgs(obj_ptr, method). 1263TEST(InvokeWithoutArgsTest, Method) { 1264 Foo foo; 1265 Action<int(bool, char)> a = // NOLINT 1266 InvokeWithoutArgs(&foo, &Foo::Nullary); 1267 EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a'))); 1268} 1269 1270// Tests using IgnoreResult() on a polymorphic action. 1271TEST(IgnoreResultTest, PolymorphicAction) { 1272 Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT 1273 a.Perform(std::make_tuple(1)); 1274} 1275 1276// Tests using IgnoreResult() on a monomorphic action. 1277 1278int ReturnOne() { 1279 g_done = true; 1280 return 1; 1281} 1282 1283TEST(IgnoreResultTest, MonomorphicAction) { 1284 g_done = false; 1285 Action<void()> a = IgnoreResult(Invoke(ReturnOne)); 1286 a.Perform(std::make_tuple()); 1287 EXPECT_TRUE(g_done); 1288} 1289 1290// Tests using IgnoreResult() on an action that returns a class type. 1291 1292MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) { 1293 g_done = true; 1294 return MyNonDefaultConstructible(42); 1295} 1296 1297TEST(IgnoreResultTest, ActionReturningClass) { 1298 g_done = false; 1299 Action<void(int)> a = 1300 IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT 1301 a.Perform(std::make_tuple(2)); 1302 EXPECT_TRUE(g_done); 1303} 1304 1305TEST(AssignTest, Int) { 1306 int x = 0; 1307 Action<void(int)> a = Assign(&x, 5); 1308 a.Perform(std::make_tuple(0)); 1309 EXPECT_EQ(5, x); 1310} 1311 1312TEST(AssignTest, String) { 1313 ::std::string x; 1314 Action<void(void)> a = Assign(&x, "Hello, world"); 1315 a.Perform(std::make_tuple()); 1316 EXPECT_EQ("Hello, world", x); 1317} 1318 1319TEST(AssignTest, CompatibleTypes) { 1320 double x = 0; 1321 Action<void(int)> a = Assign(&x, 5); 1322 a.Perform(std::make_tuple(0)); 1323 EXPECT_DOUBLE_EQ(5, x); 1324} 1325 1326// DoAll should support &&-qualified actions when used with WillOnce. 1327TEST(DoAll, SupportsRefQualifiedActions) { 1328 struct InitialAction { 1329 void operator()(const int arg) && { EXPECT_EQ(17, arg); } 1330 }; 1331 1332 struct FinalAction { 1333 int operator()() && { return 19; } 1334 }; 1335 1336 MockFunction<int(int)> mock; 1337 EXPECT_CALL(mock, Call).WillOnce(DoAll(InitialAction{}, FinalAction{})); 1338 EXPECT_EQ(19, mock.AsStdFunction()(17)); 1339} 1340 1341// DoAll should never provide rvalue references to the initial actions. If the 1342// mock action itself accepts an rvalue reference or a non-scalar object by 1343// value then the final action should receive an rvalue reference, but initial 1344// actions should receive only lvalue references. 1345TEST(DoAll, ProvidesLvalueReferencesToInitialActions) { 1346 struct Obj {}; 1347 1348 // Mock action accepts by value: the initial action should be fed a const 1349 // lvalue reference, and the final action an rvalue reference. 1350 { 1351 struct InitialAction { 1352 void operator()(Obj&) const { FAIL() << "Unexpected call"; } 1353 void operator()(const Obj&) const {} 1354 void operator()(Obj&&) const { FAIL() << "Unexpected call"; } 1355 void operator()(const Obj&&) const { FAIL() << "Unexpected call"; } 1356 }; 1357 1358 MockFunction<void(Obj)> mock; 1359 EXPECT_CALL(mock, Call) 1360 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {})) 1361 .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {})); 1362 1363 mock.AsStdFunction()(Obj{}); 1364 mock.AsStdFunction()(Obj{}); 1365 } 1366 1367 // Mock action accepts by const lvalue reference: both actions should receive 1368 // a const lvalue reference. 1369 { 1370 struct InitialAction { 1371 void operator()(Obj&) const { FAIL() << "Unexpected call"; } 1372 void operator()(const Obj&) const {} 1373 void operator()(Obj&&) const { FAIL() << "Unexpected call"; } 1374 void operator()(const Obj&&) const { FAIL() << "Unexpected call"; } 1375 }; 1376 1377 MockFunction<void(const Obj&)> mock; 1378 EXPECT_CALL(mock, Call) 1379 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {})) 1380 .WillRepeatedly( 1381 DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {})); 1382 1383 mock.AsStdFunction()(Obj{}); 1384 mock.AsStdFunction()(Obj{}); 1385 } 1386 1387 // Mock action accepts by non-const lvalue reference: both actions should get 1388 // a non-const lvalue reference if they want them. 1389 { 1390 struct InitialAction { 1391 void operator()(Obj&) const {} 1392 void operator()(Obj&&) const { FAIL() << "Unexpected call"; } 1393 }; 1394 1395 MockFunction<void(Obj&)> mock; 1396 EXPECT_CALL(mock, Call) 1397 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {})) 1398 .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {})); 1399 1400 Obj obj; 1401 mock.AsStdFunction()(obj); 1402 mock.AsStdFunction()(obj); 1403 } 1404 1405 // Mock action accepts by rvalue reference: the initial actions should receive 1406 // a non-const lvalue reference if it wants it, and the final action an rvalue 1407 // reference. 1408 { 1409 struct InitialAction { 1410 void operator()(Obj&) const {} 1411 void operator()(Obj&&) const { FAIL() << "Unexpected call"; } 1412 }; 1413 1414 MockFunction<void(Obj&&)> mock; 1415 EXPECT_CALL(mock, Call) 1416 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {})) 1417 .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {})); 1418 1419 mock.AsStdFunction()(Obj{}); 1420 mock.AsStdFunction()(Obj{}); 1421 } 1422 1423 // &&-qualified initial actions should also be allowed with WillOnce. 1424 { 1425 struct InitialAction { 1426 void operator()(Obj&) && {} 1427 }; 1428 1429 MockFunction<void(Obj&)> mock; 1430 EXPECT_CALL(mock, Call) 1431 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {})); 1432 1433 Obj obj; 1434 mock.AsStdFunction()(obj); 1435 } 1436 1437 { 1438 struct InitialAction { 1439 void operator()(Obj&) && {} 1440 }; 1441 1442 MockFunction<void(Obj&&)> mock; 1443 EXPECT_CALL(mock, Call) 1444 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {})); 1445 1446 mock.AsStdFunction()(Obj{}); 1447 } 1448} 1449 1450// DoAll should support being used with type-erased Action objects, both through 1451// WillOnce and WillRepeatedly. 1452TEST(DoAll, SupportsTypeErasedActions) { 1453 // With only type-erased actions. 1454 const Action<void()> initial_action = [] {}; 1455 const Action<int()> final_action = [] { return 17; }; 1456 1457 MockFunction<int()> mock; 1458 EXPECT_CALL(mock, Call) 1459 .WillOnce(DoAll(initial_action, initial_action, final_action)) 1460 .WillRepeatedly(DoAll(initial_action, initial_action, final_action)); 1461 1462 EXPECT_EQ(17, mock.AsStdFunction()()); 1463 1464 // With &&-qualified and move-only final action. 1465 { 1466 struct FinalAction { 1467 FinalAction() = default; 1468 FinalAction(FinalAction&&) = default; 1469 1470 int operator()() && { return 17; } 1471 }; 1472 1473 EXPECT_CALL(mock, Call) 1474 .WillOnce(DoAll(initial_action, initial_action, FinalAction{})); 1475 1476 EXPECT_EQ(17, mock.AsStdFunction()()); 1477 } 1478} 1479 1480// Tests using WithArgs and with an action that takes 1 argument. 1481TEST(WithArgsTest, OneArg) { 1482 Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT 1483 EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1))); 1484 EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1))); 1485} 1486 1487// Tests using WithArgs with an action that takes 2 arguments. 1488TEST(WithArgsTest, TwoArgs) { 1489 Action<const char*(const char* s, double x, short n)> a = // NOLINT 1490 WithArgs<0, 2>(Invoke(Binary)); 1491 const char s[] = "Hello"; 1492 EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2)))); 1493} 1494 1495struct ConcatAll { 1496 std::string operator()() const { return {}; } 1497 template <typename... I> 1498 std::string operator()(const char* a, I... i) const { 1499 return a + ConcatAll()(i...); 1500 } 1501}; 1502 1503// Tests using WithArgs with an action that takes 10 arguments. 1504TEST(WithArgsTest, TenArgs) { 1505 Action<std::string(const char*, const char*, const char*, const char*)> a = 1506 WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{})); 1507 EXPECT_EQ("0123210123", 1508 a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), 1509 CharPtr("3")))); 1510} 1511 1512// Tests using WithArgs with an action that is not Invoke(). 1513class SubtractAction : public ActionInterface<int(int, int)> { 1514 public: 1515 int Perform(const std::tuple<int, int>& args) override { 1516 return std::get<0>(args) - std::get<1>(args); 1517 } 1518}; 1519 1520TEST(WithArgsTest, NonInvokeAction) { 1521 Action<int(const std::string&, int, int)> a = 1522 WithArgs<2, 1>(MakeAction(new SubtractAction)); 1523 std::tuple<std::string, int, int> dummy = 1524 std::make_tuple(std::string("hi"), 2, 10); 1525 EXPECT_EQ(8, a.Perform(dummy)); 1526} 1527 1528// Tests using WithArgs to pass all original arguments in the original order. 1529TEST(WithArgsTest, Identity) { 1530 Action<int(int x, char y, short z)> a = // NOLINT 1531 WithArgs<0, 1, 2>(Invoke(Ternary)); 1532 EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3)))); 1533} 1534 1535// Tests using WithArgs with repeated arguments. 1536TEST(WithArgsTest, RepeatedArguments) { 1537 Action<int(bool, int m, int n)> a = // NOLINT 1538 WithArgs<1, 1, 1, 1>(Invoke(SumOf4)); 1539 EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10))); 1540} 1541 1542// Tests using WithArgs with reversed argument order. 1543TEST(WithArgsTest, ReversedArgumentOrder) { 1544 Action<const char*(short n, const char* input)> a = // NOLINT 1545 WithArgs<1, 0>(Invoke(Binary)); 1546 const char s[] = "Hello"; 1547 EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s)))); 1548} 1549 1550// Tests using WithArgs with compatible, but not identical, argument types. 1551TEST(WithArgsTest, ArgsOfCompatibleTypes) { 1552 Action<long(short x, char y, double z, char c)> a = // NOLINT 1553 WithArgs<0, 1, 3>(Invoke(Ternary)); 1554 EXPECT_EQ(123, 1555 a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3)))); 1556} 1557 1558// Tests using WithArgs with an action that returns void. 1559TEST(WithArgsTest, VoidAction) { 1560 Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary)); 1561 g_done = false; 1562 a.Perform(std::make_tuple(1.5, 'a', 3)); 1563 EXPECT_TRUE(g_done); 1564} 1565 1566TEST(WithArgsTest, ReturnReference) { 1567 Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; }); 1568 int i = 0; 1569 const int& res = aa.Perform(std::forward_as_tuple(i, nullptr)); 1570 EXPECT_EQ(&i, &res); 1571} 1572 1573TEST(WithArgsTest, InnerActionWithConversion) { 1574 Action<Derived*()> inner = [] { return nullptr; }; 1575 1576 MockFunction<Base*(double)> mock; 1577 EXPECT_CALL(mock, Call) 1578 .WillOnce(WithoutArgs(inner)) 1579 .WillRepeatedly(WithoutArgs(inner)); 1580 1581 EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1)); 1582 EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1)); 1583} 1584 1585// It should be possible to use an &&-qualified inner action as long as the 1586// whole shebang is used as an rvalue with WillOnce. 1587TEST(WithArgsTest, RefQualifiedInnerAction) { 1588 struct SomeAction { 1589 int operator()(const int arg) && { 1590 EXPECT_EQ(17, arg); 1591 return 19; 1592 } 1593 }; 1594 1595 MockFunction<int(int, int)> mock; 1596 EXPECT_CALL(mock, Call).WillOnce(WithArg<1>(SomeAction{})); 1597 EXPECT_EQ(19, mock.AsStdFunction()(0, 17)); 1598} 1599 1600#ifndef GTEST_OS_WINDOWS_MOBILE 1601 1602class SetErrnoAndReturnTest : public testing::Test { 1603 protected: 1604 void SetUp() override { errno = 0; } 1605 void TearDown() override { errno = 0; } 1606}; 1607 1608TEST_F(SetErrnoAndReturnTest, Int) { 1609 Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5); 1610 EXPECT_EQ(-5, a.Perform(std::make_tuple())); 1611 EXPECT_EQ(ENOTTY, errno); 1612} 1613 1614TEST_F(SetErrnoAndReturnTest, Ptr) { 1615 int x; 1616 Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x); 1617 EXPECT_EQ(&x, a.Perform(std::make_tuple())); 1618 EXPECT_EQ(ENOTTY, errno); 1619} 1620 1621TEST_F(SetErrnoAndReturnTest, CompatibleTypes) { 1622 Action<double()> a = SetErrnoAndReturn(EINVAL, 5); 1623 EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple())); 1624 EXPECT_EQ(EINVAL, errno); 1625} 1626 1627#endif // !GTEST_OS_WINDOWS_MOBILE 1628 1629// Tests ByRef(). 1630 1631// Tests that the result of ByRef() is copyable. 1632TEST(ByRefTest, IsCopyable) { 1633 const std::string s1 = "Hi"; 1634 const std::string s2 = "Hello"; 1635 1636 auto ref_wrapper = ByRef(s1); 1637 const std::string& r1 = ref_wrapper; 1638 EXPECT_EQ(&s1, &r1); 1639 1640 // Assigns a new value to ref_wrapper. 1641 ref_wrapper = ByRef(s2); 1642 const std::string& r2 = ref_wrapper; 1643 EXPECT_EQ(&s2, &r2); 1644 1645 auto ref_wrapper1 = ByRef(s1); 1646 // Copies ref_wrapper1 to ref_wrapper. 1647 ref_wrapper = ref_wrapper1; 1648 const std::string& r3 = ref_wrapper; 1649 EXPECT_EQ(&s1, &r3); 1650} 1651 1652// Tests using ByRef() on a const value. 1653TEST(ByRefTest, ConstValue) { 1654 const int n = 0; 1655 // int& ref = ByRef(n); // This shouldn't compile - we have a 1656 // negative compilation test to catch it. 1657 const int& const_ref = ByRef(n); 1658 EXPECT_EQ(&n, &const_ref); 1659} 1660 1661// Tests using ByRef() on a non-const value. 1662TEST(ByRefTest, NonConstValue) { 1663 int n = 0; 1664 1665 // ByRef(n) can be used as either an int&, 1666 int& ref = ByRef(n); 1667 EXPECT_EQ(&n, &ref); 1668 1669 // or a const int&. 1670 const int& const_ref = ByRef(n); 1671 EXPECT_EQ(&n, &const_ref); 1672} 1673 1674// Tests explicitly specifying the type when using ByRef(). 1675TEST(ByRefTest, ExplicitType) { 1676 int n = 0; 1677 const int& r1 = ByRef<const int>(n); 1678 EXPECT_EQ(&n, &r1); 1679 1680 // ByRef<char>(n); // This shouldn't compile - we have a negative 1681 // compilation test to catch it. 1682 1683 Derived d; 1684 Derived& r2 = ByRef<Derived>(d); 1685 EXPECT_EQ(&d, &r2); 1686 1687 const Derived& r3 = ByRef<const Derived>(d); 1688 EXPECT_EQ(&d, &r3); 1689 1690 Base& r4 = ByRef<Base>(d); 1691 EXPECT_EQ(&d, &r4); 1692 1693 const Base& r5 = ByRef<const Base>(d); 1694 EXPECT_EQ(&d, &r5); 1695 1696 // The following shouldn't compile - we have a negative compilation 1697 // test for it. 1698 // 1699 // Base b; 1700 // ByRef<Derived>(b); 1701} 1702 1703// Tests that Google Mock prints expression ByRef(x) as a reference to x. 1704TEST(ByRefTest, PrintsCorrectly) { 1705 int n = 42; 1706 ::std::stringstream expected, actual; 1707 testing::internal::UniversalPrinter<const int&>::Print(n, &expected); 1708 testing::internal::UniversalPrint(ByRef(n), &actual); 1709 EXPECT_EQ(expected.str(), actual.str()); 1710} 1711 1712struct UnaryConstructorClass { 1713 explicit UnaryConstructorClass(int v) : value(v) {} 1714 int value; 1715}; 1716 1717// Tests using ReturnNew() with a unary constructor. 1718TEST(ReturnNewTest, Unary) { 1719 Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000); 1720 UnaryConstructorClass* c = a.Perform(std::make_tuple()); 1721 EXPECT_EQ(4000, c->value); 1722 delete c; 1723} 1724 1725TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) { 1726 Action<UnaryConstructorClass*(bool, int)> a = 1727 ReturnNew<UnaryConstructorClass>(4000); 1728 UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5)); 1729 EXPECT_EQ(4000, c->value); 1730 delete c; 1731} 1732 1733TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) { 1734 Action<const UnaryConstructorClass*()> a = 1735 ReturnNew<UnaryConstructorClass>(4000); 1736 const UnaryConstructorClass* c = a.Perform(std::make_tuple()); 1737 EXPECT_EQ(4000, c->value); 1738 delete c; 1739} 1740 1741class TenArgConstructorClass { 1742 public: 1743 TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7, 1744 int a8, int a9, int a10) 1745 : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {} 1746 int value_; 1747}; 1748 1749// Tests using ReturnNew() with a 10-argument constructor. 1750TEST(ReturnNewTest, ConstructorThatTakes10Arguments) { 1751 Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>( 1752 1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90, 1753 0); 1754 TenArgConstructorClass* c = a.Perform(std::make_tuple()); 1755 EXPECT_EQ(1234567890, c->value_); 1756 delete c; 1757} 1758 1759std::unique_ptr<int> UniquePtrSource() { return std::make_unique<int>(19); } 1760 1761std::vector<std::unique_ptr<int>> VectorUniquePtrSource() { 1762 std::vector<std::unique_ptr<int>> out; 1763 out.emplace_back(new int(7)); 1764 return out; 1765} 1766 1767TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) { 1768 MockClass mock; 1769 std::unique_ptr<int> i(new int(19)); 1770 EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i)))); 1771 EXPECT_CALL(mock, MakeVectorUnique()) 1772 .WillOnce(Return(ByMove(VectorUniquePtrSource()))); 1773 Derived* d = new Derived; 1774 EXPECT_CALL(mock, MakeUniqueBase()) 1775 .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d)))); 1776 1777 std::unique_ptr<int> result1 = mock.MakeUnique(); 1778 EXPECT_EQ(19, *result1); 1779 1780 std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique(); 1781 EXPECT_EQ(1u, vresult.size()); 1782 EXPECT_NE(nullptr, vresult[0]); 1783 EXPECT_EQ(7, *vresult[0]); 1784 1785 std::unique_ptr<Base> result2 = mock.MakeUniqueBase(); 1786 EXPECT_EQ(d, result2.get()); 1787} 1788 1789TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) { 1790 testing::MockFunction<void()> mock_function; 1791 MockClass mock; 1792 std::unique_ptr<int> i(new int(19)); 1793 EXPECT_CALL(mock_function, Call()); 1794 EXPECT_CALL(mock, MakeUnique()) 1795 .WillOnce(DoAll(InvokeWithoutArgs(&mock_function, 1796 &testing::MockFunction<void()>::Call), 1797 Return(ByMove(std::move(i))))); 1798 1799 std::unique_ptr<int> result1 = mock.MakeUnique(); 1800 EXPECT_EQ(19, *result1); 1801} 1802 1803TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) { 1804 MockClass mock; 1805 1806 // Check default value 1807 DefaultValue<std::unique_ptr<int>>::SetFactory( 1808 [] { return std::make_unique<int>(42); }); 1809 EXPECT_EQ(42, *mock.MakeUnique()); 1810 1811 EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource)); 1812 EXPECT_CALL(mock, MakeVectorUnique()) 1813 .WillRepeatedly(Invoke(VectorUniquePtrSource)); 1814 std::unique_ptr<int> result1 = mock.MakeUnique(); 1815 EXPECT_EQ(19, *result1); 1816 std::unique_ptr<int> result2 = mock.MakeUnique(); 1817 EXPECT_EQ(19, *result2); 1818 EXPECT_NE(result1, result2); 1819 1820 std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique(); 1821 EXPECT_EQ(1u, vresult.size()); 1822 EXPECT_NE(nullptr, vresult[0]); 1823 EXPECT_EQ(7, *vresult[0]); 1824} 1825 1826TEST(MockMethodTest, CanTakeMoveOnlyValue) { 1827 MockClass mock; 1828 auto make = [](int i) { return std::make_unique<int>(i); }; 1829 1830 EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) { 1831 return *i; 1832 }); 1833 // DoAll() does not compile, since it would move from its arguments twice. 1834 // EXPECT_CALL(mock, TakeUnique(_, _)) 1835 // .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}), 1836 // Return(1))); 1837 EXPECT_CALL(mock, TakeUnique(testing::Pointee(7))) 1838 .WillOnce(Return(-7)) 1839 .RetiresOnSaturation(); 1840 EXPECT_CALL(mock, TakeUnique(testing::IsNull())) 1841 .WillOnce(Return(-1)) 1842 .RetiresOnSaturation(); 1843 1844 EXPECT_EQ(5, mock.TakeUnique(make(5))); 1845 EXPECT_EQ(-7, mock.TakeUnique(make(7))); 1846 EXPECT_EQ(7, mock.TakeUnique(make(7))); 1847 EXPECT_EQ(7, mock.TakeUnique(make(7))); 1848 EXPECT_EQ(-1, mock.TakeUnique({})); 1849 1850 // Some arguments are moved, some passed by reference. 1851 auto lvalue = make(6); 1852 EXPECT_CALL(mock, TakeUnique(_, _)) 1853 .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) { 1854 return *i * *j; 1855 }); 1856 EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7))); 1857 1858 // The unique_ptr can be saved by the action. 1859 std::unique_ptr<int> saved; 1860 EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) { 1861 saved = std::move(i); 1862 return 0; 1863 }); 1864 EXPECT_EQ(0, mock.TakeUnique(make(42))); 1865 EXPECT_EQ(42, *saved); 1866} 1867 1868// It should be possible to use callables with an &&-qualified call operator 1869// with WillOnce, since they will be called only once. This allows actions to 1870// contain and manipulate move-only types. 1871TEST(MockMethodTest, ActionHasRvalueRefQualifiedCallOperator) { 1872 struct Return17 { 1873 int operator()() && { return 17; } 1874 }; 1875 1876 // Action is directly compatible with mocked function type. 1877 { 1878 MockFunction<int()> mock; 1879 EXPECT_CALL(mock, Call).WillOnce(Return17()); 1880 1881 EXPECT_EQ(17, mock.AsStdFunction()()); 1882 } 1883 1884 // Action doesn't want mocked function arguments. 1885 { 1886 MockFunction<int(int)> mock; 1887 EXPECT_CALL(mock, Call).WillOnce(Return17()); 1888 1889 EXPECT_EQ(17, mock.AsStdFunction()(0)); 1890 } 1891} 1892 1893// Edge case: if an action has both a const-qualified and an &&-qualified call 1894// operator, there should be no "ambiguous call" errors. The &&-qualified 1895// operator should be used by WillOnce (since it doesn't need to retain the 1896// action beyond one call), and the const-qualified one by WillRepeatedly. 1897TEST(MockMethodTest, ActionHasMultipleCallOperators) { 1898 struct ReturnInt { 1899 int operator()() && { return 17; } 1900 int operator()() const& { return 19; } 1901 }; 1902 1903 // Directly compatible with mocked function type. 1904 { 1905 MockFunction<int()> mock; 1906 EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt()); 1907 1908 EXPECT_EQ(17, mock.AsStdFunction()()); 1909 EXPECT_EQ(19, mock.AsStdFunction()()); 1910 EXPECT_EQ(19, mock.AsStdFunction()()); 1911 } 1912 1913 // Ignores function arguments. 1914 { 1915 MockFunction<int(int)> mock; 1916 EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt()); 1917 1918 EXPECT_EQ(17, mock.AsStdFunction()(0)); 1919 EXPECT_EQ(19, mock.AsStdFunction()(0)); 1920 EXPECT_EQ(19, mock.AsStdFunction()(0)); 1921 } 1922} 1923 1924// WillOnce should have no problem coping with a move-only action, whether it is 1925// &&-qualified or not. 1926TEST(MockMethodTest, MoveOnlyAction) { 1927 // &&-qualified 1928 { 1929 struct Return17 { 1930 Return17() = default; 1931 Return17(Return17&&) = default; 1932 1933 Return17(const Return17&) = delete; 1934 Return17 operator=(const Return17&) = delete; 1935 1936 int operator()() && { return 17; } 1937 }; 1938 1939 MockFunction<int()> mock; 1940 EXPECT_CALL(mock, Call).WillOnce(Return17()); 1941 EXPECT_EQ(17, mock.AsStdFunction()()); 1942 } 1943 1944 // Not &&-qualified 1945 { 1946 struct Return17 { 1947 Return17() = default; 1948 Return17(Return17&&) = default; 1949 1950 Return17(const Return17&) = delete; 1951 Return17 operator=(const Return17&) = delete; 1952 1953 int operator()() const { return 17; } 1954 }; 1955 1956 MockFunction<int()> mock; 1957 EXPECT_CALL(mock, Call).WillOnce(Return17()); 1958 EXPECT_EQ(17, mock.AsStdFunction()()); 1959 } 1960} 1961 1962// It should be possible to use an action that returns a value with a mock 1963// function that doesn't, both through WillOnce and WillRepeatedly. 1964TEST(MockMethodTest, ActionReturnsIgnoredValue) { 1965 struct ReturnInt { 1966 int operator()() const { return 0; } 1967 }; 1968 1969 MockFunction<void()> mock; 1970 EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt()); 1971 1972 mock.AsStdFunction()(); 1973 mock.AsStdFunction()(); 1974} 1975 1976// Despite the fanciness around move-only actions and so on, it should still be 1977// possible to hand an lvalue reference to a copyable action to WillOnce. 1978TEST(MockMethodTest, WillOnceCanAcceptLvalueReference) { 1979 MockFunction<int()> mock; 1980 1981 const auto action = [] { return 17; }; 1982 EXPECT_CALL(mock, Call).WillOnce(action); 1983 1984 EXPECT_EQ(17, mock.AsStdFunction()()); 1985} 1986 1987// A callable that doesn't use SFINAE to restrict its call operator's overload 1988// set, but is still picky about which arguments it will accept. 1989struct StaticAssertSingleArgument { 1990 template <typename... Args> 1991 static constexpr bool CheckArgs() { 1992 static_assert(sizeof...(Args) == 1, ""); 1993 return true; 1994 } 1995 1996 template <typename... Args, bool = CheckArgs<Args...>()> 1997 int operator()(Args...) const { 1998 return 17; 1999 } 2000}; 2001 2002// WillOnce and WillRepeatedly should both work fine with na��ve implementations 2003// of actions that don't use SFINAE to limit the overload set for their call 2004// operator. If they are compatible with the actual mocked signature, we 2005// shouldn't probe them with no arguments and trip a static_assert. 2006TEST(MockMethodTest, ActionSwallowsAllArguments) { 2007 MockFunction<int(int)> mock; 2008 EXPECT_CALL(mock, Call) 2009 .WillOnce(StaticAssertSingleArgument{}) 2010 .WillRepeatedly(StaticAssertSingleArgument{}); 2011 2012 EXPECT_EQ(17, mock.AsStdFunction()(0)); 2013 EXPECT_EQ(17, mock.AsStdFunction()(0)); 2014} 2015 2016struct ActionWithTemplatedConversionOperators { 2017 template <typename... Args> 2018 operator OnceAction<int(Args...)>() && { // NOLINT 2019 return [] { return 17; }; 2020 } 2021 2022 template <typename... Args> 2023 operator Action<int(Args...)>() const { // NOLINT 2024 return [] { return 19; }; 2025 } 2026}; 2027 2028// It should be fine to hand both WillOnce and WillRepeatedly a function that 2029// defines templated conversion operators to OnceAction and Action. WillOnce 2030// should prefer the OnceAction version. 2031TEST(MockMethodTest, ActionHasTemplatedConversionOperators) { 2032 MockFunction<int()> mock; 2033 EXPECT_CALL(mock, Call) 2034 .WillOnce(ActionWithTemplatedConversionOperators{}) 2035 .WillRepeatedly(ActionWithTemplatedConversionOperators{}); 2036 2037 EXPECT_EQ(17, mock.AsStdFunction()()); 2038 EXPECT_EQ(19, mock.AsStdFunction()()); 2039} 2040 2041// Tests for std::function based action. 2042 2043int Add(int val, int& ref, int* ptr) { // NOLINT 2044 int result = val + ref + *ptr; 2045 ref = 42; 2046 *ptr = 43; 2047 return result; 2048} 2049 2050int Deref(std::unique_ptr<int> ptr) { return *ptr; } 2051 2052struct Double { 2053 template <typename T> 2054 T operator()(T t) { 2055 return 2 * t; 2056 } 2057}; 2058 2059std::unique_ptr<int> UniqueInt(int i) { return std::make_unique<int>(i); } 2060 2061TEST(FunctorActionTest, ActionFromFunction) { 2062 Action<int(int, int&, int*)> a = &Add; 2063 int x = 1, y = 2, z = 3; 2064 EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z))); 2065 EXPECT_EQ(42, y); 2066 EXPECT_EQ(43, z); 2067 2068 Action<int(std::unique_ptr<int>)> a1 = &Deref; 2069 EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7)))); 2070} 2071 2072TEST(FunctorActionTest, ActionFromLambda) { 2073 Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; }; 2074 EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); 2075 EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5))); 2076 2077 std::unique_ptr<int> saved; 2078 Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) { 2079 saved = std::move(p); 2080 }; 2081 a2.Perform(std::make_tuple(UniqueInt(5))); 2082 EXPECT_EQ(5, *saved); 2083} 2084 2085TEST(FunctorActionTest, PolymorphicFunctor) { 2086 Action<int(int)> ai = Double(); 2087 EXPECT_EQ(2, ai.Perform(std::make_tuple(1))); 2088 Action<double(double)> ad = Double(); // Double? Double double! 2089 EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5))); 2090} 2091 2092TEST(FunctorActionTest, TypeConversion) { 2093 // Numeric promotions are allowed. 2094 const Action<bool(int)> a1 = [](int i) { return i > 1; }; 2095 const Action<int(bool)> a2 = Action<int(bool)>(a1); 2096 EXPECT_EQ(1, a1.Perform(std::make_tuple(42))); 2097 EXPECT_EQ(0, a2.Perform(std::make_tuple(42))); 2098 2099 // Implicit constructors are allowed. 2100 const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); }; 2101 const Action<int(const char*)> s2 = Action<int(const char*)>(s1); 2102 EXPECT_EQ(0, s2.Perform(std::make_tuple(""))); 2103 EXPECT_EQ(1, s2.Perform(std::make_tuple("hello"))); 2104 2105 // Also between the lambda and the action itself. 2106 const Action<bool(std::string)> x1 = [](Unused) { return 42; }; 2107 const Action<bool(std::string)> x2 = [] { return 42; }; 2108 EXPECT_TRUE(x1.Perform(std::make_tuple("hello"))); 2109 EXPECT_TRUE(x2.Perform(std::make_tuple("hello"))); 2110 2111 // Ensure decay occurs where required. 2112 std::function<int()> f = [] { return 7; }; 2113 Action<int(int)> d = f; 2114 f = nullptr; 2115 EXPECT_EQ(7, d.Perform(std::make_tuple(1))); 2116 2117 // Ensure creation of an empty action succeeds. 2118 Action<void(int)>(nullptr); 2119} 2120 2121TEST(FunctorActionTest, UnusedArguments) { 2122 // Verify that users can ignore uninteresting arguments. 2123 Action<int(int, double y, double z)> a = [](int i, Unused, Unused) { 2124 return 2 * i; 2125 }; 2126 std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44); 2127 EXPECT_EQ(6, a.Perform(dummy)); 2128} 2129 2130// Test that basic built-in actions work with move-only arguments. 2131TEST(MoveOnlyArgumentsTest, ReturningActions) { 2132 Action<int(std::unique_ptr<int>)> a = Return(1); 2133 EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr))); 2134 2135 a = testing::WithoutArgs([]() { return 7; }); 2136 EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr))); 2137 2138 Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3); 2139 int x = 0; 2140 a2.Perform(std::make_tuple(nullptr, &x)); 2141 EXPECT_EQ(x, 3); 2142} 2143 2144ACTION(ReturnArity) { return std::tuple_size<args_type>::value; } 2145 2146TEST(ActionMacro, LargeArity) { 2147 EXPECT_EQ( 2148 1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0))); 2149 EXPECT_EQ( 2150 10, 2151 testing::Action<int(int, int, int, int, int, int, int, int, int, int)>( 2152 ReturnArity()) 2153 .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9))); 2154 EXPECT_EQ( 2155 20, 2156 testing::Action<int(int, int, int, int, int, int, int, int, int, int, int, 2157 int, int, int, int, int, int, int, int, int)>( 2158 ReturnArity()) 2159 .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 2160 14, 15, 16, 17, 18, 19))); 2161} 2162 2163} // namespace 2164} // namespace testing 2165 2166#if defined(_MSC_VER) && (_MSC_VER == 1900) 2167GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800 2168#endif 2169GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4503 2170