gmock-internal-utils_test.cc 24.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
29

30
31
32
33
34

// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the internal utilities.

35
#include "gmock/internal/gmock-internal-utils.h"
36
#include <stdlib.h>
37
#include <map>
38
#include <memory>
39
40
41
#include <string>
#include <sstream>
#include <vector>
42
43
44
45
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
Gennadiy Civil's avatar
Gennadiy Civil committed
46
47
48
49
50
51
52

// Indicates that this translation unit is part of Google Test's
// implementation.  It must come before gtest-internal-inl.h is
// included, or there will be a compiler error.  This trick is to
// prevent a user from accidentally including gtest-internal-inl.h in
// their code.
#define GTEST_IMPLEMENTATION_ 1
kosak's avatar
kosak committed
53
#include "src/gtest-internal-inl.h"
Gennadiy Civil's avatar
Gennadiy Civil committed
54
#undef GTEST_IMPLEMENTATION_
kosak's avatar
kosak committed
55

56
#if GTEST_OS_CYGWIN
57
# include <sys/types.h>  // For ssize_t. NOLINT
58
59
#endif

zhanyong.wan's avatar
zhanyong.wan committed
60
61
62
63
64
65
class ProtocolMessage;

namespace proto2 {
class Message;
}  // namespace proto2

66
67
68
69
70
namespace testing {
namespace internal {

namespace {

Gennadiy Civil's avatar
Gennadiy Civil committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
TEST(JoinAsTupleTest, JoinsEmptyTuple) {
  EXPECT_EQ("", JoinAsTuple(Strings()));
}

TEST(JoinAsTupleTest, JoinsOneTuple) {
  const char* fields[] = {"1"};
  EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
}

TEST(JoinAsTupleTest, JoinsTwoTuple) {
  const char* fields[] = {"1", "a"};
  EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
}

TEST(JoinAsTupleTest, JoinsTenTuple) {
  const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
  EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
            JoinAsTuple(Strings(fields, fields + 10)));
}

zhanyong.wan's avatar
zhanyong.wan committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) {
  EXPECT_EQ("", ConvertIdentifierNameToWords(""));
  EXPECT_EQ("", ConvertIdentifierNameToWords("_"));
  EXPECT_EQ("", ConvertIdentifierNameToWords("__"));
}

TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsDigits) {
  EXPECT_EQ("1", ConvertIdentifierNameToWords("_1"));
  EXPECT_EQ("2", ConvertIdentifierNameToWords("2_"));
  EXPECT_EQ("34", ConvertIdentifierNameToWords("_34_"));
  EXPECT_EQ("34 56", ConvertIdentifierNameToWords("_34_56"));
}

TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsCamelCaseWords) {
  EXPECT_EQ("a big word", ConvertIdentifierNameToWords("ABigWord"));
  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("FooBar"));
  EXPECT_EQ("foo", ConvertIdentifierNameToWords("Foo_"));
  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_Foo_Bar_"));
  EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_Foo__And_Bar"));
}

TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContains_SeparatedWords) {
  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("foo_bar"));
  EXPECT_EQ("foo", ConvertIdentifierNameToWords("_foo_"));
  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_foo_bar_"));
  EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_foo__and_bar"));
}

TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
  EXPECT_EQ("foo bar 123", ConvertIdentifierNameToWords("Foo_bar123"));
  EXPECT_EQ("chapter 11 section 1",
            ConvertIdentifierNameToWords("_Chapter11Section_1_"));
}

125
TEST(PointeeOfTest, WorksForSmartPointers) {
126
127
128
129
130
131
132
#if GTEST_HAS_STD_UNIQUE_PTR_
  CompileAssertTypesEqual<int, PointeeOf<std::unique_ptr<int> >::type>();
#endif  // GTEST_HAS_STD_UNIQUE_PTR_
#if GTEST_HAS_STD_SHARED_PTR_
  CompileAssertTypesEqual<std::string,
                          PointeeOf<std::shared_ptr<std::string> >::type>();
#endif  // GTEST_HAS_STD_SHARED_PTR_
133
134
135
136
137
138
139
140
141
}

