gmock-internal-utils_test.cc 27 KB

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