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