TEST(PointeeOfTest, WorksForRawPointers) {
  CompileAssertTypesEqual<int, PointeeOf<int*>::type>();
  CompileAssertTypesEqual<const char, PointeeOf<const char*>::type>();
  CompileAssertTypesEqual<void, PointeeOf<void*>::type>();
}

TEST(GetRawPointerTest, WorksForSmartPointers) {
142
143
144
145
146
147
148
149
150
151
#if GTEST_HAS_STD_UNIQUE_PTR_
  const char* const raw_p1 = new const char('a');  // NOLINT
  const std::unique_ptr<const char> p1(raw_p1);
  EXPECT_EQ(raw_p1, GetRawPointer(p1));
#endif  // GTEST_HAS_STD_UNIQUE_PTR_
#if GTEST_HAS_STD_SHARED_PTR_
  double* const raw_p2 = new double(2.5);  // NOLINT
  const std::shared_ptr<double> p2(raw_p2);
  EXPECT_EQ(raw_p2, GetRawPointer(p2));
#endif  // GTEST_HAS_STD_SHARED_PTR_
152
153
154
}

TEST(GetRawPointerTest, WorksForRawPointers) {
155
  int* p = nullptr;
156
  // Don't use EXPECT_EQ as no NULL-testing magic on Symbian.
157
  EXPECT_TRUE(nullptr == GetRawPointer(p));
158
159
160
161
  int n = 1;
  EXPECT_EQ(&n, GetRawPointer(&n));
}

162
163
// Tests KindOf<T>.

164
165
166
class Base {};
class Derived : public Base {};

167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
TEST(KindOfTest, Bool) {
  EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool));  // NOLINT
}

TEST(KindOfTest, Integer) {
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(Int64));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(UInt64));  // NOLINT
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t));  // NOLINT
#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN
  // ssize_t is not defined on Windows and possibly some other OSes.
  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t));  // NOLINT
#endif
}

TEST(KindOfTest, FloatingPoint) {
  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float));  // NOLINT
  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double));  // NOLINT
  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double));  // NOLINT
}

TEST(KindOfTest, Other) {
  EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*));  // NOLINT
  EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**));  // NOLINT
  EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base));  // NOLINT
}

// Tests LosslessArithmeticConvertible<T, U>.

TEST(LosslessArithmeticConvertibleTest, BoolToBool) {
  EXPECT_TRUE((LosslessArithmeticConvertible<bool, bool>::value));
}

TEST(LosslessArithmeticConvertibleTest, BoolToInteger) {
  EXPECT_TRUE((LosslessArithmeticConvertible<bool, char>::value));
  EXPECT_TRUE((LosslessArithmeticConvertible<bool, int>::value));
  EXPECT_TRUE(
      (LosslessArithmeticConvertible<bool, unsigned long>::value));  // NOLINT
}

TEST(LosslessArithmeticConvertibleTest, BoolToFloatingPoint) {
  EXPECT_TRUE((LosslessArithmeticConvertible<bool, float>::value));
  EXPECT_TRUE((LosslessArithmeticConvertible<bool, double>::value));
}

TEST(LosslessArithmeticConvertibleTest, IntegerToBool) {
  EXPECT_FALSE((LosslessArithmeticConvertible<unsigned char, bool>::value));
  EXPECT_FALSE((LosslessArithmeticConvertible<int, bool>::value));
}

TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
  // Unsigned => larger signed is fine.
  EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));

  // Unsigned => larger unsigned is fine.
  EXPECT_TRUE(
      (LosslessArithmeticConvertible<unsigned short, UInt64>::value)); // NOLINT

  // Signed => unsigned is not fine.
  EXPECT_FALSE((LosslessArithmeticConvertible<short, UInt64>::value)); // NOLINT
  EXPECT_FALSE((LosslessArithmeticConvertible<
      signed char, unsigned int>::value));  // NOLINT

  // Same size and same signedness: fine too.
  EXPECT_TRUE((LosslessArithmeticConvertible<
               unsigned char, unsigned char>::value));
  EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value));
  EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value));
  EXPECT_TRUE((LosslessArithmeticConvertible<
               unsigned long, unsigned long>::value));  // NOLINT

  // Same size, different signedness: not fine.
  EXPECT_FALSE((LosslessArithmeticConvertible<
                unsigned char, signed char>::value));
  EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));
  EXPECT_FALSE((LosslessArithmeticConvertible<UInt64, Int64>::value));

  // Larger size => smaller size is not fine.
  EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value));  // NOLINT
  EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value));
  EXPECT_FALSE((LosslessArithmeticConvertible<Int64, unsigned int>::value));
}

TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
  // Integers cannot be losslessly converted to floating-points, as
  // the format of the latter is implementation-defined.
  EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value));
  EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value));
  EXPECT_FALSE((LosslessArithmeticConvertible<
                short, long double>::value));  // NOLINT
}

TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
  EXPECT_FALSE((LosslessArithmeticConvertible<float, bool>::value));
  EXPECT_FALSE((LosslessArithmeticConvertible<double, bool>::value));
}

TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) {
  EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value));  // NOLINT
  EXPECT_FALSE((LosslessArithmeticConvertible<double, Int64>::value));
  EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value));
}

TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) {
  // Smaller size => larger size is fine.
  EXPECT_TRUE((LosslessArithmeticConvertible<float, double>::value));
  EXPECT_TRUE((LosslessArithmeticConvertible<float, long double>::value));
  EXPECT_TRUE((LosslessArithmeticConvertible<double, long double>::value));

  // Same size: fine.
  EXPECT_TRUE((LosslessArithmeticConvertible<float, float>::value));
  EXPECT_TRUE((LosslessArithmeticConvertible<double, double>::value));

  // Larger size => smaller size is not fine.
  EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value));
billydonahue's avatar
billydonahue committed
291
  GTEST_INTENTIONAL_CONST_COND_PUSH_()
292
  if (sizeof(double) == sizeof(long double)) {  // NOLINT
billydonahue's avatar
billydonahue committed
293
  GTEST_INTENTIONAL_CONST_COND_POP_()
294
295
296
297
298
299
300
301
    // In some implementations (e.g. MSVC), double and long double
    // have the same size.
    EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value));
  } else {
    EXPECT_FALSE((LosslessArithmeticConvertible<long double, double>::value));
  }
}

302
303
304
// Tests the TupleMatches() template function.

TEST(TupleMatchesTest, WorksForSize0) {
Abseil Team's avatar
Abseil Team committed
305
306
  std::tuple<> matchers;
  std::tuple<> values;
307
308
309
310
311

  EXPECT_TRUE(TupleMatches(matchers, values));
}

TEST(TupleMatchesTest, WorksForSize1) {
Abseil Team's avatar
Abseil Team committed
312
313
  std::tuple<Matcher<int> > matchers(Eq(1));
  std::tuple<int> values1(1), values2(2);
314
315
316
317
318
319

  EXPECT_TRUE(TupleMatches(matchers, values1));
  EXPECT_FALSE(TupleMatches(matchers, values2));
}

TEST(TupleMatchesTest, WorksForSize2) {
Abseil Team's avatar
Abseil Team committed
320
321
  std::tuple<Matcher<int>, Matcher<char> > matchers(Eq(1), Eq('a'));
  std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'),
322
323
324
325
326
327
328
329
330
      values4(2, 'b');

  EXPECT_TRUE(TupleMatches(matchers, values1));
  EXPECT_FALSE(TupleMatches(matchers, values2));
  EXPECT_FALSE(TupleMatches(matchers, values3));
  EXPECT_FALSE(TupleMatches(matchers, values4));
}

