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