• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 // Google Mock - a framework for writing C++ mock classes.
31 //
32 // This file tests the internal utilities.
33 
34 #include "gmock/internal/gmock-internal-utils.h"
35 
36 #include <stdlib.h>
37 
38 #include <cstdint>
39 #include <map>
40 #include <memory>
41 #include <sstream>
42 #include <string>
43 #include <vector>
44 
45 #include "gmock/gmock.h"
46 #include "gmock/internal/gmock-port.h"
47 #include "gtest/gtest-spi.h"
48 #include "gtest/gtest.h"
49 
50 // Indicates that this translation unit is part of Google Test's
51 // implementation.  It must come before gtest-internal-inl.h is
52 // included, or there will be a compiler error.  This trick is to
53 // prevent a user from accidentally including gtest-internal-inl.h in
54 // their code.
55 #define GTEST_IMPLEMENTATION_ 1
56 #include "src/gtest-internal-inl.h"
57 #undef GTEST_IMPLEMENTATION_
58 
59 #if GTEST_OS_CYGWIN
60 #include <sys/types.h>  // For ssize_t. NOLINT
61 #endif
62 
63 namespace proto2 {
64 class Message;
65 }  // namespace proto2
66 
67 namespace testing {
68 namespace internal {
69 
70 namespace {
71 
TEST(JoinAsKeyValueTupleTest,JoinsEmptyTuple)72 TEST(JoinAsKeyValueTupleTest, JoinsEmptyTuple) {
73   EXPECT_EQ("", JoinAsKeyValueTuple({}, Strings()));
74 }
75 
TEST(JoinAsKeyValueTupleTest,JoinsOneTuple)76 TEST(JoinAsKeyValueTupleTest, JoinsOneTuple) {
77   EXPECT_EQ("(a: 1)", JoinAsKeyValueTuple({"a"}, {"1"}));
78 }
79 
TEST(JoinAsKeyValueTupleTest,JoinsTwoTuple)80 TEST(JoinAsKeyValueTupleTest, JoinsTwoTuple) {
81   EXPECT_EQ("(a: 1, b: 2)", JoinAsKeyValueTuple({"a", "b"}, {"1", "2"}));
82 }
83 
TEST(JoinAsKeyValueTupleTest,JoinsTenTuple)84 TEST(JoinAsKeyValueTupleTest, JoinsTenTuple) {
85   EXPECT_EQ(
86       "(a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10)",
87       JoinAsKeyValueTuple({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"},
88                           {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}));
89 }
90 
TEST(ConvertIdentifierNameToWordsTest,WorksWhenNameContainsNoWord)91 TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) {
92   EXPECT_EQ("", ConvertIdentifierNameToWords(""));
93   EXPECT_EQ("", ConvertIdentifierNameToWords("_"));
94   EXPECT_EQ("", ConvertIdentifierNameToWords("__"));
95 }
96 
TEST(ConvertIdentifierNameToWordsTest,WorksWhenNameContainsDigits)97 TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsDigits) {
98   EXPECT_EQ("1", ConvertIdentifierNameToWords("_1"));
99   EXPECT_EQ("2", ConvertIdentifierNameToWords("2_"));
100   EXPECT_EQ("34", ConvertIdentifierNameToWords("_34_"));
101   EXPECT_EQ("34 56", ConvertIdentifierNameToWords("_34_56"));
102 }
103 
TEST(ConvertIdentifierNameToWordsTest,WorksWhenNameContainsCamelCaseWords)104 TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsCamelCaseWords) {
105   EXPECT_EQ("a big word", ConvertIdentifierNameToWords("ABigWord"));
106   EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("FooBar"));
107   EXPECT_EQ("foo", ConvertIdentifierNameToWords("Foo_"));
108   EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_Foo_Bar_"));
109   EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_Foo__And_Bar"));
110 }
111 
TEST(ConvertIdentifierNameToWordsTest,WorksWhenNameContains_SeparatedWords)112 TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContains_SeparatedWords) {
113   EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("foo_bar"));
114   EXPECT_EQ("foo", ConvertIdentifierNameToWords("_foo_"));
115   EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_foo_bar_"));
116   EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_foo__and_bar"));
117 }
118 
TEST(ConvertIdentifierNameToWordsTest,WorksWhenNameIsMixture)119 TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
120   EXPECT_EQ("foo bar 123", ConvertIdentifierNameToWords("Foo_bar123"));
121   EXPECT_EQ("chapter 11 section 1",
122             ConvertIdentifierNameToWords("_Chapter11Section_1_"));
123 }
124 
TEST(GetRawPointerTest,WorksForSmartPointers)125 TEST(GetRawPointerTest, WorksForSmartPointers) {
126   const char* const raw_p1 = new const char('a');  // NOLINT
127   const std::unique_ptr<const char> p1(raw_p1);
128   EXPECT_EQ(raw_p1, GetRawPointer(p1));
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 }
133 
TEST(GetRawPointerTest,WorksForRawPointers)134 TEST(GetRawPointerTest, WorksForRawPointers) {
135   int* p = nullptr;
136   EXPECT_TRUE(nullptr == GetRawPointer(p));
137   int n = 1;
138   EXPECT_EQ(&n, GetRawPointer(&n));
139 }
140 
TEST(GetRawPointerTest,WorksForStdReferenceWrapper)141 TEST(GetRawPointerTest, WorksForStdReferenceWrapper) {
142   int n = 1;
143   EXPECT_EQ(&n, GetRawPointer(std::ref(n)));
144   EXPECT_EQ(&n, GetRawPointer(std::cref(n)));
145 }
146 
147 // Tests KindOf<T>.
148 
149 class Base {};
150 class Derived : public Base {};
151 
TEST(KindOfTest,Bool)152 TEST(KindOfTest, Bool) {
153   EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool));  // NOLINT
154 }
155 
TEST(KindOfTest,Integer)156 TEST(KindOfTest, Integer) {
157   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char));                // NOLINT
158   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char));         // NOLINT
159   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char));       // NOLINT
160   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short));               // NOLINT
161   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short));      // NOLINT
162   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int));                 // NOLINT
163   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int));        // NOLINT
164   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long));                // NOLINT
165   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long));       // NOLINT
166   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long));           // NOLINT
167   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long));  // NOLINT
168   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t));             // NOLINT
169   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t));              // NOLINT
170 #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN
171   // ssize_t is not defined on Windows and possibly some other OSes.
172   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t));  // NOLINT
173 #endif
174 }
175 
TEST(KindOfTest,FloatingPoint)176 TEST(KindOfTest, FloatingPoint) {
177   EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float));        // NOLINT
178   EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double));       // NOLINT
179   EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double));  // NOLINT
180 }
181 
TEST(KindOfTest,Other)182 TEST(KindOfTest, Other) {
183   EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*));   // NOLINT
184   EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**));  // NOLINT
185   EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base));    // NOLINT
186 }
187 
188 // Tests LosslessArithmeticConvertible<T, U>.
189 
TEST(LosslessArithmeticConvertibleTest,BoolToBool)190 TEST(LosslessArithmeticConvertibleTest, BoolToBool) {
191   EXPECT_TRUE((LosslessArithmeticConvertible<bool, bool>::value));
192 }
193 
TEST(LosslessArithmeticConvertibleTest,BoolToInteger)194 TEST(LosslessArithmeticConvertibleTest, BoolToInteger) {
195   EXPECT_TRUE((LosslessArithmeticConvertible<bool, char>::value));
196   EXPECT_TRUE((LosslessArithmeticConvertible<bool, int>::value));
197   EXPECT_TRUE(
198       (LosslessArithmeticConvertible<bool, unsigned long>::value));  // NOLINT
199 }
200 
TEST(LosslessArithmeticConvertibleTest,BoolToFloatingPoint)201 TEST(LosslessArithmeticConvertibleTest, BoolToFloatingPoint) {
202   EXPECT_TRUE((LosslessArithmeticConvertible<bool, float>::value));
203   EXPECT_TRUE((LosslessArithmeticConvertible<bool, double>::value));
204 }
205 
TEST(LosslessArithmeticConvertibleTest,IntegerToBool)206 TEST(LosslessArithmeticConvertibleTest, IntegerToBool) {
207   EXPECT_FALSE((LosslessArithmeticConvertible<unsigned char, bool>::value));
208   EXPECT_FALSE((LosslessArithmeticConvertible<int, bool>::value));
209 }
210 
TEST(LosslessArithmeticConvertibleTest,IntegerToInteger)211 TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
212   // Unsigned => larger signed is fine.
213   EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));
214 
215   // Unsigned => larger unsigned is fine.
216   EXPECT_TRUE((LosslessArithmeticConvertible<unsigned short,
217                                              uint64_t>::value));  // NOLINT
218 
219   // Signed => unsigned is not fine.
220   EXPECT_FALSE(
221       (LosslessArithmeticConvertible<short, uint64_t>::value));  // NOLINT
222   EXPECT_FALSE((LosslessArithmeticConvertible<signed char,
223                                               unsigned int>::value));  // NOLINT
224 
225   // Same size and same signedness: fine too.
226   EXPECT_TRUE(
227       (LosslessArithmeticConvertible<unsigned char, unsigned char>::value));
228   EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value));
229   EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value));
230   EXPECT_TRUE((LosslessArithmeticConvertible<unsigned long,
231                                              unsigned long>::value));  // NOLINT
232 
233   // Same size, different signedness: not fine.
234   EXPECT_FALSE(
235       (LosslessArithmeticConvertible<unsigned char, signed char>::value));
236   EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));
237   EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value));
238 
239   // Larger size => smaller size is not fine.
240   EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value));  // NOLINT
241   EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value));
242   EXPECT_FALSE((LosslessArithmeticConvertible<int64_t, unsigned int>::value));
243 }
244 
TEST(LosslessArithmeticConvertibleTest,IntegerToFloatingPoint)245 TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
246   // Integers cannot be losslessly converted to floating-points, as
247   // the format of the latter is implementation-defined.
248   EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value));
249   EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value));
250   EXPECT_FALSE(
251       (LosslessArithmeticConvertible<short, long double>::value));  // NOLINT
252 }
253 
TEST(LosslessArithmeticConvertibleTest,FloatingPointToBool)254 TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
255   EXPECT_FALSE((LosslessArithmeticConvertible<float, bool>::value));
256   EXPECT_FALSE((LosslessArithmeticConvertible<double, bool>::value));
257 }
258 
TEST(LosslessArithmeticConvertibleTest,FloatingPointToInteger)259 TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) {
260   EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value));  // NOLINT
261   EXPECT_FALSE((LosslessArithmeticConvertible<double, int64_t>::value));
262   EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value));
263 }
264 
TEST(LosslessArithmeticConvertibleTest,FloatingPointToFloatingPoint)265 TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) {
266   // Smaller size => larger size is fine.
267   EXPECT_TRUE((LosslessArithmeticConvertible<float, double>::value));
268   EXPECT_TRUE((LosslessArithmeticConvertible<float, long double>::value));
269   EXPECT_TRUE((LosslessArithmeticConvertible<double, long double>::value));
270 
271   // Same size: fine.
272   EXPECT_TRUE((LosslessArithmeticConvertible<float, float>::value));
273   EXPECT_TRUE((LosslessArithmeticConvertible<double, double>::value));
274 
275   // Larger size => smaller size is not fine.
276   EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value));
277   GTEST_INTENTIONAL_CONST_COND_PUSH_()
278   if (sizeof(double) == sizeof(long double)) {  // NOLINT
279     GTEST_INTENTIONAL_CONST_COND_POP_()
280     // In some implementations (e.g. MSVC), double and long double
281     // have the same size.
282     EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value));
283   } else {
284     EXPECT_FALSE((LosslessArithmeticConvertible<long double, double>::value));
285   }
286 }
287 
288 // Tests the TupleMatches() template function.
289 
TEST(TupleMatchesTest,WorksForSize0)290 TEST(TupleMatchesTest, WorksForSize0) {
291   std::tuple<> matchers;
292   std::tuple<> values;
293 
294   EXPECT_TRUE(TupleMatches(matchers, values));
295 }
296 
TEST(TupleMatchesTest,WorksForSize1)297 TEST(TupleMatchesTest, WorksForSize1) {
298   std::tuple<Matcher<int>> matchers(Eq(1));
299   std::tuple<int> values1(1), values2(2);
300 
301   EXPECT_TRUE(TupleMatches(matchers, values1));
302   EXPECT_FALSE(TupleMatches(matchers, values2));
303 }
304 
TEST(TupleMatchesTest,WorksForSize2)305 TEST(TupleMatchesTest, WorksForSize2) {
306   std::tuple<Matcher<int>, Matcher<char>> matchers(Eq(1), Eq('a'));
307   std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'),
308       values4(2, 'b');
309 
310   EXPECT_TRUE(TupleMatches(matchers, values1));
311   EXPECT_FALSE(TupleMatches(matchers, values2));
312   EXPECT_FALSE(TupleMatches(matchers, values3));
313   EXPECT_FALSE(TupleMatches(matchers, values4));
314 }
315 
TEST(TupleMatchesTest,WorksForSize5)316 TEST(TupleMatchesTest, WorksForSize5) {
317   std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>,
318              Matcher<long>,  // NOLINT
319              Matcher<std::string>>
320       matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi"));
321   std::tuple<int, char, bool, long, std::string>  // NOLINT
322       values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"),
323       values3(2, 'a', true, 2L, "hi");
324 
325   EXPECT_TRUE(TupleMatches(matchers, values1));
326   EXPECT_FALSE(TupleMatches(matchers, values2));
327   EXPECT_FALSE(TupleMatches(matchers, values3));
328 }
329 
330 // Tests that Assert(true, ...) succeeds.
TEST(AssertTest,SucceedsOnTrue)331 TEST(AssertTest, SucceedsOnTrue) {
332   Assert(true, __FILE__, __LINE__, "This should succeed.");
333   Assert(true, __FILE__, __LINE__);  // This should succeed too.
334 }
335 
336 // Tests that Assert(false, ...) generates a fatal failure.
TEST(AssertTest,FailsFatallyOnFalse)337 TEST(AssertTest, FailsFatallyOnFalse) {
338   EXPECT_DEATH_IF_SUPPORTED(
339       { Assert(false, __FILE__, __LINE__, "This should fail."); }, "");
340 
341   EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, "");
342 }
343 
344 // Tests that Expect(true, ...) succeeds.
TEST(ExpectTest,SucceedsOnTrue)345 TEST(ExpectTest, SucceedsOnTrue) {
346   Expect(true, __FILE__, __LINE__, "This should succeed.");
347   Expect(true, __FILE__, __LINE__);  // This should succeed too.
348 }
349 
350 // Tests that Expect(false, ...) generates a non-fatal failure.
TEST(ExpectTest,FailsNonfatallyOnFalse)351 TEST(ExpectTest, FailsNonfatallyOnFalse) {
352   EXPECT_NONFATAL_FAILURE(
353       {  // NOLINT
354         Expect(false, __FILE__, __LINE__, "This should fail.");
355       },
356       "This should fail");
357 
358   EXPECT_NONFATAL_FAILURE(
359       {  // NOLINT
360         Expect(false, __FILE__, __LINE__);
361       },
362       "Expectation failed");
363 }
364 
365 // Tests LogIsVisible().
366 
367 class LogIsVisibleTest : public ::testing::Test {
368  protected:
SetUp()369   void SetUp() override { original_verbose_ = GMOCK_FLAG_GET(verbose); }
370 
TearDown()371   void TearDown() override { GMOCK_FLAG_SET(verbose, original_verbose_); }
372 
373   std::string original_verbose_;
374 };
375 
TEST_F(LogIsVisibleTest,AlwaysReturnsTrueIfVerbosityIsInfo)376 TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) {
377   GMOCK_FLAG_SET(verbose, kInfoVerbosity);
378   EXPECT_TRUE(LogIsVisible(kInfo));
379   EXPECT_TRUE(LogIsVisible(kWarning));
380 }
381 
TEST_F(LogIsVisibleTest,AlwaysReturnsFalseIfVerbosityIsError)382 TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) {
383   GMOCK_FLAG_SET(verbose, kErrorVerbosity);
384   EXPECT_FALSE(LogIsVisible(kInfo));
385   EXPECT_FALSE(LogIsVisible(kWarning));
386 }
387 
TEST_F(LogIsVisibleTest,WorksWhenVerbosityIsWarning)388 TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) {
389   GMOCK_FLAG_SET(verbose, kWarningVerbosity);
390   EXPECT_FALSE(LogIsVisible(kInfo));
391   EXPECT_TRUE(LogIsVisible(kWarning));
392 }
393 
394 #if GTEST_HAS_STREAM_REDIRECTION
395 
396 // Tests the Log() function.
397 
398 // Verifies that Log() behaves correctly for the given verbosity level
399 // and log severity.
TestLogWithSeverity(const std::string & verbosity,LogSeverity severity,bool should_print)400 void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity,
401                          bool should_print) {
402   const std::string old_flag = GMOCK_FLAG_GET(verbose);
403   GMOCK_FLAG_SET(verbose, verbosity);
404   CaptureStdout();
405   Log(severity, "Test log.\n", 0);
406   if (should_print) {
407     EXPECT_THAT(
408         GetCapturedStdout().c_str(),
409         ContainsRegex(severity == kWarning
410                           ? "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n"
411                           : "^\nTest log\\.\nStack trace:\n"));
412   } else {
413     EXPECT_STREQ("", GetCapturedStdout().c_str());
414   }
415   GMOCK_FLAG_SET(verbose, old_flag);
416 }
417 
418 // Tests that when the stack_frames_to_skip parameter is negative,
419 // Log() doesn't include the stack trace in the output.
TEST(LogTest,NoStackTraceWhenStackFramesToSkipIsNegative)420 TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) {
421   const std::string saved_flag = GMOCK_FLAG_GET(verbose);
422   GMOCK_FLAG_SET(verbose, kInfoVerbosity);
423   CaptureStdout();
424   Log(kInfo, "Test log.\n", -1);
425   EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str());
426   GMOCK_FLAG_SET(verbose, saved_flag);
427 }
428 
429 struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface {
CurrentStackTracetesting::internal::__anon19b48abd0111::MockStackTraceGetter430   std::string CurrentStackTrace(int max_depth, int skip_count) override {
431     return (testing::Message() << max_depth << "::" << skip_count << "\n")
432         .GetString();
433   }
UponLeavingGTesttesting::internal::__anon19b48abd0111::MockStackTraceGetter434   void UponLeavingGTest() override {}
435 };
436 
437 // Tests that in opt mode, a positive stack_frames_to_skip argument is
438 // treated as 0.
TEST(LogTest,NoSkippingStackFrameInOptMode)439 TEST(LogTest, NoSkippingStackFrameInOptMode) {
440   MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter;
441   GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter);
442 
443   CaptureStdout();
444   Log(kWarning, "Test log.\n", 100);
445   const std::string log = GetCapturedStdout();
446 
447   std::string expected_trace =
448       (testing::Message() << GTEST_FLAG_GET(stack_trace_depth) << "::")
449           .GetString();
450   std::string expected_message =
451       "\nGMOCK WARNING:\n"
452       "Test log.\n"
453       "Stack trace:\n" +
454       expected_trace;
455   EXPECT_THAT(log, HasSubstr(expected_message));
456   int skip_count = atoi(log.substr(expected_message.size()).c_str());
457 
458 #if defined(NDEBUG)
459   // In opt mode, no stack frame should be skipped.
460   const int expected_skip_count = 0;
461 #else
462   // In dbg mode, the stack frames should be skipped.
463   const int expected_skip_count = 100;
464 #endif
465 
466   // Note that each inner implementation layer will +1 the number to remove
467   // itself from the trace. This means that the value is a little higher than
468   // expected, but close enough.
469   EXPECT_THAT(skip_count,
470               AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10)));
471 
472   // Restores the default OS stack trace getter.
473   GetUnitTestImpl()->set_os_stack_trace_getter(nullptr);
474 }
475 
476 // Tests that all logs are printed when the value of the
477 // --gmock_verbose flag is "info".
TEST(LogTest,AllLogsArePrintedWhenVerbosityIsInfo)478 TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) {
479   TestLogWithSeverity(kInfoVerbosity, kInfo, true);
480   TestLogWithSeverity(kInfoVerbosity, kWarning, true);
481 }
482 
483 // Tests that only warnings are printed when the value of the
484 // --gmock_verbose flag is "warning".
TEST(LogTest,OnlyWarningsArePrintedWhenVerbosityIsWarning)485 TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) {
486   TestLogWithSeverity(kWarningVerbosity, kInfo, false);
487   TestLogWithSeverity(kWarningVerbosity, kWarning, true);
488 }
489 
490 // Tests that no logs are printed when the value of the
491 // --gmock_verbose flag is "error".
TEST(LogTest,NoLogsArePrintedWhenVerbosityIsError)492 TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) {
493   TestLogWithSeverity(kErrorVerbosity, kInfo, false);
494   TestLogWithSeverity(kErrorVerbosity, kWarning, false);
495 }
496 
497 // Tests that only warnings are printed when the value of the
498 // --gmock_verbose flag is invalid.
TEST(LogTest,OnlyWarningsArePrintedWhenVerbosityIsInvalid)499 TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) {
500   TestLogWithSeverity("invalid", kInfo, false);
501   TestLogWithSeverity("invalid", kWarning, true);
502 }
503 
504 // Verifies that Log() behaves correctly for the given verbosity level
505 // and log severity.
GrabOutput(void (* logger)(),const char * verbosity)506 std::string GrabOutput(void (*logger)(), const char* verbosity) {
507   const std::string saved_flag = GMOCK_FLAG_GET(verbose);
508   GMOCK_FLAG_SET(verbose, verbosity);
509   CaptureStdout();
510   logger();
511   GMOCK_FLAG_SET(verbose, saved_flag);
512   return GetCapturedStdout();
513 }
514 
515 class DummyMock {
516  public:
517   MOCK_METHOD0(TestMethod, void());
518   MOCK_METHOD1(TestMethodArg, void(int dummy));
519 };
520 
ExpectCallLogger()521 void ExpectCallLogger() {
522   DummyMock mock;
523   EXPECT_CALL(mock, TestMethod());
524   mock.TestMethod();
525 }
526 
527 // Verifies that EXPECT_CALL logs if the --gmock_verbose flag is set to "info".
TEST(ExpectCallTest,LogsWhenVerbosityIsInfo)528 TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) {
529   EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)),
530               HasSubstr("EXPECT_CALL(mock, TestMethod())"));
531 }
532 
533 // Verifies that EXPECT_CALL doesn't log
534 // if the --gmock_verbose flag is set to "warning".
TEST(ExpectCallTest,DoesNotLogWhenVerbosityIsWarning)535 TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) {
536   EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kWarningVerbosity).c_str());
537 }
538 
539 // Verifies that EXPECT_CALL doesn't log
540 // if the --gmock_verbose flag is set to "error".
TEST(ExpectCallTest,DoesNotLogWhenVerbosityIsError)541 TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) {
542   EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str());
543 }
544 
OnCallLogger()545 void OnCallLogger() {
546   DummyMock mock;
547   ON_CALL(mock, TestMethod());
548 }
549 
550 // Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info".
TEST(OnCallTest,LogsWhenVerbosityIsInfo)551 TEST(OnCallTest, LogsWhenVerbosityIsInfo) {
552   EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)),
553               HasSubstr("ON_CALL(mock, TestMethod())"));
554 }
555 
556 // Verifies that ON_CALL doesn't log
557 // if the --gmock_verbose flag is set to "warning".
TEST(OnCallTest,DoesNotLogWhenVerbosityIsWarning)558 TEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) {
559   EXPECT_STREQ("", GrabOutput(OnCallLogger, kWarningVerbosity).c_str());
560 }
561 
562 // Verifies that ON_CALL doesn't log if
563 // the --gmock_verbose flag is set to "error".
TEST(OnCallTest,DoesNotLogWhenVerbosityIsError)564 TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) {
565   EXPECT_STREQ("", GrabOutput(OnCallLogger, kErrorVerbosity).c_str());
566 }
567 
OnCallAnyArgumentLogger()568 void OnCallAnyArgumentLogger() {
569   DummyMock mock;
570   ON_CALL(mock, TestMethodArg(_));
571 }
572 
573 // Verifies that ON_CALL prints provided _ argument.
TEST(OnCallTest,LogsAnythingArgument)574 TEST(OnCallTest, LogsAnythingArgument) {
575   EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)),
576               HasSubstr("ON_CALL(mock, TestMethodArg(_)"));
577 }
578 
579 #endif  // GTEST_HAS_STREAM_REDIRECTION
580 
581 // Tests StlContainerView.
582 
TEST(StlContainerViewTest,WorksForStlContainer)583 TEST(StlContainerViewTest, WorksForStlContainer) {
584   StaticAssertTypeEq<std::vector<int>,
585                      StlContainerView<std::vector<int>>::type>();
586   StaticAssertTypeEq<const std::vector<double>&,
587                      StlContainerView<std::vector<double>>::const_reference>();
588 
589   typedef std::vector<char> Chars;
590   Chars v1;
591   const Chars& v2(StlContainerView<Chars>::ConstReference(v1));
592   EXPECT_EQ(&v1, &v2);
593 
594   v1.push_back('a');
595   Chars v3 = StlContainerView<Chars>::Copy(v1);
596   EXPECT_THAT(v3, Eq(v3));
597 }
598 
TEST(StlContainerViewTest,WorksForStaticNativeArray)599 TEST(StlContainerViewTest, WorksForStaticNativeArray) {
600   StaticAssertTypeEq<NativeArray<int>, StlContainerView<int[3]>::type>();
601   StaticAssertTypeEq<NativeArray<double>,
602                      StlContainerView<const double[4]>::type>();
603   StaticAssertTypeEq<NativeArray<char[3]>,
604                      StlContainerView<const char[2][3]>::type>();
605 
606   StaticAssertTypeEq<const NativeArray<int>,
607                      StlContainerView<int[2]>::const_reference>();
608 
609   int a1[3] = {0, 1, 2};
610   NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1);
611   EXPECT_EQ(3U, a2.size());
612   EXPECT_EQ(a1, a2.begin());
613 
614   const NativeArray<int> a3 = StlContainerView<int[3]>::Copy(a1);
615   ASSERT_EQ(3U, a3.size());
616   EXPECT_EQ(0, a3.begin()[0]);
617   EXPECT_EQ(1, a3.begin()[1]);
618   EXPECT_EQ(2, a3.begin()[2]);
619 
620   // Makes sure a1 and a3 aren't aliases.
621   a1[0] = 3;
622   EXPECT_EQ(0, a3.begin()[0]);
623 }
624 
TEST(StlContainerViewTest,WorksForDynamicNativeArray)625 TEST(StlContainerViewTest, WorksForDynamicNativeArray) {
626   StaticAssertTypeEq<NativeArray<int>,
627                      StlContainerView<std::tuple<const int*, size_t>>::type>();
628   StaticAssertTypeEq<
629       NativeArray<double>,
630       StlContainerView<std::tuple<std::shared_ptr<double>, int>>::type>();
631 
632   StaticAssertTypeEq<
633       const NativeArray<int>,
634       StlContainerView<std::tuple<const int*, int>>::const_reference>();
635 
636   int a1[3] = {0, 1, 2};
637   const int* const p1 = a1;
638   NativeArray<int> a2 =
639       StlContainerView<std::tuple<const int*, int>>::ConstReference(
640           std::make_tuple(p1, 3));
641   EXPECT_EQ(3U, a2.size());
642   EXPECT_EQ(a1, a2.begin());
643 
644   const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t>>::Copy(
645       std::make_tuple(static_cast<int*>(a1), 3));
646   ASSERT_EQ(3U, a3.size());
647   EXPECT_EQ(0, a3.begin()[0]);
648   EXPECT_EQ(1, a3.begin()[1]);
649   EXPECT_EQ(2, a3.begin()[2]);
650 
651   // Makes sure a1 and a3 aren't aliases.
652   a1[0] = 3;
653   EXPECT_EQ(0, a3.begin()[0]);
654 }
655 
656 // Tests the Function template struct.
657 
TEST(FunctionTest,Nullary)658 TEST(FunctionTest, Nullary) {
659   typedef Function<int()> F;  // NOLINT
660   EXPECT_EQ(0u, F::ArgumentCount);
661   EXPECT_TRUE((std::is_same<int, F::Result>::value));
662   EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentTuple>::value));
663   EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentMatcherTuple>::value));
664   EXPECT_TRUE((std::is_same<void(), F::MakeResultVoid>::value));
665   EXPECT_TRUE((std::is_same<IgnoredValue(), F::MakeResultIgnoredValue>::value));
666 }
667 
TEST(FunctionTest,Unary)668 TEST(FunctionTest, Unary) {
669   typedef Function<int(bool)> F;  // NOLINT
670   EXPECT_EQ(1u, F::ArgumentCount);
671   EXPECT_TRUE((std::is_same<int, F::Result>::value));
672   EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));
673   EXPECT_TRUE((std::is_same<std::tuple<bool>, F::ArgumentTuple>::value));
674   EXPECT_TRUE((
675       std::is_same<std::tuple<Matcher<bool>>, F::ArgumentMatcherTuple>::value));
676   EXPECT_TRUE((std::is_same<void(bool), F::MakeResultVoid>::value));  // NOLINT
677   EXPECT_TRUE((std::is_same<IgnoredValue(bool),                       // NOLINT
678                             F::MakeResultIgnoredValue>::value));
679 }
680 
TEST(FunctionTest,Binary)681 TEST(FunctionTest, Binary) {
682   typedef Function<int(bool, const long&)> F;  // NOLINT
683   EXPECT_EQ(2u, F::ArgumentCount);
684   EXPECT_TRUE((std::is_same<int, F::Result>::value));
685   EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));
686   EXPECT_TRUE((std::is_same<const long&, F::Arg<1>::type>::value));  // NOLINT
687   EXPECT_TRUE((std::is_same<std::tuple<bool, const long&>,           // NOLINT
688                             F::ArgumentTuple>::value));
689   EXPECT_TRUE(
690       (std::is_same<std::tuple<Matcher<bool>, Matcher<const long&>>,  // NOLINT
691                     F::ArgumentMatcherTuple>::value));
692   EXPECT_TRUE((std::is_same<void(bool, const long&),  // NOLINT
693                             F::MakeResultVoid>::value));
694   EXPECT_TRUE((std::is_same<IgnoredValue(bool, const long&),  // NOLINT
695                             F::MakeResultIgnoredValue>::value));
696 }
697 
TEST(FunctionTest,LongArgumentList)698 TEST(FunctionTest, LongArgumentList) {
699   typedef Function<char(bool, int, char*, int&, const long&)> F;  // NOLINT
700   EXPECT_EQ(5u, F::ArgumentCount);
701   EXPECT_TRUE((std::is_same<char, F::Result>::value));
702   EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));
703   EXPECT_TRUE((std::is_same<int, F::Arg<1>::type>::value));
704   EXPECT_TRUE((std::is_same<char*, F::Arg<2>::type>::value));
705   EXPECT_TRUE((std::is_same<int&, F::Arg<3>::type>::value));
706   EXPECT_TRUE((std::is_same<const long&, F::Arg<4>::type>::value));  // NOLINT
707   EXPECT_TRUE(
708       (std::is_same<std::tuple<bool, int, char*, int&, const long&>,  // NOLINT
709                     F::ArgumentTuple>::value));
710   EXPECT_TRUE(
711       (std::is_same<
712           std::tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>,
713                      Matcher<const long&>>,  // NOLINT
714           F::ArgumentMatcherTuple>::value));
715   EXPECT_TRUE(
716       (std::is_same<void(bool, int, char*, int&, const long&),  // NOLINT
717                     F::MakeResultVoid>::value));
718   EXPECT_TRUE((
719       std::is_same<IgnoredValue(bool, int, char*, int&, const long&),  // NOLINT
720                    F::MakeResultIgnoredValue>::value));
721 }
722 
TEST(Base64Unescape,InvalidString)723 TEST(Base64Unescape, InvalidString) {
724   std::string unescaped;
725   EXPECT_FALSE(Base64Unescape("(invalid)", &unescaped));
726 }
727 
TEST(Base64Unescape,ShortString)728 TEST(Base64Unescape, ShortString) {
729   std::string unescaped;
730   EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQh", &unescaped));
731   EXPECT_EQ("Hello world!", unescaped);
732 }
733 
TEST(Base64Unescape,ShortStringWithPadding)734 TEST(Base64Unescape, ShortStringWithPadding) {
735   std::string unescaped;
736   EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ=", &unescaped));
737   EXPECT_EQ("Hello world", unescaped);
738 }
739 
TEST(Base64Unescape,ShortStringWithoutPadding)740 TEST(Base64Unescape, ShortStringWithoutPadding) {
741   std::string unescaped;
742   EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ", &unescaped));
743   EXPECT_EQ("Hello world", unescaped);
744 }
745 
TEST(Base64Unescape,LongStringWithWhiteSpaces)746 TEST(Base64Unescape, LongStringWithWhiteSpaces) {
747   std::string escaped =
748       R"(TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
749   IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
750   dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
751   dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
752   ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=)";
753   std::string expected =
754       "Man is distinguished, not only by his reason, but by this singular "
755       "passion from other animals, which is a lust of the mind, that by a "
756       "perseverance of delight in the continued and indefatigable generation "
757       "of knowledge, exceeds the short vehemence of any carnal pleasure.";
758   std::string unescaped;
759   EXPECT_TRUE(Base64Unescape(escaped, &unescaped));
760   EXPECT_EQ(expected, unescaped);
761 }
762 
763 }  // namespace
764 }  // namespace internal
765 }  // namespace testing
766