TEST(TupleMatchesTest, WorksForSize5) {
Abseil Team's avatar
Abseil Team committed
331
332
333
  std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>,
             Matcher<long>,  // NOLINT
             Matcher<std::string> >
334
      matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi"));
Abseil Team's avatar
Abseil Team committed
335
  std::tuple<int, char, bool, long, std::string>  // NOLINT
336
      values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"),
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
      values3(2, 'a', true, 2L, "hi");

  EXPECT_TRUE(TupleMatches(matchers, values1));
  EXPECT_FALSE(TupleMatches(matchers, values2));
  EXPECT_FALSE(TupleMatches(matchers, values3));
}

// Tests that Assert(true, ...) succeeds.
TEST(AssertTest, SucceedsOnTrue) {
  Assert(true, __FILE__, __LINE__, "This should succeed.");
  Assert(true, __FILE__, __LINE__);  // This should succeed too.
}

// Tests that Assert(false, ...) generates a fatal failure.
TEST(AssertTest, FailsFatallyOnFalse) {
352
  EXPECT_DEATH_IF_SUPPORTED({
353
354
355
    Assert(false, __FILE__, __LINE__, "This should fail.");
  }, "");

356
  EXPECT_DEATH_IF_SUPPORTED({
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
    Assert(false, __FILE__, __LINE__);
  }, "");
}

// Tests that Expect(true, ...) succeeds.
TEST(ExpectTest, SucceedsOnTrue) {
  Expect(true, __FILE__, __LINE__, "This should succeed.");
  Expect(true, __FILE__, __LINE__);  // This should succeed too.
}

// Tests that Expect(false, ...) generates a non-fatal failure.
TEST(ExpectTest, FailsNonfatallyOnFalse) {
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    Expect(false, __FILE__, __LINE__, "This should fail.");
  }, "This should fail");

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    Expect(false, __FILE__, __LINE__);
  }, "Expectation failed");
}

378
379
380
381
// Tests LogIsVisible().

class LogIsVisibleTest : public ::testing::Test {
 protected:
382
  virtual void SetUp() {
383
    original_verbose_ = GMOCK_FLAG(verbose);
384
385
  }

386
387
  virtual void TearDown() { GMOCK_FLAG(verbose) = original_verbose_; }

388
  std::string original_verbose_;
389
390
391
392
};

TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) {
  GMOCK_FLAG(verbose) = kInfoVerbosity;
zhanyong.wan's avatar
zhanyong.wan committed
393
394
  EXPECT_TRUE(LogIsVisible(kInfo));
  EXPECT_TRUE(LogIsVisible(kWarning));
395
396
397
398
}

TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) {
  GMOCK_FLAG(verbose) = kErrorVerbosity;
zhanyong.wan's avatar
zhanyong.wan committed
399
400
  EXPECT_FALSE(LogIsVisible(kInfo));
  EXPECT_FALSE(LogIsVisible(kWarning));
401
402
403
404
}

TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) {
  GMOCK_FLAG(verbose) = kWarningVerbosity;
zhanyong.wan's avatar
zhanyong.wan committed
405
406
  EXPECT_FALSE(LogIsVisible(kInfo));
  EXPECT_TRUE(LogIsVisible(kWarning));
407
408
}

409
#if GTEST_HAS_STREAM_REDIRECTION
410
411
412
413
414

// Tests the Log() function.

// Verifies that Log() behaves correctly for the given verbosity level
// and log severity.
415
void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity,
416
                         bool should_print) {
417
  const std::string old_flag = GMOCK_FLAG(verbose);
418
  GMOCK_FLAG(verbose) = verbosity;
419
  CaptureStdout();
420
421
  Log(severity, "Test log.\n", 0);
  if (should_print) {
422
423
    EXPECT_THAT(GetCapturedStdout().c_str(),
                ContainsRegex(
zhanyong.wan's avatar
zhanyong.wan committed
424
                    severity == kWarning ?
425
426
                    "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" :
                    "^\nTest log\\.\nStack trace:\n"));
427
  } else {
428
    EXPECT_STREQ("", GetCapturedStdout().c_str());
429
430
431
432
433
434
435
  }
  GMOCK_FLAG(verbose) = old_flag;
}

