gmock-internal-utils_test.cc 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. // Google Mock - a framework for writing C++ mock classes.
  30. //
  31. // This file tests the internal utilities.
  32. #include "gmock/internal/gmock-internal-utils.h"
  33. #include <stdlib.h>
  34. #include <map>
  35. #include <memory>
  36. #include <string>
  37. #include <sstream>
  38. #include <vector>
  39. #include "gmock/gmock.h"
  40. #include "gmock/internal/gmock-port.h"
  41. #include "gtest/gtest.h"
  42. #include "gtest/gtest-spi.h"
  43. // Indicates that this translation unit is part of Google Test's
  44. // implementation. It must come before gtest-internal-inl.h is
  45. // included, or there will be a compiler error. This trick is to
  46. // prevent a user from accidentally including gtest-internal-inl.h in
  47. // their code.
  48. #define GTEST_IMPLEMENTATION_ 1
  49. #include "src/gtest-internal-inl.h"
  50. #undef GTEST_IMPLEMENTATION_
  51. #if GTEST_OS_CYGWIN
  52. # include <sys/types.h> // For ssize_t. NOLINT
  53. #endif
  54. class ProtocolMessage;
  55. namespace proto2 {
  56. class Message;
  57. } // namespace proto2
  58. namespace testing {
  59. namespace internal {
  60. namespace {
  61. TEST(JoinAsTupleTest, JoinsEmptyTuple) {
  62. EXPECT_EQ("", JoinAsTuple(Strings()));
  63. }
  64. TEST(JoinAsTupleTest, JoinsOneTuple) {
  65. const char* fields[] = {"1"};
  66. EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
  67. }
  68. TEST(JoinAsTupleTest, JoinsTwoTuple) {
  69. const char* fields[] = {"1", "a"};
  70. EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
  71. }
  72. TEST(JoinAsTupleTest, JoinsTenTuple) {
  73. const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
  74. EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
  75. JoinAsTuple(Strings(fields, fields + 10)));
  76. }
  77. TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) {
  78. EXPECT_EQ("", ConvertIdentifierNameToWords(""));
  79. EXPECT_EQ("", ConvertIdentifierNameToWords("_"));
  80. EXPECT_EQ("", ConvertIdentifierNameToWords("__"));
  81. }
  82. TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsDigits) {
  83. EXPECT_EQ("1", ConvertIdentifierNameToWords("_1"));
  84. EXPECT_EQ("2", ConvertIdentifierNameToWords("2_"));
  85. EXPECT_EQ("34", ConvertIdentifierNameToWords("_34_"));
  86. EXPECT_EQ("34 56", ConvertIdentifierNameToWords("_34_56"));
  87. }
  88. TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsCamelCaseWords) {
  89. EXPECT_EQ("a big word", ConvertIdentifierNameToWords("ABigWord"));
  90. EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("FooBar"));
  91. EXPECT_EQ("foo", ConvertIdentifierNameToWords("Foo_"));
  92. EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_Foo_Bar_"));
  93. EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_Foo__And_Bar"));
  94. }
  95. TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContains_SeparatedWords) {
  96. EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("foo_bar"));
  97. EXPECT_EQ("foo", ConvertIdentifierNameToWords("_foo_"));
  98. EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_foo_bar_"));
  99. EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_foo__and_bar"));
  100. }
  101. TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
  102. EXPECT_EQ("foo bar 123", ConvertIdentifierNameToWords("Foo_bar123"));
  103. EXPECT_EQ("chapter 11 section 1",
  104. ConvertIdentifierNameToWords("_Chapter11Section_1_"));
  105. }
  106. TEST(PointeeOfTest, WorksForSmartPointers) {
  107. CompileAssertTypesEqual<const char,
  108. PointeeOf<internal::linked_ptr<const char> >::type>();
  109. #if GTEST_HAS_STD_UNIQUE_PTR_
  110. CompileAssertTypesEqual<int, PointeeOf<std::unique_ptr<int> >::type>();
  111. #endif // GTEST_HAS_STD_UNIQUE_PTR_
  112. #if GTEST_HAS_STD_SHARED_PTR_
  113. CompileAssertTypesEqual<std::string,
  114. PointeeOf<std::shared_ptr<std::string> >::type>();
  115. #endif // GTEST_HAS_STD_SHARED_PTR_
  116. }
  117. TEST(PointeeOfTest, WorksForRawPointers) {
  118. CompileAssertTypesEqual<int, PointeeOf<int*>::type>();
  119. CompileAssertTypesEqual<const char, PointeeOf<const char*>::type>();
  120. CompileAssertTypesEqual<void, PointeeOf<void*>::type>();
  121. }
  122. TEST(GetRawPointerTest, WorksForSmartPointers) {
  123. #if GTEST_HAS_STD_UNIQUE_PTR_
  124. const char* const raw_p1 = new const char('a'); // NOLINT
  125. const std::unique_ptr<const char> p1(raw_p1);
  126. EXPECT_EQ(raw_p1, GetRawPointer(p1));
  127. #endif // GTEST_HAS_STD_UNIQUE_PTR_
  128. #if GTEST_HAS_STD_SHARED_PTR_
  129. double* const raw_p2 = new double(2.5); // NOLINT
  130. const std::shared_ptr<double> p2(raw_p2);
  131. EXPECT_EQ(raw_p2, GetRawPointer(p2));
  132. #endif // GTEST_HAS_STD_SHARED_PTR_
  133. const char* const raw_p4 = new const char('a'); // NOLINT
  134. const internal::linked_ptr<const char> p4(raw_p4);
  135. EXPECT_EQ(raw_p4, GetRawPointer(p4));
  136. }
  137. TEST(GetRawPointerTest, WorksForRawPointers) {
  138. int* p = NULL;
  139. // Don't use EXPECT_EQ as no NULL-testing magic on Symbian.
  140. EXPECT_TRUE(NULL == GetRawPointer(p));
  141. int n = 1;
  142. EXPECT_EQ(&n, GetRawPointer(&n));
  143. }
  144. // Tests KindOf<T>.
  145. class Base {};
  146. class Derived : public Base {};
  147. TEST(KindOfTest, Bool) {
  148. EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool)); // NOLINT
  149. }
  150. TEST(KindOfTest, Integer) {
  151. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char)); // NOLINT
  152. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char)); // NOLINT
  153. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char)); // NOLINT
  154. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short)); // NOLINT
  155. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short)); // NOLINT
  156. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int)); // NOLINT
  157. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); // NOLINT
  158. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); // NOLINT
  159. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); // NOLINT
  160. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); // NOLINT
  161. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(Int64)); // NOLINT
  162. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(UInt64)); // NOLINT
  163. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT
  164. #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN
  165. // ssize_t is not defined on Windows and possibly some other OSes.
  166. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); // NOLINT
  167. #endif
  168. }
  169. TEST(KindOfTest, FloatingPoint) {
  170. EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float)); // NOLINT
  171. EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double)); // NOLINT
  172. EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double)); // NOLINT
  173. }
  174. TEST(KindOfTest, Other) {
  175. EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*)); // NOLINT
  176. EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**)); // NOLINT
  177. EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base)); // NOLINT
  178. }
  179. // Tests LosslessArithmeticConvertible<T, U>.
  180. TEST(LosslessArithmeticConvertibleTest, BoolToBool) {
  181. EXPECT_TRUE((LosslessArithmeticConvertible<bool, bool>::value));
  182. }
  183. TEST(LosslessArithmeticConvertibleTest, BoolToInteger) {
  184. EXPECT_TRUE((LosslessArithmeticConvertible<bool, char>::value));
  185. EXPECT_TRUE((LosslessArithmeticConvertible<bool, int>::value));
  186. EXPECT_TRUE(
  187. (LosslessArithmeticConvertible<bool, unsigned long>::value)); // NOLINT
  188. }
  189. TEST(LosslessArithmeticConvertibleTest, BoolToFloatingPoint) {
  190. EXPECT_TRUE((LosslessArithmeticConvertible<bool, float>::value));
  191. EXPECT_TRUE((LosslessArithmeticConvertible<bool, double>::value));
  192. }
  193. TEST(LosslessArithmeticConvertibleTest, IntegerToBool) {
  194. EXPECT_FALSE((LosslessArithmeticConvertible<unsigned char, bool>::value));
  195. EXPECT_FALSE((LosslessArithmeticConvertible<int, bool>::value));
  196. }
  197. TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
  198. // Unsigned => larger signed is fine.
  199. EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));
  200. // Unsigned => larger unsigned is fine.
  201. EXPECT_TRUE(
  202. (LosslessArithmeticConvertible<unsigned short, UInt64>::value)); // NOLINT
  203. // Signed => unsigned is not fine.
  204. EXPECT_FALSE((LosslessArithmeticConvertible<short, UInt64>::value)); // NOLINT
  205. EXPECT_FALSE((LosslessArithmeticConvertible<
  206. signed char, unsigned int>::value)); // NOLINT
  207. // Same size and same signedness: fine too.
  208. EXPECT_TRUE((LosslessArithmeticConvertible<
  209. unsigned char, unsigned char>::value));
  210. EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value));
  211. EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value));
  212. EXPECT_TRUE((LosslessArithmeticConvertible<
  213. unsigned long, unsigned long>::value)); // NOLINT
  214. // Same size, different signedness: not fine.
  215. EXPECT_FALSE((LosslessArithmeticConvertible<
  216. unsigned char, signed char>::value));
  217. EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));
  218. EXPECT_FALSE((LosslessArithmeticConvertible<UInt64, Int64>::value));
  219. // Larger size => smaller size is not fine.
  220. EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value)); // NOLINT
  221. EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value));
  222. EXPECT_FALSE((LosslessArithmeticConvertible<Int64, unsigned int>::value));
  223. }
  224. TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
  225. // Integers cannot be losslessly converted to floating-points, as
  226. // the format of the latter is implementation-defined.
  227. EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value));
  228. EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value));
  229. EXPECT_FALSE((LosslessArithmeticConvertible<
  230. short, long double>::value)); // NOLINT
  231. }
  232. TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
  233. EXPECT_FALSE((LosslessArithmeticConvertible<float, bool>::value));
  234. EXPECT_FALSE((LosslessArithmeticConvertible<double, bool>::value));
  235. }
  236. TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) {
  237. EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value)); // NOLINT
  238. EXPECT_FALSE((LosslessArithmeticConvertible<double, Int64>::value));
  239. EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value));
  240. }
  241. TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) {
  242. // Smaller size => larger size is fine.
  243. EXPECT_TRUE((LosslessArithmeticConvertible<float, double>::value));
  244. EXPECT_TRUE((LosslessArithmeticConvertible<float, long double>::value));
  245. EXPECT_TRUE((LosslessArithmeticConvertible<double, long double>::value));
  246. // Same size: fine.
  247. EXPECT_TRUE((LosslessArithmeticConvertible<float, float>::value));
  248. EXPECT_TRUE((LosslessArithmeticConvertible<double, double>::value));
  249. // Larger size => smaller size is not fine.
  250. EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value));
  251. GTEST_INTENTIONAL_CONST_COND_PUSH_()
  252. if (sizeof(double) == sizeof(long double)) { // NOLINT
  253. GTEST_INTENTIONAL_CONST_COND_POP_()
  254. // In some implementations (e.g. MSVC), double and long double
  255. // have the same size.
  256. EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value));
  257. } else {
  258. EXPECT_FALSE((LosslessArithmeticConvertible<long double, double>::value));
  259. }
  260. }
  261. // Tests the TupleMatches() template function.
  262. TEST(TupleMatchesTest, WorksForSize0) {
  263. tuple<> matchers;
  264. tuple<> values;
  265. EXPECT_TRUE(TupleMatches(matchers, values));
  266. }
  267. TEST(TupleMatchesTest, WorksForSize1) {
  268. tuple<Matcher<int> > matchers(Eq(1));
  269. tuple<int> values1(1),
  270. values2(2);
  271. EXPECT_TRUE(TupleMatches(matchers, values1));
  272. EXPECT_FALSE(TupleMatches(matchers, values2));
  273. }
  274. TEST(TupleMatchesTest, WorksForSize2) {
  275. tuple<Matcher<int>, Matcher<char> > matchers(Eq(1), Eq('a'));
  276. tuple<int, char> values1(1, 'a'),
  277. values2(1, 'b'),
  278. values3(2, 'a'),
  279. values4(2, 'b');
  280. EXPECT_TRUE(TupleMatches(matchers, values1));
  281. EXPECT_FALSE(TupleMatches(matchers, values2));
  282. EXPECT_FALSE(TupleMatches(matchers, values3));
  283. EXPECT_FALSE(TupleMatches(matchers, values4));
  284. }
  285. TEST(TupleMatchesTest, WorksForSize5) {
  286. tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>, // NOLINT
  287. Matcher<std::string> >
  288. matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi"));
  289. tuple<int, char, bool, long, std::string> // NOLINT
  290. values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"),
  291. values3(2, 'a', true, 2L, "hi");
  292. EXPECT_TRUE(TupleMatches(matchers, values1));
  293. EXPECT_FALSE(TupleMatches(matchers, values2));
  294. EXPECT_FALSE(TupleMatches(matchers, values3));
  295. }
  296. // Tests that Assert(true, ...) succeeds.
  297. TEST(AssertTest, SucceedsOnTrue) {
  298. Assert(true, __FILE__, __LINE__, "This should succeed.");
  299. Assert(true, __FILE__, __LINE__); // This should succeed too.
  300. }
  301. // Tests that Assert(false, ...) generates a fatal failure.
  302. TEST(AssertTest, FailsFatallyOnFalse) {
  303. EXPECT_DEATH_IF_SUPPORTED({
  304. Assert(false, __FILE__, __LINE__, "This should fail.");
  305. }, "");
  306. EXPECT_DEATH_IF_SUPPORTED({
  307. Assert(false, __FILE__, __LINE__);
  308. }, "");
  309. }
  310. // Tests that Expect(true, ...) succeeds.
  311. TEST(ExpectTest, SucceedsOnTrue) {
  312. Expect(true, __FILE__, __LINE__, "This should succeed.");
  313. Expect(true, __FILE__, __LINE__); // This should succeed too.
  314. }
  315. // Tests that Expect(false, ...) generates a non-fatal failure.
  316. TEST(ExpectTest, FailsNonfatallyOnFalse) {
  317. EXPECT_NONFATAL_FAILURE({ // NOLINT
  318. Expect(false, __FILE__, __LINE__, "This should fail.");
  319. }, "This should fail");
  320. EXPECT_NONFATAL_FAILURE({ // NOLINT
  321. Expect(false, __FILE__, __LINE__);
  322. }, "Expectation failed");
  323. }
  324. // Tests LogIsVisible().
  325. class LogIsVisibleTest : public ::testing::Test {
  326. protected:
  327. virtual void SetUp() {
  328. original_verbose_ = GMOCK_FLAG(verbose);
  329. }
  330. virtual void TearDown() { GMOCK_FLAG(verbose) = original_verbose_; }
  331. std::string original_verbose_;
  332. };
  333. TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) {
  334. GMOCK_FLAG(verbose) = kInfoVerbosity;
  335. EXPECT_TRUE(LogIsVisible(kInfo));
  336. EXPECT_TRUE(LogIsVisible(kWarning));
  337. }
  338. TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) {
  339. GMOCK_FLAG(verbose) = kErrorVerbosity;
  340. EXPECT_FALSE(LogIsVisible(kInfo));
  341. EXPECT_FALSE(LogIsVisible(kWarning));
  342. }
  343. TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) {
  344. GMOCK_FLAG(verbose) = kWarningVerbosity;
  345. EXPECT_FALSE(LogIsVisible(kInfo));
  346. EXPECT_TRUE(LogIsVisible(kWarning));
  347. }
  348. #if GTEST_HAS_STREAM_REDIRECTION
  349. // Tests the Log() function.
  350. // Verifies that Log() behaves correctly for the given verbosity level
  351. // and log severity.
  352. void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity,
  353. bool should_print) {
  354. const std::string old_flag = GMOCK_FLAG(verbose);
  355. GMOCK_FLAG(verbose) = verbosity;
  356. CaptureStdout();
  357. Log(severity, "Test log.\n", 0);
  358. if (should_print) {
  359. EXPECT_THAT(GetCapturedStdout().c_str(),
  360. ContainsRegex(
  361. severity == kWarning ?
  362. "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" :
  363. "^\nTest log\\.\nStack trace:\n"));
  364. } else {
  365. EXPECT_STREQ("", GetCapturedStdout().c_str());
  366. }
  367. GMOCK_FLAG(verbose) = old_flag;
  368. }
  369. // Tests that when the stack_frames_to_skip parameter is negative,
  370. // Log() doesn't include the stack trace in the output.
  371. TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) {
  372. const std::string saved_flag = GMOCK_FLAG(verbose);
  373. GMOCK_FLAG(verbose) = kInfoVerbosity;
  374. CaptureStdout();
  375. Log(kInfo, "Test log.\n", -1);
  376. EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str());
  377. GMOCK_FLAG(verbose) = saved_flag;
  378. }
  379. struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface {
  380. virtual std::string CurrentStackTrace(int max_depth, int skip_count) {
  381. return (testing::Message() << max_depth << "::" << skip_count << "\n")
  382. .GetString();
  383. }
  384. virtual void UponLeavingGTest() {}
  385. };
  386. // Tests that in opt mode, a positive stack_frames_to_skip argument is
  387. // treated as 0.
  388. TEST(LogTest, NoSkippingStackFrameInOptMode) {
  389. MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter;
  390. GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter);
  391. CaptureStdout();
  392. Log(kWarning, "Test log.\n", 100);
  393. const std::string log = GetCapturedStdout();
  394. std::string expected_trace =
  395. (testing::Message() << GTEST_FLAG(stack_trace_depth) << "::").GetString();
  396. std::string expected_message =
  397. "\nGMOCK WARNING:\n"
  398. "Test log.\n"
  399. "Stack trace:\n" +
  400. expected_trace;
  401. EXPECT_THAT(log, HasSubstr(expected_message));
  402. int skip_count = atoi(log.substr(expected_message.size()).c_str());
  403. # if defined(NDEBUG)
  404. // In opt mode, no stack frame should be skipped.
  405. const int expected_skip_count = 0;
  406. # else
  407. // In dbg mode, the stack frames should be skipped.
  408. const int expected_skip_count = 100;
  409. # endif
  410. // Note that each inner implementation layer will +1 the number to remove
  411. // itself from the trace. This means that the value is a little higher than
  412. // expected, but close enough.
  413. EXPECT_THAT(skip_count,
  414. AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10)));
  415. // Restores the default OS stack trace getter.
  416. GetUnitTestImpl()->set_os_stack_trace_getter(NULL);
  417. }
  418. // Tests that all logs are printed when the value of the
  419. // --gmock_verbose flag is "info".
  420. TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) {
  421. TestLogWithSeverity(kInfoVerbosity, kInfo, true);
  422. TestLogWithSeverity(kInfoVerbosity, kWarning, true);
  423. }
  424. // Tests that only warnings are printed when the value of the
  425. // --gmock_verbose flag is "warning".
  426. TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) {
  427. TestLogWithSeverity(kWarningVerbosity, kInfo, false);
  428. TestLogWithSeverity(kWarningVerbosity, kWarning, true);
  429. }
  430. // Tests that no logs are printed when the value of the
  431. // --gmock_verbose flag is "error".
  432. TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) {
  433. TestLogWithSeverity(kErrorVerbosity, kInfo, false);
  434. TestLogWithSeverity(kErrorVerbosity, kWarning, false);
  435. }
  436. // Tests that only warnings are printed when the value of the
  437. // --gmock_verbose flag is invalid.
  438. TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) {
  439. TestLogWithSeverity("invalid", kInfo, false);
  440. TestLogWithSeverity("invalid", kWarning, true);
  441. }
  442. #endif // GTEST_HAS_STREAM_REDIRECTION
  443. TEST(TypeTraitsTest, true_type) {
  444. EXPECT_TRUE(true_type::value);
  445. }
  446. TEST(TypeTraitsTest, false_type) {
  447. EXPECT_FALSE(false_type::value);
  448. }
  449. TEST(TypeTraitsTest, is_reference) {
  450. EXPECT_FALSE(is_reference<int>::value);
  451. EXPECT_FALSE(is_reference<char*>::value);
  452. EXPECT_TRUE(is_reference<const int&>::value);
  453. }
  454. TEST(TypeTraitsTest, is_pointer) {
  455. EXPECT_FALSE(is_pointer<int>::value);
  456. EXPECT_FALSE(is_pointer<char&>::value);
  457. EXPECT_TRUE(is_pointer<const int*>::value);
  458. }
  459. TEST(TypeTraitsTest, type_equals) {
  460. EXPECT_FALSE((type_equals<int, const int>::value));
  461. EXPECT_FALSE((type_equals<int, int&>::value));
  462. EXPECT_FALSE((type_equals<int, double>::value));
  463. EXPECT_TRUE((type_equals<char, char>::value));
  464. }
  465. TEST(TypeTraitsTest, remove_reference) {
  466. EXPECT_TRUE((type_equals<char, remove_reference<char&>::type>::value));
  467. EXPECT_TRUE((type_equals<const int,
  468. remove_reference<const int&>::type>::value));
  469. EXPECT_TRUE((type_equals<int, remove_reference<int>::type>::value));
  470. EXPECT_TRUE((type_equals<double*, remove_reference<double*>::type>::value));
  471. }
  472. #if GTEST_HAS_STREAM_REDIRECTION
  473. // Verifies that Log() behaves correctly for the given verbosity level
  474. // and log severity.
  475. std::string GrabOutput(void(*logger)(), const char* verbosity) {
  476. const std::string saved_flag = GMOCK_FLAG(verbose);
  477. GMOCK_FLAG(verbose) = verbosity;
  478. CaptureStdout();
  479. logger();
  480. GMOCK_FLAG(verbose) = saved_flag;
  481. return GetCapturedStdout();
  482. }
  483. class DummyMock {
  484. public:
  485. MOCK_METHOD0(TestMethod, void());
  486. MOCK_METHOD1(TestMethodArg, void(int dummy));
  487. };
  488. void ExpectCallLogger() {
  489. DummyMock mock;
  490. EXPECT_CALL(mock, TestMethod());
  491. mock.TestMethod();
  492. };
  493. // Verifies that EXPECT_CALL logs if the --gmock_verbose flag is set to "info".
  494. TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) {
  495. EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)),
  496. HasSubstr("EXPECT_CALL(mock, TestMethod())"));
  497. }
  498. // Verifies that EXPECT_CALL doesn't log
  499. // if the --gmock_verbose flag is set to "warning".
  500. TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) {
  501. EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kWarningVerbosity).c_str());
  502. }
  503. // Verifies that EXPECT_CALL doesn't log
  504. // if the --gmock_verbose flag is set to "error".
  505. TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) {
  506. EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str());
  507. }
  508. void OnCallLogger() {
  509. DummyMock mock;
  510. ON_CALL(mock, TestMethod());
  511. };
  512. // Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info".
  513. TEST(OnCallTest, LogsWhenVerbosityIsInfo) {
  514. EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)),
  515. HasSubstr("ON_CALL(mock, TestMethod())"));
  516. }
  517. // Verifies that ON_CALL doesn't log
  518. // if the --gmock_verbose flag is set to "warning".
  519. TEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) {
  520. EXPECT_STREQ("", GrabOutput(OnCallLogger, kWarningVerbosity).c_str());
  521. }
  522. // Verifies that ON_CALL doesn't log if
  523. // the --gmock_verbose flag is set to "error".
  524. TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) {
  525. EXPECT_STREQ("", GrabOutput(OnCallLogger, kErrorVerbosity).c_str());
  526. }
  527. void OnCallAnyArgumentLogger() {
  528. DummyMock mock;
  529. ON_CALL(mock, TestMethodArg(_));
  530. }
  531. // Verifies that ON_CALL prints provided _ argument.
  532. TEST(OnCallTest, LogsAnythingArgument) {
  533. EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)),
  534. HasSubstr("ON_CALL(mock, TestMethodArg(_)"));
  535. }
  536. #endif // GTEST_HAS_STREAM_REDIRECTION
  537. // Tests StlContainerView.
  538. TEST(StlContainerViewTest, WorksForStlContainer) {
  539. StaticAssertTypeEq<std::vector<int>,
  540. StlContainerView<std::vector<int> >::type>();
  541. StaticAssertTypeEq<const std::vector<double>&,
  542. StlContainerView<std::vector<double> >::const_reference>();
  543. typedef std::vector<char> Chars;
  544. Chars v1;
  545. const Chars& v2(StlContainerView<Chars>::ConstReference(v1));
  546. EXPECT_EQ(&v1, &v2);
  547. v1.push_back('a');
  548. Chars v3 = StlContainerView<Chars>::Copy(v1);
  549. EXPECT_THAT(v3, Eq(v3));
  550. }
  551. TEST(StlContainerViewTest, WorksForStaticNativeArray) {
  552. StaticAssertTypeEq<NativeArray<int>,
  553. StlContainerView<int[3]>::type>();
  554. StaticAssertTypeEq<NativeArray<double>,
  555. StlContainerView<const double[4]>::type>();
  556. StaticAssertTypeEq<NativeArray<char[3]>,
  557. StlContainerView<const char[2][3]>::type>();
  558. StaticAssertTypeEq<const NativeArray<int>,
  559. StlContainerView<int[2]>::const_reference>();
  560. int a1[3] = { 0, 1, 2 };
  561. NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1);
  562. EXPECT_EQ(3U, a2.size());
  563. EXPECT_EQ(a1, a2.begin());
  564. const NativeArray<int> a3 = StlContainerView<int[3]>::Copy(a1);
  565. ASSERT_EQ(3U, a3.size());
  566. EXPECT_EQ(0, a3.begin()[0]);
  567. EXPECT_EQ(1, a3.begin()[1]);
  568. EXPECT_EQ(2, a3.begin()[2]);
  569. // Makes sure a1 and a3 aren't aliases.
  570. a1[0] = 3;
  571. EXPECT_EQ(0, a3.begin()[0]);
  572. }
  573. TEST(StlContainerViewTest, WorksForDynamicNativeArray) {
  574. StaticAssertTypeEq<NativeArray<int>,
  575. StlContainerView<tuple<const int*, size_t> >::type>();
  576. StaticAssertTypeEq<NativeArray<double>,
  577. StlContainerView<tuple<linked_ptr<double>, int> >::type>();
  578. StaticAssertTypeEq<const NativeArray<int>,
  579. StlContainerView<tuple<const int*, int> >::const_reference>();
  580. int a1[3] = { 0, 1, 2 };
  581. const int* const p1 = a1;
  582. NativeArray<int> a2 = StlContainerView<tuple<const int*, int> >::
  583. ConstReference(make_tuple(p1, 3));
  584. EXPECT_EQ(3U, a2.size());
  585. EXPECT_EQ(a1, a2.begin());
  586. const NativeArray<int> a3 = StlContainerView<tuple<int*, size_t> >::
  587. Copy(make_tuple(static_cast<int*>(a1), 3));
  588. ASSERT_EQ(3U, a3.size());
  589. EXPECT_EQ(0, a3.begin()[0]);
  590. EXPECT_EQ(1, a3.begin()[1]);
  591. EXPECT_EQ(2, a3.begin()[2]);
  592. // Makes sure a1 and a3 aren't aliases.
  593. a1[0] = 3;
  594. EXPECT_EQ(0, a3.begin()[0]);
  595. }
  596. } // namespace
  597. } // namespace internal
  598. } // namespace testing