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