gmock-internal-utils_test.cc 26 KB

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