// Tests that when the stack_frames_to_skip parameter is negative,
// Log() doesn't include the stack trace in the output.
TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) {
436
  const std::string saved_flag = GMOCK_FLAG(verbose);
437
  GMOCK_FLAG(verbose) = kInfoVerbosity;
438
  CaptureStdout();
zhanyong.wan's avatar
zhanyong.wan committed
439
  Log(kInfo, "Test log.\n", -1);
440
  EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str());
441
  GMOCK_FLAG(verbose) = saved_flag;
442
443
}

kosak's avatar
kosak committed
444
struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface {
445
  virtual std::string CurrentStackTrace(int max_depth, int skip_count) {
kosak's avatar
kosak committed
446
447
448
449
450
451
    return (testing::Message() << max_depth << "::" << skip_count << "\n")
        .GetString();
  }
  virtual void UponLeavingGTest() {}
};

452
453
454
// Tests that in opt mode, a positive stack_frames_to_skip argument is
// treated as 0.
TEST(LogTest, NoSkippingStackFrameInOptMode) {
kosak's avatar
kosak committed
455
456
457
  MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter;
  GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter);

458
  CaptureStdout();
zhanyong.wan's avatar
zhanyong.wan committed
459
  Log(kWarning, "Test log.\n", 100);
460
  const std::string log = GetCapturedStdout();
461

462
  std::string expected_trace =
kosak's avatar
kosak committed
463
      (testing::Message() << GTEST_FLAG(stack_trace_depth) << "::").GetString();
464
  std::string expected_message =
kosak's avatar
kosak committed
465
466
467
468
469
470
471
472
      "\nGMOCK WARNING:\n"
      "Test log.\n"
      "Stack trace:\n" +
      expected_trace;
  EXPECT_THAT(log, HasSubstr(expected_message));
  int skip_count = atoi(log.substr(expected_message.size()).c_str());

# if defined(NDEBUG)
473
  // In opt mode, no stack frame should be skipped.
kosak's avatar
kosak committed
474
  const int expected_skip_count = 0;
475
# else
476
  // In dbg mode, the stack frames should be skipped.
kosak's avatar
kosak committed
477
  const int expected_skip_count = 100;
478
# endif
kosak's avatar
kosak committed
479
480
481
482
483
484
485
486

  // Note that each inner implementation layer will +1 the number to remove
  // itself from the trace. This means that the value is a little higher than
  // expected, but close enough.
  EXPECT_THAT(skip_count,
              AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10)));

  // Restores the default OS stack trace getter.
487
  GetUnitTestImpl()->set_os_stack_trace_getter(nullptr);
488
489
490
491
492
}

// Tests that all logs are printed when the value of the
// --gmock_verbose flag is "info".
TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) {
zhanyong.wan's avatar
zhanyong.wan committed
493
494
  TestLogWithSeverity(kInfoVerbosity, kInfo, true);
  TestLogWithSeverity(kInfoVerbosity, kWarning, true);
495
496
497
498
499
}

// Tests that only warnings are printed when the value of the
// --gmock_verbose flag is "warning".
TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) {
zhanyong.wan's avatar
zhanyong.wan committed
500
501
  TestLogWithSeverity(kWarningVerbosity, kInfo, false);
  TestLogWithSeverity(kWarningVerbosity, kWarning, true);
502
503
504
505
506
}

// Tests that no logs are printed when the value of the
// --gmock_verbose flag is "error".
TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) {
zhanyong.wan's avatar
zhanyong.wan committed
507
508
  TestLogWithSeverity(kErrorVerbosity, kInfo, false);
  TestLogWithSeverity(kErrorVerbosity, kWarning, false);
509
510
511
512
513
}

// Tests that only warnings are printed when the value of the
// --gmock_verbose flag is invalid.
TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) {
zhanyong.wan's avatar
zhanyong.wan committed
514
515
  TestLogWithSeverity("invalid", kInfo, false);
  TestLogWithSeverity("invalid", kWarning, true);
516
517
}

