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