518
#endif  // GTEST_HAS_STREAM_REDIRECTION
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554

TEST(TypeTraitsTest, true_type) {
  EXPECT_TRUE(true_type::value);
}

TEST(TypeTraitsTest, false_type) {
  EXPECT_FALSE(false_type::value);
}

TEST(TypeTraitsTest, is_reference) {
  EXPECT_FALSE(is_reference<int>::value);
  EXPECT_FALSE(is_reference<char*>::value);
  EXPECT_TRUE(is_reference<const int&>::value);
}

TEST(TypeTraitsTest, is_pointer) {
  EXPECT_FALSE(is_pointer<int>::value);
  EXPECT_FALSE(is_pointer<char&>::value);
  EXPECT_TRUE(is_pointer<const int*>::value);
}

TEST(TypeTraitsTest, type_equals) {
  EXPECT_FALSE((type_equals<int, const int>::value));
  EXPECT_FALSE((type_equals<int, int&>::value));
  EXPECT_FALSE((type_equals<int, double>::value));
  EXPECT_TRUE((type_equals<char, char>::value));
}

TEST(TypeTraitsTest, remove_reference) {
  EXPECT_TRUE((type_equals<char, remove_reference<char&>::type>::value));
  EXPECT_TRUE((type_equals<const int,
               remove_reference<const int&>::type>::value));
  EXPECT_TRUE((type_equals<int, remove_reference<int>::type>::value));
  EXPECT_TRUE((type_equals<double*, remove_reference<double*>::type>::value));
}

555
#if GTEST_HAS_STREAM_REDIRECTION
556
557
558

// Verifies that Log() behaves correctly for the given verbosity level
// and log severity.
559
std::string GrabOutput(void(*logger)(), const char* verbosity) {
560
  const std::string saved_flag = GMOCK_FLAG(verbose);
561
  GMOCK_FLAG(verbose) = verbosity;
562
  CaptureStdout();
563
564
  logger();
  GMOCK_FLAG(verbose) = saved_flag;
565
  return GetCapturedStdout();
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
}

class DummyMock {
 public:
  MOCK_METHOD0(TestMethod, void());
  MOCK_METHOD1(TestMethodArg, void(int dummy));
};

void ExpectCallLogger() {
  DummyMock mock;
  EXPECT_CALL(mock, TestMethod());
  mock.TestMethod();
};

// Verifies that EXPECT_CALL logs if the --gmock_verbose flag is set to "info".
TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) {
582
  EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)),
583
584
585
586
587
588
              HasSubstr("EXPECT_CALL(mock, TestMethod())"));
}

// Verifies that EXPECT_CALL doesn't log
// if the --gmock_verbose flag is set to "warning".
TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) {
589
  EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kWarningVerbosity).c_str());
590
591
592
593
594
}

// Verifies that EXPECT_CALL doesn't log
// if the --gmock_verbose flag is set to "error".
TEST(ExpectCallTest,  DoesNotLogWhenVerbosityIsError) {
595
  EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str());
596
597
598
599
600
601
602
603
604
}

void OnCallLogger() {
  DummyMock mock;
  ON_CALL(mock, TestMethod());
};

// Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info".
TEST(OnCallTest, LogsWhenVerbosityIsInfo) {
605
  EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)),
606
607
608
609
610
611
              HasSubstr("ON_CALL(mock, TestMethod())"));
}

// Verifies that ON_CALL doesn't log
// if the --gmock_verbose flag is set to "warning".
TEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) {
612
  EXPECT_STREQ("", GrabOutput(OnCallLogger, kWarningVerbosity).c_str());
613
614
615
616
617
}

// Verifies that ON_CALL doesn't log if
// the --gmock_verbose flag is set to "error".
TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) {
618
  EXPECT_STREQ("", GrabOutput(OnCallLogger, kErrorVerbosity).c_str());
619
620
621
622
623
624
625
626
627
}

void OnCallAnyArgumentLogger() {
  DummyMock mock;
  ON_CALL(mock, TestMethodArg(_));
}

// Verifies that ON_CALL prints provided _ argument.
TEST(OnCallTest, LogsAnythingArgument) {
628
  EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)),
629
630
631
              HasSubstr("ON_CALL(mock, TestMethodArg(_)"));
}

632
#endif  // GTEST_HAS_STREAM_REDIRECTION
633

634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
// Tests StlContainerView.

TEST(StlContainerViewTest, WorksForStlContainer) {
  StaticAssertTypeEq<std::vector<int>,
      StlContainerView<std::vector<int> >::type>();
  StaticAssertTypeEq<const std::vector<double>&,
      StlContainerView<std::vector<double> >::const_reference>();

  typedef std::vector<char> Chars;
  Chars v1;
  const Chars& v2(StlContainerView<Chars>::ConstReference(v1));
  EXPECT_EQ(&v1, &v2);

  v1.push_back('a');
  Chars v3 = StlContainerView<Chars>::Copy(v1);
  EXPECT_THAT(v3, Eq(v3));
}

TEST(StlContainerViewTest, WorksForStaticNativeArray) {
  StaticAssertTypeEq<NativeArray<int>,
      StlContainerView<int[3]>::type>();
  StaticAssertTypeEq<NativeArray<double>,
      StlContainerView<const double[4]>::type>();
  StaticAssertTypeEq<NativeArray<char[3]>,
      StlContainerView<const char[2][3]>::type>();

  StaticAssertTypeEq<const NativeArray<int>,
      StlContainerView<int[2]>::const_reference>();

  int a1[3] = { 0, 1, 2 };
  NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1);
665
  EXPECT_EQ(3U, a2.size());
666
667
668
  EXPECT_EQ(a1, a2.begin());

  const NativeArray<int> a3 = StlContainerView<int[3]>::Copy(a1);
669
  ASSERT_EQ(3U, a3.size());
670
671
672
673
674
675
676
677
678
679
680
  EXPECT_EQ(0, a3.begin()[0]);
  EXPECT_EQ(1, a3.begin()[1]);
  EXPECT_EQ(2, a3.begin()[2]);

  // Makes sure a1 and a3 aren't aliases.
  a1[0] = 3;
  EXPECT_EQ(0, a3.begin()[0]);
}

TEST(StlContainerViewTest, WorksForDynamicNativeArray) {
  StaticAssertTypeEq<NativeArray<int>,
Abseil Team's avatar
Abseil Team committed
681
682
683
                     StlContainerView<std::tuple<const int*, size_t> >::type>();
  StaticAssertTypeEq<
      NativeArray<double>,
misterg's avatar
misterg committed
684
      StlContainerView<std::tuple<std::shared_ptr<double>, int> >::type>();
685

Abseil Team's avatar
Abseil Team committed
686
687
688
  StaticAssertTypeEq<
      const NativeArray<int>,
      StlContainerView<std::tuple<const int*, int> >::const_reference>();
689
690

  int a1[3] = { 0, 1, 2 };
691
  const int* const p1 = a1;
Abseil Team's avatar
Abseil Team committed
692
693
694
  NativeArray<int> a2 =
      StlContainerView<std::tuple<const int*, int> >::ConstReference(
          std::make_tuple(p1, 3));
695
  EXPECT_EQ(3U, a2.size());
696
697
  EXPECT_EQ(a1, a2.begin());

Abseil Team's avatar
Abseil Team committed
698
699
  const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t> >::Copy(
      std::make_tuple(static_cast<int*>(a1), 3));
700
  ASSERT_EQ(3U, a3.size());
701
702
703
704
705
706
707
708
709
  EXPECT_EQ(0, a3.begin()[0]);
  EXPECT_EQ(1, a3.begin()[1]);
  EXPECT_EQ(2, a3.begin()[2]);

  // Makes sure a1 and a3 aren't aliases.
  a1[0] = 3;
  EXPECT_EQ(0, a3.begin()[0]);
}

710
711
712
}  // namespace
}  // namespace internal
}  // namespace testing