gtest_unittest.cc 247 KB
Newer Older
shiqian's avatar
shiqian committed
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 2005, 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

shiqian's avatar
shiqian committed
30
31
32
33
//
// Tests for Google Test itself.  This verifies that the basic constructs of
// Google Test work.

Gennadiy Civil's avatar
Gennadiy Civil committed
34
#include "gtest/gtest.h"
35

36
// Verifies that the command line flag variables can be accessed in
Gennadiy Civil's avatar
 
Gennadiy Civil committed
37
38
// code once "gtest.h" has been #included.
// Do not move it after other gtest #includes.
39
40
41
42
43
44
45
46
47
TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
  bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
      || testing::GTEST_FLAG(break_on_failure)
      || testing::GTEST_FLAG(catch_exceptions)
      || testing::GTEST_FLAG(color) != "unknown"
      || testing::GTEST_FLAG(filter) != "unknown"
      || testing::GTEST_FLAG(list_tests)
      || testing::GTEST_FLAG(output) != "unknown"
      || testing::GTEST_FLAG(print_time)
48
      || testing::GTEST_FLAG(random_seed)
49
50
      || testing::GTEST_FLAG(repeat) > 0
      || testing::GTEST_FLAG(show_internal_stack_frames)
51
      || testing::GTEST_FLAG(shuffle)
52
      || testing::GTEST_FLAG(stack_trace_depth) > 0
53
      || testing::GTEST_FLAG(stream_result_to) != "unknown"
54
      || testing::GTEST_FLAG(throw_on_failure);
55
56
57
  EXPECT_TRUE(dummy || !dummy);  // Suppresses warning that dummy is unused.
}

58
59
60
61
62
63
64
65
#include <limits.h>  // For INT_MAX.
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <map>
#include <vector>
#include <ostream>
66
#include <unordered_set>
67

Gennadiy Civil's avatar
Gennadiy Civil committed
68
69
#include "gtest/gtest-spi.h"
#include "src/gtest-internal-inl.h"
shiqian's avatar
shiqian committed
70
71
72

namespace testing {
namespace internal {
73

kosak's avatar
kosak committed
74
75
76
77
78
79
80
#if GTEST_CAN_STREAM_RESULTS_

class StreamingListenerTest : public Test {
 public:
  class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
   public:
    // Sends a string to the socket.
Abseil Team's avatar
Abseil Team committed
81
    void Send(const std::string& message) override { output_ += message; }
kosak's avatar
kosak committed
82

83
    std::string output_;
kosak's avatar
kosak committed
84
85
86
87
88
  };

  StreamingListenerTest()
      : fake_sock_writer_(new FakeSocketWriter),
        streamer_(fake_sock_writer_),
89
90
        test_info_obj_("FooTest", "Bar", nullptr, nullptr,
                       CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {}
kosak's avatar
kosak committed
91
92

 protected:
93
  std::string* output() { return &(fake_sock_writer_->output_); }
kosak's avatar
kosak committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

  FakeSocketWriter* const fake_sock_writer_;
  StreamingListener streamer_;
  UnitTest unit_test_;
  TestInfo test_info_obj_;  // The name test_info_ was taken by testing::Test.
};

TEST_F(StreamingListenerTest, OnTestProgramEnd) {
  *output() = "";
  streamer_.OnTestProgramEnd(unit_test_);
  EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
}

TEST_F(StreamingListenerTest, OnTestIterationEnd) {
  *output() = "";
  streamer_.OnTestIterationEnd(unit_test_, 42);
  EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
}

TEST_F(StreamingListenerTest, OnTestCaseStart) {
  *output() = "";
115
  streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", nullptr, nullptr));
kosak's avatar
kosak committed
116
117
118
119
120
  EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
}

TEST_F(StreamingListenerTest, OnTestCaseEnd) {
  *output() = "";
121
  streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", nullptr, nullptr));
kosak's avatar
kosak committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
  EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
}

TEST_F(StreamingListenerTest, OnTestStart) {
  *output() = "";
  streamer_.OnTestStart(test_info_obj_);
  EXPECT_EQ("event=TestStart&name=Bar\n", *output());
}

TEST_F(StreamingListenerTest, OnTestEnd) {
  *output() = "";
  streamer_.OnTestEnd(test_info_obj_);
  EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
}

TEST_F(StreamingListenerTest, OnTestPartResult) {
  *output() = "";
  streamer_.OnTestPartResult(TestPartResult(
      TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));

  // Meta characters in the failure message should be properly escaped.
  EXPECT_EQ(
      "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
      *output());
}

#endif  // GTEST_CAN_STREAM_RESULTS_

150
// Provides access to otherwise private parts of the TestEventListeners class
151
// that are needed to test it.
152
class TestEventListenersAccessor {
153
 public:
154
  static TestEventListener* GetRepeater(TestEventListeners* listeners) {
155
156
    return listeners->repeater();
  }
157

158
  static void SetDefaultResultPrinter(TestEventListeners* listeners,
159
                                      TestEventListener* listener) {
160
161
    listeners->SetDefaultResultPrinter(listener);
  }
162
  static void SetDefaultXmlGenerator(TestEventListeners* listeners,
163
                                     TestEventListener* listener) {
164
165
166
    listeners->SetDefaultXmlGenerator(listener);
  }

167
  static bool EventForwardingEnabled(const TestEventListeners& listeners) {
168
169
170
    return listeners.EventForwardingEnabled();
  }

171
  static void SuppressEventForwarding(TestEventListeners* listeners) {
172
173
174
175
    listeners->SuppressEventForwarding();
  }
};

176
177
178
179
180
181
182
183
184
185
186
187
class UnitTestRecordPropertyTestHelper : public Test {
 protected:
  UnitTestRecordPropertyTestHelper() {}

  // Forwards to UnitTest::RecordProperty() to bypass access controls.
  void UnitTestRecordProperty(const char* key, const std::string& value) {
    unit_test_.RecordProperty(key, value);
  }

  UnitTest unit_test_;
};

shiqian's avatar
shiqian committed
188
189
190
}  // namespace internal
}  // namespace testing

191
192
193
194
using testing::AssertionFailure;
using testing::AssertionResult;
using testing::AssertionSuccess;
using testing::DoubleLE;
195
using testing::EmptyTestEventListener;
196
using testing::Environment;
197
using testing::FloatLE;
198
using testing::GTEST_FLAG(also_run_disabled_tests);
199
200
using testing::GTEST_FLAG(break_on_failure);
using testing::GTEST_FLAG(catch_exceptions);
shiqian's avatar
shiqian committed
201
using testing::GTEST_FLAG(color);
202
using testing::GTEST_FLAG(death_test_use_fork);
203
204
205
206
using testing::GTEST_FLAG(filter);
using testing::GTEST_FLAG(list_tests);
using testing::GTEST_FLAG(output);
using testing::GTEST_FLAG(print_time);
207
using testing::GTEST_FLAG(random_seed);
208
209
using testing::GTEST_FLAG(repeat);
using testing::GTEST_FLAG(show_internal_stack_frames);
210
using testing::GTEST_FLAG(shuffle);
211
using testing::GTEST_FLAG(stack_trace_depth);
212
using testing::GTEST_FLAG(stream_result_to);
213
using testing::GTEST_FLAG(throw_on_failure);
214
215
216
using testing::IsNotSubstring;
using testing::IsSubstring;
using testing::Message;
shiqian's avatar
shiqian committed
217
using testing::ScopedFakeTestPartResultReporter;
218
using testing::StaticAssertTypeEq;
219
using testing::Test;
220
using testing::TestCase;
221
using testing::TestEventListeners;
222
using testing::TestInfo;
223
224
using testing::TestPartResult;
using testing::TestPartResultArray;
225
226
using testing::TestProperty;
using testing::TestResult;
227
using testing::TimeInMillis;
shiqian's avatar
shiqian committed
228
using testing::UnitTest;
229
using testing::internal::AddReference;
230
231
using testing::internal::AlwaysFalse;
using testing::internal::AlwaysTrue;
shiqian's avatar
shiqian committed
232
using testing::internal::AppendUserMessage;
233
234
using testing::internal::ArrayAwareFind;
using testing::internal::ArrayEq;
235
using testing::internal::CodePointToUtf8;
236
237
using testing::internal::CompileAssertTypesEqual;
using testing::internal::CopyArray;
238
using testing::internal::CountIf;
shiqian's avatar
shiqian committed
239
using testing::internal::EqFailure;
240
using testing::internal::FloatingPoint;
241
using testing::internal::ForEach;
242
using testing::internal::FormatEpochTimeInMillisAsIso8601;
243
using testing::internal::FormatTimeInMillisAsSeconds;
244
using testing::internal::GTestFlagSaver;
245
using testing::internal::GetCurrentOsStackTraceExceptTop;
246
using testing::internal::GetElementOr;
247
248
using testing::internal::GetNextRandomSeed;
using testing::internal::GetRandomSeedFromFlag;
249
using testing::internal::GetTestTypeId;
250
using testing::internal::GetTimeInMillis;
251
using testing::internal::GetTypeId;
252
using testing::internal::GetUnitTestImpl;
shiqian's avatar
shiqian committed
253
using testing::internal::Int32;
254
using testing::internal::Int32FromEnvOrDie;
255
256
257
258
259
using testing::internal::IsAProtocolMessage;
using testing::internal::IsContainer;
using testing::internal::IsContainerTest;
using testing::internal::IsNotContainer;
using testing::internal::NativeArray;
260
261
using testing::internal::OsStackTraceGetter;
using testing::internal::OsStackTraceGetterInterface;
262
using testing::internal::ParseInt32Flag;
billydonahue's avatar
billydonahue committed
263
264
using testing::internal::RelationToSourceCopy;
using testing::internal::RelationToSourceReference;
265
266
using testing::internal::RemoveConst;
using testing::internal::RemoveReference;
267
268
using testing::internal::ShouldRunTestOnShard;
using testing::internal::ShouldShard;
shiqian's avatar
shiqian committed
269
using testing::internal::ShouldUseColor;
270
271
using testing::internal::Shuffle;
using testing::internal::ShuffleRange;
zhanyong.wan's avatar
zhanyong.wan committed
272
using testing::internal::SkipPrefix;
shiqian's avatar
shiqian committed
273
274
using testing::internal::StreamableToString;
using testing::internal::String;
275
using testing::internal::TestEventListenersAccessor;
276
using testing::internal::TestResultAccessor;
277
using testing::internal::UInt32;
278
using testing::internal::UnitTestImpl;
279
using testing::internal::WideStringToUtf8;
280
281
282
using testing::internal::edit_distance::CalculateOptimalEdits;
using testing::internal::edit_distance::CreateUnifiedDiff;
using testing::internal::edit_distance::EditType;
283
using testing::internal::kMaxRandomSeed;
284
using testing::internal::kTestTypeIdInGoogleTest;
billydonahue's avatar
billydonahue committed
285
using testing::kMaxStackTraceDepth;
shiqian's avatar
shiqian committed
286

287
#if GTEST_HAS_STREAM_REDIRECTION
288
289
using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStdout;
290
#endif
291

292
293
294
295
#if GTEST_IS_THREADSAFE
using testing::internal::ThreadWithParam;
#endif

296
class TestingVector : public std::vector<int> {
297
298
299
300
301
};

::std::ostream& operator<<(::std::ostream& os,
                           const TestingVector& vector) {
  os << "{ ";
302
303
  for (size_t i = 0; i < vector.size(); i++) {
    os << vector[i] << " ";
304
305
306
307
308
  }
  os << "}";
  return os;
}

shiqian's avatar
shiqian committed
309
310
311
// This line tests that we can define tests in an unnamed namespace.
namespace {

312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
TEST(GetRandomSeedFromFlagTest, HandlesZero) {
  const int seed = GetRandomSeedFromFlag(0);
  EXPECT_LE(1, seed);
  EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
}

TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
  EXPECT_EQ(1, GetRandomSeedFromFlag(1));
  EXPECT_EQ(2, GetRandomSeedFromFlag(2));
  EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
  EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
            GetRandomSeedFromFlag(kMaxRandomSeed));
}

TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
  const int seed1 = GetRandomSeedFromFlag(-1);
  EXPECT_LE(1, seed1);
  EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));

  const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
  EXPECT_LE(1, seed2);
  EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
}

TEST(GetNextRandomSeedTest, WorksForValidInput) {
  EXPECT_EQ(2, GetNextRandomSeed(1));
  EXPECT_EQ(3, GetNextRandomSeed(2));
  EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
            GetNextRandomSeed(kMaxRandomSeed - 1));
  EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));

  // We deliberately don't test GetNextRandomSeed() with invalid
  // inputs, as that requires death tests, which are expensive.  This
  // is fine as GetNextRandomSeed() is internal and has a
  // straightforward definition.
}

349
350
351
352
353
static void ClearCurrentTestPartResults() {
  TestResultAccessor::ClearTestPartResults(
      GetUnitTestImpl()->current_test_result());
}

354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Tests GetTypeId.

TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
  EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
  EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
}

class SubClassOfTest : public Test {};
class AnotherSubClassOfTest : public Test {};

TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
  EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
  EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
  EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
  EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
  EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
  EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
}

// Verifies that GetTestTypeId() returns the same value, no matter it
// is called from inside Google Test or outside of it.
TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
  EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
}

379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Tests CanonicalizeForStdLibVersioning.

using ::testing::internal::CanonicalizeForStdLibVersioning;

TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) {
  EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind"));
  EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_"));
  EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo"));
  EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x"));
  EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x"));
  EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x"));
}

TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
  EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind"));
  EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_"));

  EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind"));
  EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_"));

  EXPECT_EQ("std::bind",
            CanonicalizeForStdLibVersioning("std::__google::bind"));
  EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_"));
}
Gennadiy Civil's avatar
Gennadiy Civil committed
403

shiqian's avatar
shiqian committed
404
405
406
// Tests FormatTimeInMillisAsSeconds().

TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
407
  EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
shiqian's avatar
shiqian committed
408
409
410
}

TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
411
412
413
414
415
  EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
  EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
  EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
  EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
  EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
shiqian's avatar
shiqian committed
416
417
418
}

TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
419
420
421
422
423
  EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
  EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
  EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
  EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
  EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
shiqian's avatar
shiqian committed
424
425
}

426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Tests FormatEpochTimeInMillisAsIso8601().  The correctness of conversion
// for particular dates below was verified in Python using
// datetime.datetime.fromutctimestamp(<timetamp>/1000).

// FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
// have to set up a particular timezone to obtain predictable results.
class FormatEpochTimeInMillisAsIso8601Test : public Test {
 public:
  // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
  // 32 bits, even when 64-bit integer types are available.  We have to
  // force the constants to have a 64-bit type here.
  static const TimeInMillis kMillisPerSec = 1000;

 private:
Abseil Team's avatar
Abseil Team committed
440
  void SetUp() override {
441
    saved_tz_ = nullptr;
billydonahue's avatar
billydonahue committed
442

443
    GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
444
445
    if (getenv("TZ"))
      saved_tz_ = strdup(getenv("TZ"));
446
    GTEST_DISABLE_MSC_DEPRECATED_POP_()
447
448
449
450
451
452
453

    // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use.  We
    // cannot use the local time zone because the function's output depends
    // on the time zone.
    SetTimeZone("UTC+00");
  }

Abseil Team's avatar
Abseil Team committed
454
  void TearDown() override {
455
456
    SetTimeZone(saved_tz_);
    free(const_cast<char*>(saved_tz_));
457
    saved_tz_ = nullptr;
458
459
460
461
462
463
  }

  static void SetTimeZone(const char* time_zone) {
    // tzset() distinguishes between the TZ variable being present and empty
    // and not being present, so we have to consider the case of time_zone
    // being NULL.
464
#if _MSC_VER || GTEST_OS_WINDOWS_MINGW
465
466
467
468
469
    // ...Unless it's MSVC, whose standard library's _putenv doesn't
    // distinguish between an empty and a missing variable.
    const std::string env_var =
        std::string("TZ=") + (time_zone ? time_zone : "");
    _putenv(env_var.c_str());
billydonahue's avatar
billydonahue committed
470
    GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
471
    tzset();
billydonahue's avatar
billydonahue committed
472
    GTEST_DISABLE_MSC_WARNINGS_POP_()
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
#else
    if (time_zone) {
      setenv(("TZ"), time_zone, 1);
    } else {
      unsetenv("TZ");
    }
    tzset();
#endif
  }

  const char* saved_tz_;
};

const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;

TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
  EXPECT_EQ("2011-10-31T18:52:42",
            FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
}

TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) {
  EXPECT_EQ(
      "2011-10-31T18:52:42",
      FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
}

TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
  EXPECT_EQ("2011-09-03T05:07:02",
            FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
}

TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
  EXPECT_EQ("2011-09-28T17:08:22",
            FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
}

TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
  EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0));
}

513
# ifdef __BORLANDC__
514
// Silences warnings: "Condition is always true", "Unreachable code"
515
516
#  pragma option push -w-ccc -w-rch
# endif
517

Abseil Team's avatar
Abseil Team committed
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
// Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal
// when the RHS is a pointer type.
TEST(NullLiteralTest, LHSAllowsNullLiterals) {
  EXPECT_EQ(0, static_cast<void*>(nullptr));     // NOLINT
  ASSERT_EQ(0, static_cast<void*>(nullptr));     // NOLINT
  EXPECT_EQ(NULL, static_cast<void*>(nullptr));  // NOLINT
  ASSERT_EQ(NULL, static_cast<void*>(nullptr));  // NOLINT
  EXPECT_EQ(nullptr, static_cast<void*>(nullptr));
  ASSERT_EQ(nullptr, static_cast<void*>(nullptr));

  const int* const p = nullptr;
  EXPECT_EQ(0, p);     // NOLINT
  ASSERT_EQ(0, p);     // NOLINT
  EXPECT_EQ(NULL, p);  // NOLINT
  ASSERT_EQ(NULL, p);  // NOLINT
  EXPECT_EQ(nullptr, p);
  ASSERT_EQ(nullptr, p);
shiqian's avatar
shiqian committed
535
536
}

Abseil Team's avatar
Abseil Team committed
537
538
539
540
541
542
543
struct ConvertToAll {
  template <typename T>
  operator T() const {  // NOLINT
    return T();
  }
};

Abseil Team's avatar
Abseil Team committed
544
545
546
547
548
549
550
struct ConvertToPointer {
  template <class T>
  operator T*() const {  // NOLINT
    return nullptr;
  }
};

Abseil Team's avatar
Abseil Team committed
551
552
553
554
555
556
557
558
struct ConvertToAllButNoPointers {
  template <typename T,
            typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0>
  operator T() const {  // NOLINT
    return T();
  }
};

Abseil Team's avatar
Abseil Team committed
559
560
561
struct MyType {};
inline bool operator==(MyType const&, MyType const&) { return true; }

Abseil Team's avatar
Abseil Team committed
562
TEST(NullLiteralTest, ImplicitConversion) {
Abseil Team's avatar
Abseil Team committed
563
564
565
566
567
568
569
  EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr));
#if !defined(__GNUC__) || defined(__clang__)
  // Disabled due to GCC bug gcc.gnu.org/PR89580
  EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr));
#endif
  EXPECT_EQ(ConvertToAll{}, MyType{});
  EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{});
Abseil Team's avatar
Abseil Team committed
570
571
}

Abseil Team's avatar
Abseil Team committed
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
#ifdef __clang__
#pragma clang diagnostic push
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic error "-Wzero-as-null-pointer-constant"
#endif
#endif

TEST(NullLiteralTest, NoConversionNoWarning) {
  // Test that gtests detection and handling of null pointer constants
  // doesn't trigger a warning when '0' isn't actually used as null.
  EXPECT_EQ(0, 0);
  ASSERT_EQ(0, 0);
}

#ifdef __clang__
#pragma clang diagnostic pop
#endif

590
# ifdef __BORLANDC__
591
// Restores warnings after previous "#pragma option push" suppressed them.
592
593
#  pragma option pop
# endif
594

595
596
//
// Tests CodePointToUtf8().
shiqian's avatar
shiqian committed
597
598

// Tests that the NUL character L'\0' is encoded correctly.
599
TEST(CodePointToUtf8Test, CanEncodeNul) {
600
  EXPECT_EQ("", CodePointToUtf8(L'\0'));
shiqian's avatar
shiqian committed
601
602
603
}

// Tests that ASCII characters are encoded correctly.
604
TEST(CodePointToUtf8Test, CanEncodeAscii) {
605
606
607
608
  EXPECT_EQ("a", CodePointToUtf8(L'a'));
  EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
  EXPECT_EQ("&", CodePointToUtf8(L'&'));
  EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
shiqian's avatar
shiqian committed
609
610
611
612
}

// Tests that Unicode code-points that have 8 to 11 bits are encoded
// as 110xxxxx 10xxxxxx.
613
TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
shiqian's avatar
shiqian committed
614
  // 000 1101 0011 => 110-00011 10-010011
615
  EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
shiqian's avatar
shiqian committed
616
617

  // 101 0111 0110 => 110-10101 10-110110
618
  // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
Troy Holsapple's avatar
Troy Holsapple committed
619
  // in wide strings and wide chars. In order to accommodate them, we have to
620
  // introduce such character constants as integers.
621
622
  EXPECT_EQ("\xD5\xB6",
            CodePointToUtf8(static_cast<wchar_t>(0x576)));
shiqian's avatar
shiqian committed
623
624
625
626
}

// Tests that Unicode code-points that have 12 to 16 bits are encoded
// as 1110xxxx 10xxxxxx 10xxxxxx.
627
TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
shiqian's avatar
shiqian committed
628
  // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
629
630
  EXPECT_EQ("\xE0\xA3\x93",
            CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
shiqian's avatar
shiqian committed
631
632

  // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
633
634
  EXPECT_EQ("\xEC\x9D\x8D",
            CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
shiqian's avatar
shiqian committed
635
636
}

zhanyong.wan's avatar
zhanyong.wan committed
637
#if !GTEST_WIDE_STRING_USES_UTF16_
shiqian's avatar
shiqian committed
638
// Tests in this group require a wchar_t to hold > 16 bits, and thus
Abseil Team's avatar
Abseil Team committed
639
// are skipped on Windows, and Cygwin, where a wchar_t is
640
// 16-bit wide. This code may not compile on those systems.
shiqian's avatar
shiqian committed
641
642
643

// Tests that Unicode code-points that have 17 to 21 bits are encoded
// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
644
TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
shiqian's avatar
shiqian committed
645
  // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
646
  EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
647
648

  // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
649
  EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
shiqian's avatar
shiqian committed
650

651
  // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
652
  EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
shiqian's avatar
shiqian committed
653
654
655
}

// Tests that encoding an invalid code-point generates the expected result.
656
TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
657
  EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
658
659
}

zhanyong.wan's avatar
zhanyong.wan committed
660
#endif  // !GTEST_WIDE_STRING_USES_UTF16_
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685

// Tests WideStringToUtf8().

// Tests that the NUL character L'\0' is encoded correctly.
TEST(WideStringToUtf8Test, CanEncodeNul) {
  EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
  EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
}

// Tests that ASCII strings are encoded correctly.
TEST(WideStringToUtf8Test, CanEncodeAscii) {
  EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
  EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
  EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
  EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
}

// Tests that Unicode code-points that have 8 to 11 bits are encoded
// as 110xxxxx 10xxxxxx.
TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
  // 000 1101 0011 => 110-00011 10-010011
  EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
  EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());

  // 101 0111 0110 => 110-10101 10-110110
686
687
688
  const wchar_t s[] = { 0x576, '\0' };
  EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
  EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
689
690
691
692
693
694
}

// Tests that Unicode code-points that have 12 to 16 bits are encoded
// as 1110xxxx 10xxxxxx 10xxxxxx.
TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
  // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
695
696
697
  const wchar_t s1[] = { 0x8D3, '\0' };
  EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
  EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
698
699

  // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
700
701
702
  const wchar_t s2[] = { 0xC74D, '\0' };
  EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
  EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
shiqian's avatar
shiqian committed
703
704
}

705
706
707
708
709
710
711
712
713
714
715
// Tests that the conversion stops when the function encounters \0 character.
TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
  EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
}

// Tests that the conversion stops when the function reaches the limit
// specified by the 'length' parameter.
TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
  EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
}

zhanyong.wan's avatar
zhanyong.wan committed
716
#if !GTEST_WIDE_STRING_USES_UTF16_
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
// Tests that Unicode code-points that have 17 to 21 bits are encoded
// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
// on the systems using UTF-16 encoding.
TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
  // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
  EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
  EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());

  // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
  EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
  EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
}

// Tests that encoding an invalid code-point generates the expected result.
TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
  EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
               WideStringToUtf8(L"\xABCDFF", -1).c_str());
}
zhanyong.wan's avatar
zhanyong.wan committed
735
#else  // !GTEST_WIDE_STRING_USES_UTF16_
736
737
738
// Tests that surrogate pairs are encoded correctly on the systems using
// UTF-16 encoding in the wide strings.
TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
739
740
  const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
  EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
741
742
743
744
745
746
}

// Tests that encoding an invalid UTF-16 surrogate pair
// generates the expected result.
TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
  // Leading surrogate is at the end of the string.
747
748
  const wchar_t s1[] = { 0xD800, '\0' };
  EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
749
  // Leading surrogate is not followed by the trailing surrogate.
750
751
  const wchar_t s2[] = { 0xD800, 'M', '\0' };
  EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
752
  // Trailing surrogate appearas without a leading surrogate.
753
754
  const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
  EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
755
}
zhanyong.wan's avatar
zhanyong.wan committed
756
#endif  // !GTEST_WIDE_STRING_USES_UTF16_
757
758

// Tests that codepoint concatenation works correctly.
zhanyong.wan's avatar
zhanyong.wan committed
759
#if !GTEST_WIDE_STRING_USES_UTF16_
760
TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
761
  const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
762
763
764
765
766
767
768
  EXPECT_STREQ(
      "\xF4\x88\x98\xB4"
          "\xEC\x9D\x8D"
          "\n"
          "\xD5\xB6"
          "\xE0\xA3\x93"
          "\xF4\x88\x98\xB4",
769
      WideStringToUtf8(s, -1).c_str());
770
771
772
}
#else
TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
773
  const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
774
775
  EXPECT_STREQ(
      "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
776
      WideStringToUtf8(s, -1).c_str());
777
}
zhanyong.wan's avatar
zhanyong.wan committed
778
#endif  // !GTEST_WIDE_STRING_USES_UTF16_
shiqian's avatar
shiqian committed
779

780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
// Tests the Random class.

TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
  testing::internal::Random random(42);
  EXPECT_DEATH_IF_SUPPORTED(
      random.Generate(0),
      "Cannot generate a number in the range \\[0, 0\\)");
  EXPECT_DEATH_IF_SUPPORTED(
      random.Generate(testing::internal::Random::kMaxRange + 1),
      "Generation of a number in \\[0, 2147483649\\) was requested, "
      "but this can only generate numbers in \\[0, 2147483648\\)");
}

TEST(RandomTest, GeneratesNumbersWithinRange) {
  const UInt32 kRange = 10000;
  testing::internal::Random random(12345);
  for (int i = 0; i < 10; i++) {
    EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
  }

  testing::internal::Random random2(testing::internal::Random::kMaxRange);
  for (int i = 0; i < 10; i++) {
    EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
  }
}

TEST(RandomTest, RepeatsWhenReseeded) {
  const int kSeed = 123;
  const int kArraySize = 10;
  const UInt32 kRange = 10000;
  UInt32 values[kArraySize];

  testing::internal::Random random(kSeed);
  for (int i = 0; i < kArraySize; i++) {
    values[i] = random.Generate(kRange);
  }

  random.Reseed(kSeed);
  for (int i = 0; i < kArraySize; i++) {
    EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
  }
}

823
// Tests STL container utilities.
824

825
// Tests CountIf().
826

827
static bool IsPositive(int n) { return n > 0; }
828

829
830
831
TEST(ContainerUtilityTest, CountIf) {
  std::vector<int> v;
  EXPECT_EQ(0, CountIf(v, IsPositive));  // Works for an empty container.
832

833
834
835
  v.push_back(-1);
  v.push_back(0);
  EXPECT_EQ(0, CountIf(v, IsPositive));  // Works when no value satisfies.
836

837
838
839
840
  v.push_back(2);
  v.push_back(-10);
  v.push_back(10);
  EXPECT_EQ(2, CountIf(v, IsPositive));
841
}
shiqian's avatar
shiqian committed
842

843
// Tests ForEach().
844

845
846
static int g_sum = 0;
static void Accumulate(int n) { g_sum += n; }
847

848
849
850
851
852
TEST(ContainerUtilityTest, ForEach) {
  std::vector<int> v;
  g_sum = 0;
  ForEach(v, Accumulate);
  EXPECT_EQ(0, g_sum);  // Works for an empty container;
853

854
855
856
857
858
859
860
861
862
863
  g_sum = 0;
  v.push_back(1);
  ForEach(v, Accumulate);
  EXPECT_EQ(1, g_sum);  // Works for a container with one element.

  g_sum = 0;
  v.push_back(20);
  v.push_back(300);
  ForEach(v, Accumulate);
  EXPECT_EQ(321, g_sum);
864
865
}

866
867
868
869
// Tests GetElementOr().
TEST(ContainerUtilityTest, GetElementOr) {
  std::vector<char> a;
  EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
870

871
872
873
874
875
876
  a.push_back('a');
  a.push_back('b');
  EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
  EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
  EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
  EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
877
878
}

879
880
881
882
883
TEST(ContainerUtilityDeathTest, ShuffleRange) {
  std::vector<int> a;
  a.push_back(0);
  a.push_back(1);
  a.push_back(2);
884
885
886
  testing::internal::Random random(1);

  EXPECT_DEATH_IF_SUPPORTED(
887
      ShuffleRange(&random, -1, 1, &a),
888
889
      "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
  EXPECT_DEATH_IF_SUPPORTED(
890
      ShuffleRange(&random, 4, 4, &a),
891
892
      "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
  EXPECT_DEATH_IF_SUPPORTED(
893
      ShuffleRange(&random, 3, 2, &a),
894
895
      "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
  EXPECT_DEATH_IF_SUPPORTED(
896
      ShuffleRange(&random, 3, 4, &a),
897
898
899
900
901
      "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
}

class VectorShuffleTest : public Test {
 protected:
902
  static const size_t kVectorSize = 20;
903
904

  VectorShuffleTest() : random_(1) {
905
    for (int i = 0; i < static_cast<int>(kVectorSize); i++) {
906
      vector_.push_back(i);
907
908
909
910
    }
  }

  static bool VectorIsCorrupt(const TestingVector& vector) {
911
    if (kVectorSize != vector.size()) {
912
913
914
915
      return true;
    }

    bool found_in_vector[kVectorSize] = { false };
916
917
    for (size_t i = 0; i < vector.size(); i++) {
      const int e = vector[i];
918
      if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
        return true;
      }
      found_in_vector[e] = true;
    }

    // Vector size is correct, elements' range is correct, no
    // duplicate elements.  Therefore no corruption has occurred.
    return false;
  }

  static bool VectorIsNotCorrupt(const TestingVector& vector) {
    return !VectorIsCorrupt(vector);
  }

  static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
    for (int i = begin; i < end; i++) {
935
      if (i != vector[static_cast<size_t>(i)]) {
936
937
938
939
940
941
942
943
944
945
946
947
        return true;
      }
    }
    return false;
  }

  static bool RangeIsUnshuffled(
      const TestingVector& vector, int begin, int end) {
    return !RangeIsShuffled(vector, begin, end);
  }

  static bool VectorIsShuffled(const TestingVector& vector) {
948
    return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
949
950
951
952
953
954
955
956
957
958
  }

  static bool VectorIsUnshuffled(const TestingVector& vector) {
    return !VectorIsShuffled(vector);
  }

  testing::internal::Random random_;
  TestingVector vector_;
};  // class VectorShuffleTest

959
const size_t VectorShuffleTest::kVectorSize;
960
961
962

TEST_F(VectorShuffleTest, HandlesEmptyRange) {
  // Tests an empty range at the beginning...
963
  ShuffleRange(&random_, 0, 0, &vector_);
964
965
966
967
  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  ASSERT_PRED1(VectorIsUnshuffled, vector_);

  // ...in the middle...
968
  ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
969
970
971
972
  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  ASSERT_PRED1(VectorIsUnshuffled, vector_);

  // ...at the end...
973
  ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
974
975
976
977
  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  ASSERT_PRED1(VectorIsUnshuffled, vector_);

  // ...and past the end.
978
  ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
979
980
981
982
983
984
  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  ASSERT_PRED1(VectorIsUnshuffled, vector_);
}

TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
  // Tests a size one range at the beginning...
985
  ShuffleRange(&random_, 0, 1, &vector_);
986
987
988
989
  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  ASSERT_PRED1(VectorIsUnshuffled, vector_);

  // ...in the middle...
990
  ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
991
992
993
994
  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  ASSERT_PRED1(VectorIsUnshuffled, vector_);

  // ...and at the end.
995
  ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
996
997
998
999
1000
1001
1002
1003
  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  ASSERT_PRED1(VectorIsUnshuffled, vector_);
}

// Because we use our own random number generator and a fixed seed,
// we can guarantee that the following "random" tests will succeed.

TEST_F(VectorShuffleTest, ShufflesEntireVector) {
1004
  Shuffle(&random_, &vector_);
1005
1006
1007
1008
1009
  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;

  // Tests the first and last elements in particular to ensure that
  // there are no off-by-one problems in our shuffle algorithm.
1010
  EXPECT_NE(0, vector_[0]);
1011
  EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);
1012
1013
1014
1015
1016
}

TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
  const int kRangeSize = kVectorSize/2;

1017
  ShuffleRange(&random_, 0, kRangeSize, &vector_);
1018
1019
1020

  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
1021
1022
  EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize,
               static_cast<int>(kVectorSize));
1023
1024
1025
1026
}

TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
  const int kRangeSize = kVectorSize / 2;
1027
  ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
1028
1029
1030

  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1031
1032
  EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize,
               static_cast<int>(kVectorSize));
1033
1034
1035
}

TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
1036
  const int kRangeSize = static_cast<int>(kVectorSize) / 3;
1037
  ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
1038
1039
1040
1041

  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
  EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
1042
1043
  EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,
               static_cast<int>(kVectorSize));
1044
1045
1046
1047
}

TEST_F(VectorShuffleTest, ShufflesRepeatably) {
  TestingVector vector2;
1048
1049
  for (size_t i = 0; i < kVectorSize; i++) {
    vector2.push_back(static_cast<int>(i));
1050
1051
1052
  }

  random_.Reseed(1234);
1053
  Shuffle(&random_, &vector_);
1054
  random_.Reseed(1234);
1055
  Shuffle(&random_, &vector2);
1056
1057
1058
1059

  ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  ASSERT_PRED1(VectorIsNotCorrupt, vector2);

1060
  for (size_t i = 0; i < kVectorSize; i++) {
1061
    EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
1062
1063
1064
  }
}

1065
// Tests the size of the AssertHelper class.
shiqian's avatar
shiqian committed
1066

1067
TEST(AssertHelperTest, AssertHelperIsSmall) {
1068
  // To avoid breaking clients that use lots of assertions in one
1069
1070
  // function, we cannot grow the size of AssertHelper.
  EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
1071
1072
}

shiqian's avatar
shiqian committed
1073
1074
// Tests String::EndsWithCaseInsensitive().
TEST(StringTest, EndsWithCaseInsensitive) {
1075
1076
1077
1078
  EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
  EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
  EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
  EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
shiqian's avatar
shiqian committed
1079

1080
1081
1082
  EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
  EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
  EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
shiqian's avatar
shiqian committed
1083
1084
}

1085
1086
1087
// C++Builder's preprocessor is buggy; it fails to expand macros that
// appear in macro parameters after wide char literals.  Provide an alias
// for NULL as a workaround.
1088
static const wchar_t* const kNull = nullptr;
1089

1090
1091
// Tests String::CaseInsensitiveWideCStringEquals
TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1092
  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr));
1093
1094
1095
1096
  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
1097
1098
1099
1100
1101
  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
}

zhanyong.wan's avatar
zhanyong.wan committed
1102
#if GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
1103
1104
1105
1106
1107
1108
1109
1110
1111

// Tests String::ShowWideCString().
TEST(StringTest, ShowWideCString) {
  EXPECT_STREQ("(null)",
               String::ShowWideCString(NULL).c_str());
  EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
  EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
}

1112
# if GTEST_OS_WINDOWS_MOBILE
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
TEST(StringTest, AnsiAndUtf16Null) {
  EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
  EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
}

TEST(StringTest, AnsiAndUtf16ConvertBasic) {
  const char* ansi = String::Utf16ToAnsi(L"str");
  EXPECT_STREQ("str", ansi);
  delete [] ansi;
  const WCHAR* utf16 = String::AnsiToUtf16("str");
1123
  EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
1124
1125
1126
1127
1128
1129
1130
1131
  delete [] utf16;
}

TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
  const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
  EXPECT_STREQ(".:\\ \"*?", ansi);
  delete [] ansi;
  const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
1132
  EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
1133
1134
  delete [] utf16;
}
1135
# endif  // GTEST_OS_WINDOWS_MOBILE
1136

shiqian's avatar
shiqian committed
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
#endif  // GTEST_OS_WINDOWS

// Tests TestProperty construction.
TEST(TestPropertyTest, StringValue) {
  TestProperty property("key", "1");
  EXPECT_STREQ("key", property.key());
  EXPECT_STREQ("1", property.value());
}

// Tests TestProperty replacing a value.
TEST(TestPropertyTest, ReplaceStringValue) {
  TestProperty property("key", "1");
  EXPECT_STREQ("1", property.value());
  property.SetValue("2");
  EXPECT_STREQ("2", property.value());
}

1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
// functions (i.e. their definitions cannot be inlined at the call
// sites), or C++Builder won't compile the code.
static void AddFatalFailure() {
  FAIL() << "Expected fatal failure.";
}

static void AddNonfatalFailure() {
  ADD_FAILURE() << "Expected non-fatal failure.";
}

shiqian's avatar
shiqian committed
1165
class ScopedFakeTestPartResultReporterTest : public Test {
1166
 public:  // Must be public and not protected due to a bug in g++ 3.4.2.
shiqian's avatar
shiqian committed
1167
1168
1169
1170
1171
1172
  enum FailureMode {
    FATAL_FAILURE,
    NONFATAL_FAILURE
  };
  static void AddFailure(FailureMode failure) {
    if (failure == FATAL_FAILURE) {
1173
      AddFatalFailure();
shiqian's avatar
shiqian committed
1174
    } else {
1175
      AddNonfatalFailure();
shiqian's avatar
shiqian committed
1176
1177
    }
  }
shiqian's avatar
shiqian committed
1178
1179
};

shiqian's avatar
shiqian committed
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
// Tests that ScopedFakeTestPartResultReporter intercepts test
// failures.
TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
  TestPartResultArray results;
  {
    ScopedFakeTestPartResultReporter reporter(
        ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
        &results);
    AddFailure(NONFATAL_FAILURE);
    AddFailure(FATAL_FAILURE);
  }
shiqian's avatar
shiqian committed
1191

shiqian's avatar
shiqian committed
1192
1193
1194
  EXPECT_EQ(2, results.size());
  EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
  EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
shiqian's avatar
shiqian committed
1195
1196
}

shiqian's avatar
shiqian committed
1197
1198
1199
1200
1201
1202
1203
1204
TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
  TestPartResultArray results;
  {
    // Tests, that the deprecated constructor still works.
    ScopedFakeTestPartResultReporter reporter(&results);
    AddFailure(NONFATAL_FAILURE);
  }
  EXPECT_EQ(1, results.size());
shiqian's avatar
shiqian committed
1205
1206
}

1207
#if GTEST_IS_THREADSAFE
shiqian's avatar
shiqian committed
1208
1209
1210
1211
1212

class ScopedFakeTestPartResultReporterWithThreadsTest
  : public ScopedFakeTestPartResultReporterTest {
 protected:
  static void AddFailureInOtherThread(FailureMode failure) {
1213
    ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
1214
    thread.Join();
shiqian's avatar
shiqian committed
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
  }
};

TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
       InterceptsTestFailuresInAllThreads) {
  TestPartResultArray results;
  {
    ScopedFakeTestPartResultReporter reporter(
        ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
    AddFailure(NONFATAL_FAILURE);
    AddFailure(FATAL_FAILURE);
    AddFailureInOtherThread(NONFATAL_FAILURE);
    AddFailureInOtherThread(FATAL_FAILURE);
  }

  EXPECT_EQ(4, results.size());
  EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
  EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
  EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
  EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
shiqian's avatar
shiqian committed
1235
1236
}

1237
#endif  // GTEST_IS_THREADSAFE
shiqian's avatar
shiqian committed
1238

1239
1240
1241
// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}.  Makes sure that they
// work even if the failure is generated in a called function rather than
// the current context.
shiqian's avatar
shiqian committed
1242

1243
typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
shiqian's avatar
shiqian committed
1244

1245
TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1246
  EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
shiqian's avatar
shiqian committed
1247
1248
}

1249
1250
1251
1252
1253
TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
  EXPECT_FATAL_FAILURE(AddFatalFailure(),
                       ::std::string("Expected fatal failure."));
}

1254
1255
1256
TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
  // We have another test below to verify that the macro catches fatal
  // failures generated on another thread.
1257
  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
shiqian's avatar
shiqian committed
1258
                                      "Expected fatal failure.");
shiqian's avatar
shiqian committed
1259
1260
}

1261
1262
#ifdef __BORLANDC__
// Silences warnings: "Condition is always true"
1263
# pragma option push -w-ccc
1264
1265
#endif

1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
// function even when the statement in it contains ASSERT_*.

int NonVoidFunction() {
  EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
  return 0;
}

TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
  NonVoidFunction();
}

// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
// current function even though 'statement' generates a fatal failure.

void DoesNotAbortHelper(bool* aborted) {
  EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");

  *aborted = false;
}

1289
#ifdef __BORLANDC__
1290
// Restores warnings after previous "#pragma option push" suppressed them.
1291
# pragma option pop
1292
1293
#endif

1294
1295
1296
1297
TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
  bool aborted = true;
  DoesNotAbortHelper(&aborted);
  EXPECT_FALSE(aborted);
shiqian's avatar
shiqian committed
1298
1299
}

1300
1301
1302
// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
// statement that contains a macro which expands to code containing an
// unprotected comma.
shiqian's avatar
shiqian committed
1303

shiqian's avatar
shiqian committed
1304
1305
static int global_var = 0;
#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
shiqian's avatar
shiqian committed
1306

1307
TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1308
1309
#ifndef __BORLANDC__
  // ICE's in C++Builder.
shiqian's avatar
shiqian committed
1310
1311
  EXPECT_FATAL_FAILURE({
    GTEST_USE_UNPROTECTED_COMMA_;
1312
    AddFatalFailure();
shiqian's avatar
shiqian committed
1313
  }, "");
1314
#endif
shiqian's avatar
shiqian committed
1315

shiqian's avatar
shiqian committed
1316
1317
  EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
    GTEST_USE_UNPROTECTED_COMMA_;
1318
    AddFatalFailure();
shiqian's avatar
shiqian committed
1319
  }, "");
1320
1321
1322
1323
1324
1325
1326
}

// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.

typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;

TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1327
  EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1328
1329
                          "Expected non-fatal failure.");
}
shiqian's avatar
shiqian committed
1330

1331
1332
1333
1334
1335
TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
  EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
                          ::std::string("Expected non-fatal failure."));
}

1336
1337
1338
TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
  // We have another test below to verify that the macro catches
  // non-fatal failures generated on another thread.
1339
  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
1340
1341
1342
1343
1344
1345
1346
                                         "Expected non-fatal failure.");
}

// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
// statement that contains a macro which expands to code containing an
// unprotected comma.
TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
shiqian's avatar
shiqian committed
1347
1348
  EXPECT_NONFATAL_FAILURE({
    GTEST_USE_UNPROTECTED_COMMA_;
1349
    AddNonfatalFailure();
shiqian's avatar
shiqian committed
1350
  }, "");
shiqian's avatar
shiqian committed
1351

shiqian's avatar
shiqian committed
1352
1353
  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
    GTEST_USE_UNPROTECTED_COMMA_;
1354
    AddNonfatalFailure();
shiqian's avatar
shiqian committed
1355
  }, "");
shiqian's avatar
shiqian committed
1356
1357
}

1358
#if GTEST_IS_THREADSAFE
shiqian's avatar
shiqian committed
1359

shiqian's avatar
shiqian committed
1360
1361
typedef ScopedFakeTestPartResultReporterWithThreadsTest
    ExpectFailureWithThreadsTest;
shiqian's avatar
shiqian committed
1362

shiqian's avatar
shiqian committed
1363
1364
1365
1366
1367
1368
1369
1370
TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
                                      "Expected fatal failure.");
}

TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
      AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
shiqian's avatar
shiqian committed
1371
1372
}

1373
#endif  // GTEST_IS_THREADSAFE
shiqian's avatar
shiqian committed
1374

1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
// Tests the TestProperty class.

TEST(TestPropertyTest, ConstructorWorks) {
  const TestProperty property("key", "value");
  EXPECT_STREQ("key", property.key());
  EXPECT_STREQ("value", property.value());
}

TEST(TestPropertyTest, SetValue) {
  TestProperty property("key", "value_1");
  EXPECT_STREQ("key", property.key());
  property.SetValue("value_2");
  EXPECT_STREQ("key", property.key());
  EXPECT_STREQ("value_2", property.value());
}

shiqian's avatar
shiqian committed
1391
1392
1393
// Tests the TestResult class

// The test fixture for testing TestResult.
1394
class TestResultTest : public Test {
shiqian's avatar
shiqian committed
1395
 protected:
1396
  typedef std::vector<TestPartResult> TPRVector;
shiqian's avatar
shiqian committed
1397
1398
1399
1400
1401
1402
1403

  // We make use of 2 TestPartResult objects,
  TestPartResult * pr1, * pr2;

  // ... and 3 TestResult objects.
  TestResult * r0, * r1, * r2;

Abseil Team's avatar
Abseil Team committed
1404
  void SetUp() override {
shiqian's avatar
shiqian committed
1405
    // pr1 is for success.
1406
1407
1408
1409
    pr1 = new TestPartResult(TestPartResult::kSuccess,
                             "foo/bar.cc",
                             10,
                             "Success!");
shiqian's avatar
shiqian committed
1410
1411

    // pr2 is for fatal failure.
1412
1413
    pr2 = new TestPartResult(TestPartResult::kFatalFailure,
                             "foo/bar.cc",
1414
1415
                             -1,  // This line number means "unknown"
                             "Failure!");
shiqian's avatar
shiqian committed
1416
1417
1418
1419
1420
1421
1422

    // Creates the TestResult objects.
    r0 = new TestResult();
    r1 = new TestResult();
    r2 = new TestResult();

    // In order to test TestResult, we need to modify its internal
1423
1424
    // state, in particular the TestPartResult vector it holds.
    // test_part_results() returns a const reference to this vector.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
1425
    // We cast it to a non-const object s.t. it can be modified
1426
    TPRVector* results1 = const_cast<TPRVector*>(
1427
        &TestResultAccessor::test_part_results(*r1));
1428
    TPRVector* results2 = const_cast<TPRVector*>(
1429
        &TestResultAccessor::test_part_results(*r2));
shiqian's avatar
shiqian committed
1430
1431
1432
1433

    // r0 is an empty TestResult.

    // r1 contains a single SUCCESS TestPartResult.
1434
    results1->push_back(*pr1);
shiqian's avatar
shiqian committed
1435
1436

    // r2 contains a SUCCESS, and a FAILURE.
1437
1438
    results2->push_back(*pr1);
    results2->push_back(*pr2);
shiqian's avatar
shiqian committed
1439
1440
  }

Abseil Team's avatar
Abseil Team committed
1441
  void TearDown() override {
shiqian's avatar
shiqian committed
1442
1443
1444
1445
1446
1447
1448
    delete pr1;
    delete pr2;

    delete r0;
    delete r1;
    delete r2;
  }
1449

Li Peng's avatar
Li Peng committed
1450
  // Helper that compares two TestPartResults.
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
  static void CompareTestPartResult(const TestPartResult& expected,
                                    const TestPartResult& actual) {
    EXPECT_EQ(expected.type(), actual.type());
    EXPECT_STREQ(expected.file_name(), actual.file_name());
    EXPECT_EQ(expected.line_number(), actual.line_number());
    EXPECT_STREQ(expected.summary(), actual.summary());
    EXPECT_STREQ(expected.message(), actual.message());
    EXPECT_EQ(expected.passed(), actual.passed());
    EXPECT_EQ(expected.failed(), actual.failed());
    EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
    EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
1462
  }
shiqian's avatar
shiqian committed
1463
1464
};

1465
// Tests TestResult::total_part_count().
shiqian's avatar
shiqian committed
1466
TEST_F(TestResultTest, total_part_count) {
1467
1468
1469
  ASSERT_EQ(0, r0->total_part_count());
  ASSERT_EQ(1, r1->total_part_count());
  ASSERT_EQ(2, r2->total_part_count());
shiqian's avatar
shiqian committed
1470
1471
}

1472
// Tests TestResult::Passed().
shiqian's avatar
shiqian committed
1473
1474
1475
1476
1477
1478
TEST_F(TestResultTest, Passed) {
  ASSERT_TRUE(r0->Passed());
  ASSERT_TRUE(r1->Passed());
  ASSERT_FALSE(r2->Passed());
}

1479
// Tests TestResult::Failed().
shiqian's avatar
shiqian committed
1480
1481
1482
1483
1484
1485
TEST_F(TestResultTest, Failed) {
  ASSERT_FALSE(r0->Failed());
  ASSERT_FALSE(r1->Failed());
  ASSERT_TRUE(r2->Failed());
}

1486
// Tests TestResult::GetTestPartResult().
1487
1488
1489
1490
1491
1492

typedef TestResultTest TestResultDeathTest;

TEST_F(TestResultDeathTest, GetTestPartResult) {
  CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
  CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1493
1494
  EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
  EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
1495
1496
}

1497
// Tests TestResult has no properties when none are added.
shiqian's avatar
shiqian committed
1498
1499
TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
  TestResult test_result;
1500
  ASSERT_EQ(0, test_result.test_property_count());
shiqian's avatar
shiqian committed
1501
1502
}

1503
// Tests TestResult has the expected property when added.
shiqian's avatar
shiqian committed
1504
1505
1506
TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
  TestResult test_result;
  TestProperty property("key_1", "1");
1507
  TestResultAccessor::RecordProperty(&test_result, "testcase", property);
1508
  ASSERT_EQ(1, test_result.test_property_count());
1509
1510
1511
  const TestProperty& actual_property = test_result.GetTestProperty(0);
  EXPECT_STREQ("key_1", actual_property.key());
  EXPECT_STREQ("1", actual_property.value());
shiqian's avatar
shiqian committed
1512
1513
}

1514
// Tests TestResult has multiple properties when added.
shiqian's avatar
shiqian committed
1515
1516
1517
1518
TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
  TestResult test_result;
  TestProperty property_1("key_1", "1");
  TestProperty property_2("key_2", "2");
1519
1520
  TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
  TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1521
  ASSERT_EQ(2, test_result.test_property_count());
1522
1523
1524
  const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
  EXPECT_STREQ("key_1", actual_property_1.key());
  EXPECT_STREQ("1", actual_property_1.value());
shiqian's avatar
shiqian committed
1525

1526
1527
1528
  const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
  EXPECT_STREQ("key_2", actual_property_2.key());
  EXPECT_STREQ("2", actual_property_2.value());
shiqian's avatar
shiqian committed
1529
1530
}

1531
// Tests TestResult::RecordProperty() overrides values for duplicate keys.
shiqian's avatar
shiqian committed
1532
1533
1534
1535
1536
1537
TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
  TestResult test_result;
  TestProperty property_1_1("key_1", "1");
  TestProperty property_2_1("key_2", "2");
  TestProperty property_1_2("key_1", "12");
  TestProperty property_2_2("key_2", "22");
1538
1539
1540
1541
  TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
  TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
  TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
  TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
1542
1543

  ASSERT_EQ(2, test_result.test_property_count());
1544
1545
1546
  const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
  EXPECT_STREQ("key_1", actual_property_1.key());
  EXPECT_STREQ("12", actual_property_1.value());
1547

1548
1549
1550
  const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
  EXPECT_STREQ("key_2", actual_property_2.key());
  EXPECT_STREQ("22", actual_property_2.value());
1551
1552
1553
}

// Tests TestResult::GetTestProperty().
1554
TEST(TestResultPropertyTest, GetTestProperty) {
1555
1556
1557
1558
  TestResult test_result;
  TestProperty property_1("key_1", "1");
  TestProperty property_2("key_2", "2");
  TestProperty property_3("key_3", "3");
1559
1560
1561
  TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
  TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
  TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
1562

1563
1564
1565
  const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
  const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
  const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
1566

1567
1568
  EXPECT_STREQ("key_1", fetched_property_1.key());
  EXPECT_STREQ("1", fetched_property_1.value());
1569

1570
1571
  EXPECT_STREQ("key_2", fetched_property_2.key());
  EXPECT_STREQ("2", fetched_property_2.value());
1572

1573
1574
  EXPECT_STREQ("key_3", fetched_property_3.key());
  EXPECT_STREQ("3", fetched_property_3.value());
1575

1576
1577
  EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
  EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
1578
1579
}

kosak's avatar
kosak committed
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
// Tests the Test class.
//
// It's difficult to test every public method of this class (we are
// already stretching the limit of Google Test by using it to test itself!).
// Fortunately, we don't have to do that, as we are already testing
// the functionalities of the Test class extensively by using Google Test
// alone.
//
// Therefore, this section only contains one test.

shiqian's avatar
shiqian committed
1590
1591
// Tests that GTestFlagSaver works on Windows and Mac.

1592
class GTestFlagSaverTest : public Test {
shiqian's avatar
shiqian committed
1593
1594
1595
1596
 protected:
  // Saves the Google Test flags such that we can restore them later, and
  // then sets them to their default values.  This will be called
  // before the first test in this test case is run.
misterg's avatar
misterg committed
1597
  static void SetUpTestSuite() {
1598
1599
    saver_ = new GTestFlagSaver;

1600
    GTEST_FLAG(also_run_disabled_tests) = false;
1601
1602
    GTEST_FLAG(break_on_failure) = false;
    GTEST_FLAG(catch_exceptions) = false;
1603
    GTEST_FLAG(death_test_use_fork) = false;
1604
1605
1606
1607
    GTEST_FLAG(color) = "auto";
    GTEST_FLAG(filter) = "";
    GTEST_FLAG(list_tests) = false;
    GTEST_FLAG(output) = "";
1608
    GTEST_FLAG(print_time) = true;
1609
    GTEST_FLAG(random_seed) = 0;
1610
    GTEST_FLAG(repeat) = 1;
1611
    GTEST_FLAG(shuffle) = false;
1612
    GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
1613
    GTEST_FLAG(stream_result_to) = "";
1614
    GTEST_FLAG(throw_on_failure) = false;
shiqian's avatar
shiqian committed
1615
1616
1617
1618
  }

  // Restores the Google Test flags that the tests have modified.  This will
  // be called after the last test in this test case is run.
misterg's avatar
misterg committed
1619
  static void TearDownTestSuite() {
shiqian's avatar
shiqian committed
1620
    delete saver_;
1621
    saver_ = nullptr;
shiqian's avatar
shiqian committed
1622
1623
1624
1625
1626
  }

  // Verifies that the Google Test flags have their default values, and then
  // modifies each of them.
  void VerifyAndModifyFlags() {
1627
    EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
1628
1629
1630
    EXPECT_FALSE(GTEST_FLAG(break_on_failure));
    EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
    EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
1631
    EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
1632
1633
1634
    EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
    EXPECT_FALSE(GTEST_FLAG(list_tests));
    EXPECT_STREQ("", GTEST_FLAG(output).c_str());
1635
    EXPECT_TRUE(GTEST_FLAG(print_time));
1636
    EXPECT_EQ(0, GTEST_FLAG(random_seed));
1637
    EXPECT_EQ(1, GTEST_FLAG(repeat));
1638
    EXPECT_FALSE(GTEST_FLAG(shuffle));
1639
    EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
1640
    EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
1641
    EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
1642

1643
    GTEST_FLAG(also_run_disabled_tests) = true;
1644
1645
1646
    GTEST_FLAG(break_on_failure) = true;
    GTEST_FLAG(catch_exceptions) = true;
    GTEST_FLAG(color) = "no";
1647
    GTEST_FLAG(death_test_use_fork) = true;
1648
1649
1650
    GTEST_FLAG(filter) = "abc";
    GTEST_FLAG(list_tests) = true;
    GTEST_FLAG(output) = "xml:foo.xml";
1651
    GTEST_FLAG(print_time) = false;
1652
    GTEST_FLAG(random_seed) = 1;
1653
    GTEST_FLAG(repeat) = 100;
1654
    GTEST_FLAG(shuffle) = true;
1655
    GTEST_FLAG(stack_trace_depth) = 1;
1656
    GTEST_FLAG(stream_result_to) = "localhost:1234";
1657
    GTEST_FLAG(throw_on_failure) = true;
shiqian's avatar
shiqian committed
1658
  }
1659

shiqian's avatar
shiqian committed
1660
1661
 private:
  // For saving Google Test flags during this test case.
1662
  static GTestFlagSaver* saver_;
shiqian's avatar
shiqian committed
1663
1664
};

1665
GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;
shiqian's avatar
shiqian committed
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684

// Google Test doesn't guarantee the order of tests.  The following two
// tests are designed to work regardless of their order.

// Modifies the Google Test flags in the test body.
TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
  VerifyAndModifyFlags();
}

// Verifies that the Google Test flags in the body of the previous test were
// restored to their original values.
TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
  VerifyAndModifyFlags();
}

// Sets an environment variable with the given name to the given
// value.  If the value argument is "", unsets the environment
// variable.  The caller must ensure that both arguments are not NULL.
static void SetEnv(const char* name, const char* value) {
1685
#if GTEST_OS_WINDOWS_MOBILE
shiqian's avatar
shiqian committed
1686
1687
  // Environment variables are not supported on Windows CE.
  return;
1688
#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1689
1690
1691
  // C++Builder's putenv only stores a pointer to its parameter; we have to
  // ensure that the string remains valid as long as it might be needed.
  // We use an std::map to do so.
1692
  static std::map<std::string, std::string*> added_env;
1693
1694
1695

  // Because putenv stores a pointer to the string buffer, we can't delete the
  // previous string (if present) until after it's replaced.
1696
  std::string *prev_env = NULL;
1697
1698
1699
  if (added_env.find(name) != added_env.end()) {
    prev_env = added_env[name];
  }
1700
1701
  added_env[name] = new std::string(
      (Message() << name << "=" << value).GetString());
1702
1703
1704
1705
1706

  // The standard signature of putenv accepts a 'char*' argument. Other
  // implementations, like C++Builder's, accept a 'const char*'.
  // We cast away the 'const' since that would work for both variants.
  putenv(const_cast<char*>(added_env[name]->c_str()));
1707
  delete prev_env;
zhanyong.wan's avatar
zhanyong.wan committed
1708
#elif GTEST_OS_WINDOWS  // If we are on Windows proper.
1709
  _putenv((Message() << name << "=" << value).GetString().c_str());
shiqian's avatar
shiqian committed
1710
1711
1712
1713
1714
1715
#else
  if (*value == '\0') {
    unsetenv(name);
  } else {
    setenv(name, value, 1);
  }
1716
#endif  // GTEST_OS_WINDOWS_MOBILE
shiqian's avatar
shiqian committed
1717
1718
}

1719
#if !GTEST_OS_WINDOWS_MOBILE
shiqian's avatar
shiqian committed
1720
1721
// Environment variables are not supported on Windows CE.

1722
using testing::internal::Int32FromGTestEnv;
shiqian's avatar
shiqian committed
1723
1724
1725
1726
1727
1728

// Tests Int32FromGTestEnv().

// Tests that Int32FromGTestEnv() returns the default value when the
// environment variable is not set.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
zhanyong.wan's avatar
zhanyong.wan committed
1729
  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
shiqian's avatar
shiqian committed
1730
1731
1732
  EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
}

1733
1734
# if !defined(GTEST_GET_INT32_FROM_ENV_)

shiqian's avatar
shiqian committed
1735
1736
1737
1738
1739
// Tests that Int32FromGTestEnv() returns the default value when the
// environment variable overflows as an Int32.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
  printf("(expecting 2 warnings)\n");

zhanyong.wan's avatar
zhanyong.wan committed
1740
  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
shiqian's avatar
shiqian committed
1741
1742
  EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));

zhanyong.wan's avatar
zhanyong.wan committed
1743
  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
shiqian's avatar
shiqian committed
1744
1745
1746
1747
1748
1749
1750
1751
  EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
}

// Tests that Int32FromGTestEnv() returns the default value when the
// environment variable does not represent a valid decimal integer.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
  printf("(expecting 2 warnings)\n");

zhanyong.wan's avatar
zhanyong.wan committed
1752
  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
shiqian's avatar
shiqian committed
1753
1754
  EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));

zhanyong.wan's avatar
zhanyong.wan committed
1755
  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
shiqian's avatar
shiqian committed
1756
1757
1758
  EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
}

1759
1760
# endif  // !defined(GTEST_GET_INT32_FROM_ENV_)

shiqian's avatar
shiqian committed
1761
1762
1763
1764
// Tests that Int32FromGTestEnv() parses and returns the value of the
// environment variable when it represents a valid decimal integer in
// the range of an Int32.
TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
zhanyong.wan's avatar
zhanyong.wan committed
1765
  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
shiqian's avatar
shiqian committed
1766
1767
  EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));

zhanyong.wan's avatar
zhanyong.wan committed
1768
  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
shiqian's avatar
shiqian committed
1769
1770
  EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
}
1771
#endif  // !GTEST_OS_WINDOWS_MOBILE
shiqian's avatar
shiqian committed
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817

// Tests ParseInt32Flag().

// Tests that ParseInt32Flag() returns false and doesn't change the
// output value when the flag has wrong format
TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
  Int32 value = 123;
  EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
  EXPECT_EQ(123, value);

  EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
  EXPECT_EQ(123, value);
}

// Tests that ParseInt32Flag() returns false and doesn't change the
// output value when the flag overflows as an Int32.
TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
  printf("(expecting 2 warnings)\n");

  Int32 value = 123;
  EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
  EXPECT_EQ(123, value);

  EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
  EXPECT_EQ(123, value);
}

// Tests that ParseInt32Flag() returns false and doesn't change the
// output value when the flag does not represent a valid decimal
// integer.
TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
  printf("(expecting 2 warnings)\n");

  Int32 value = 123;
  EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
  EXPECT_EQ(123, value);

  EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
  EXPECT_EQ(123, value);
}

// Tests that ParseInt32Flag() parses the value of the flag and
// returns true when the flag represents a valid decimal integer in
// the range of an Int32.
TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
  Int32 value = 123;
zhanyong.wan's avatar
zhanyong.wan committed
1818
  EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
shiqian's avatar
shiqian committed
1819
1820
  EXPECT_EQ(456, value);

1821
1822
  EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
                             "abc", &value));
shiqian's avatar
shiqian committed
1823
1824
1825
  EXPECT_EQ(-789, value);
}

1826
1827
// Tests that Int32FromEnvOrDie() parses the value of the var or
// returns the correct default.
1828
// Environment variables are not supported on Windows CE.
1829
#if !GTEST_OS_WINDOWS_MOBILE
1830
TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
zhanyong.wan's avatar
zhanyong.wan committed
1831
1832
1833
1834
1835
  EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
  EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
  EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1836
}
1837
#endif  // !GTEST_OS_WINDOWS_MOBILE
1838
1839
1840
1841

// Tests that Int32FromEnvOrDie() aborts with an error message
// if the variable is not an Int32.
TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
zhanyong.wan's avatar
zhanyong.wan committed
1842
  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1843
  EXPECT_DEATH_IF_SUPPORTED(
1844
1845
      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
      ".*");
1846
1847
1848
}

// Tests that Int32FromEnvOrDie() aborts with an error message
Troy Holsapple's avatar
Troy Holsapple committed
1849
// if the variable cannot be represented by an Int32.
1850
TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
zhanyong.wan's avatar
zhanyong.wan committed
1851
  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1852
  EXPECT_DEATH_IF_SUPPORTED(
1853
1854
      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
      ".*");
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
}

// Tests that ShouldRunTestOnShard() selects all tests
// where there is 1 shard.
TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
}

class ShouldShardTest : public testing::Test {
 protected:
Abseil Team's avatar
Abseil Team committed
1869
  void SetUp() override {
zhanyong.wan's avatar
zhanyong.wan committed
1870
1871
    index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
    total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1872
1873
  }

Abseil Team's avatar
Abseil Team committed
1874
  void TearDown() override {
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
    SetEnv(index_var_, "");
    SetEnv(total_var_, "");
  }

  const char* index_var_;
  const char* total_var_;
};

// Tests that sharding is disabled if neither of the environment variables
// are set.
TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
  SetEnv(index_var_, "");
  SetEnv(total_var_, "");

  EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
}

// Tests that sharding is not enabled if total_shards  == 1.
TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
  SetEnv(index_var_, "0");
  SetEnv(total_var_, "1");
  EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
}

// Tests that sharding is enabled if total_shards > 1 and
// we are not in a death test subprocess.
1903
// Environment variables are not supported on Windows CE.
1904
#if !GTEST_OS_WINDOWS_MOBILE
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
  SetEnv(index_var_, "4");
  SetEnv(total_var_, "22");
  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));

  SetEnv(index_var_, "8");
  SetEnv(total_var_, "9");
  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));

  SetEnv(index_var_, "0");
  SetEnv(total_var_, "9");
  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
}
1921
#endif  // !GTEST_OS_WINDOWS_MOBILE
1922
1923

// Tests that we exit in error if the sharding values are not valid.
1924
1925
1926
1927

typedef ShouldShardTest ShouldShardDeathTest;

TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
1928
1929
  SetEnv(index_var_, "4");
  SetEnv(total_var_, "4");
1930
  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1931
1932
1933

  SetEnv(index_var_, "4");
  SetEnv(total_var_, "-2");
1934
  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1935
1936
1937

  SetEnv(index_var_, "5");
  SetEnv(total_var_, "");
1938
  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1939
1940
1941

  SetEnv(index_var_, "");
  SetEnv(total_var_, "5");
1942
  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
}

// Tests that ShouldRunTestOnShard is a partition when 5
// shards are used.
TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
  // Choose an arbitrary number of tests and shards.
  const int num_tests = 17;
  const int num_shards = 5;

  // Check partitioning: each test should be on exactly 1 shard.
  for (int test_id = 0; test_id < num_tests; test_id++) {
    int prev_selected_shard_index = -1;
    for (int shard_index = 0; shard_index < num_shards; shard_index++) {
      if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
        if (prev_selected_shard_index < 0) {
          prev_selected_shard_index = shard_index;
        } else {
          ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
            << shard_index << " are both selected to run test " << test_id;
        }
      }
    }
  }

  // Check balance: This is not required by the sharding protocol, but is a
  // desirable property for performance.
  for (int shard_index = 0; shard_index < num_shards; shard_index++) {
    int num_tests_on_shard = 0;
    for (int test_id = 0; test_id < num_tests; test_id++) {
      num_tests_on_shard +=
        ShouldRunTestOnShard(num_shards, shard_index, test_id);
    }
    EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
  }
}

shiqian's avatar
shiqian committed
1979
// For the same reason we are not explicitly testing everything in the
1980
1981
// Test class, there are no separate tests for the following classes
// (except for some trivial cases):
shiqian's avatar
shiqian committed
1982
//
misterg's avatar
misterg committed
1983
//   TestSuite, UnitTest, UnitTestResultPrinter.
shiqian's avatar
shiqian committed
1984
1985
1986
1987
1988
//
// Similarly, there are no separate tests for the following macros:
//
//   TEST, TEST_F, RUN_ALL_TESTS

1989
TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1990
  ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr);
1991
1992
1993
  EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
}

1994
1995
1996
1997
1998
TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
  EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
  EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
}

1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
// When a property using a reserved key is supplied to this function, it
// tests that a non-fatal failure is added, a fatal failure is not added,
// and that the property is not recorded.
void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
    const TestResult& test_result, const char* key) {
  EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
  ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
                                                  << "' recorded unexpectedly.";
}

void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
    const char* key) {
  const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
2012
  ASSERT_TRUE(test_info != nullptr);
2013
2014
2015
2016
  ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
                                                        key);
}

misterg's avatar
misterg committed
2017
void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2018
2019
    const char* key) {
  const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
2020
  ASSERT_TRUE(test_case != nullptr);
2021
2022
2023
2024
  ExpectNonFatalFailureRecordingPropertyWithReservedKey(
      test_case->ad_hoc_test_result(), key);
}

misterg's avatar
misterg committed
2025
void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
    const char* key) {
  ExpectNonFatalFailureRecordingPropertyWithReservedKey(
      UnitTest::GetInstance()->ad_hoc_test_result(), key);
}

// Tests that property recording functions in UnitTest outside of tests
// functions correcly.  Creating a separate instance of UnitTest ensures it
// is in a state similar to the UnitTest's singleton's between tests.
class UnitTestRecordPropertyTest :
    public testing::internal::UnitTestRecordPropertyTestHelper {
 public:
misterg's avatar
misterg committed
2037
2038
  static void SetUpTestSuite() {
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2039
        "disabled");
misterg's avatar
misterg committed
2040
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2041
        "errors");
misterg's avatar
misterg committed
2042
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2043
        "failures");
misterg's avatar
misterg committed
2044
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2045
        "name");
misterg's avatar
misterg committed
2046
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2047
        "tests");
misterg's avatar
misterg committed
2048
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2049
2050
2051
        "time");

    Test::RecordProperty("test_case_key_1", "1");
misterg's avatar
misterg committed
2052
2053
2054
    const testing::TestSuite* test_suite =
        UnitTest::GetInstance()->current_test_case();
    ASSERT_TRUE(test_suite != nullptr);
2055

misterg's avatar
misterg committed
2056
    ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count());
2057
    EXPECT_STREQ("test_case_key_1",
misterg's avatar
misterg committed
2058
                 test_suite->ad_hoc_test_result().GetTestProperty(0).key());
2059
    EXPECT_STREQ("1",
misterg's avatar
misterg committed
2060
                 test_suite->ad_hoc_test_result().GetTestProperty(0).value());
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
  }
};

// Tests TestResult has the expected property when added.
TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
  UnitTestRecordProperty("key_1", "1");

  ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());

  EXPECT_STREQ("key_1",
               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
  EXPECT_STREQ("1",
               unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
}

// Tests TestResult has multiple properties when added.
TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
  UnitTestRecordProperty("key_1", "1");
  UnitTestRecordProperty("key_2", "2");

  ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());

  EXPECT_STREQ("key_1",
               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
  EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());

  EXPECT_STREQ("key_2",
               unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
  EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
}

// Tests TestResult::RecordProperty() overrides values for duplicate keys.
TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
  UnitTestRecordProperty("key_1", "1");
  UnitTestRecordProperty("key_2", "2");
  UnitTestRecordProperty("key_1", "12");
  UnitTestRecordProperty("key_2", "22");

  ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());

  EXPECT_STREQ("key_1",
               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
  EXPECT_STREQ("12",
               unit_test_.ad_hoc_test_result().GetTestProperty(0).value());

  EXPECT_STREQ("key_2",
               unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
  EXPECT_STREQ("22",
               unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
}

TEST_F(UnitTestRecordPropertyTest,
misterg's avatar
misterg committed
2113
       AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
      "name");
  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
      "value_param");
  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
      "type_param");
  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
      "status");
  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
      "time");
  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
      "classname");
}

TEST_F(UnitTestRecordPropertyTest,
       AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
  EXPECT_NONFATAL_FAILURE(
      Test::RecordProperty("name", "1"),
2132
2133
      "'classname', 'name', 'status', 'time', 'type_param', 'value_param',"
      " 'file', and 'line' are reserved");
2134
2135
2136
2137
}

class UnitTestRecordPropertyTestEnvironment : public Environment {
 public:
Abseil Team's avatar
Abseil Team committed
2138
  void TearDown() override {
misterg's avatar
misterg committed
2139
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2140
        "tests");
misterg's avatar
misterg committed
2141
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2142
        "failures");
misterg's avatar
misterg committed
2143
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2144
        "disabled");
misterg's avatar
misterg committed
2145
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2146
        "errors");
misterg's avatar
misterg committed
2147
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2148
        "name");
misterg's avatar
misterg committed
2149
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2150
        "timestamp");
misterg's avatar
misterg committed
2151
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2152
        "time");
misterg's avatar
misterg committed
2153
    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2154
2155
2156
2157
2158
        "random_seed");
  }
};

// This will test property recording outside of any test or test case.
2159
static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ =
2160
2161
    AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);

shiqian's avatar
shiqian committed
2162
2163
2164
2165
2166
2167
2168
2169
// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
// of various arities.  They do not attempt to be exhaustive.  Rather,
// view them as smoke tests that can be easily reviewed and verified.
// A more complete set of tests for predicate assertions can be found
// in gtest_pred_impl_unittest.cc.

// First, some predicates and predicate-formatters needed by the tests.

Krystian Kuzniarek's avatar
Krystian Kuzniarek committed
2170
// Returns true if the argument is an even number.
shiqian's avatar
shiqian committed
2171
2172
2173
2174
bool IsEven(int n) {
  return (n % 2) == 0;
}

Krystian Kuzniarek's avatar
Krystian Kuzniarek committed
2175
// A functor that returns true if the argument is an even number.
shiqian's avatar
shiqian committed
2176
2177
2178
2179
2180
2181
struct IsEvenFunctor {
  bool operator()(int n) { return IsEven(n); }
};

// A predicate-formatter function that asserts the argument is an even
// number.
2182
AssertionResult AssertIsEven(const char* expr, int n) {
shiqian's avatar
shiqian committed
2183
  if (IsEven(n)) {
2184
    return AssertionSuccess();
shiqian's avatar
shiqian committed
2185
2186
  }

2187
  Message msg;
shiqian's avatar
shiqian committed
2188
  msg << expr << " evaluates to " << n << ", which is not even.";
2189
  return AssertionFailure(msg);
shiqian's avatar
shiqian committed
2190
2191
}

2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
// A predicate function that returns AssertionResult for use in
// EXPECT/ASSERT_TRUE/FALSE.
AssertionResult ResultIsEven(int n) {
  if (IsEven(n))
    return AssertionSuccess() << n << " is even";
  else
    return AssertionFailure() << n << " is odd";
}

// A predicate function that returns AssertionResult but gives no
// explanation why it succeeds. Needed for testing that
// EXPECT/ASSERT_FALSE handles such functions correctly.
AssertionResult ResultIsEvenNoExplanation(int n) {
  if (IsEven(n))
    return AssertionSuccess();
  else
    return AssertionFailure() << n << " is odd";
}

shiqian's avatar
shiqian committed
2211
2212
2213
// A predicate-formatter functor that asserts the argument is an even
// number.
struct AssertIsEvenFunctor {
2214
  AssertionResult operator()(const char* expr, int n) {
shiqian's avatar
shiqian committed
2215
2216
2217
2218
    return AssertIsEven(expr, n);
  }
};

Krystian Kuzniarek's avatar
Krystian Kuzniarek committed
2219
// Returns true if the sum of the arguments is an even number.
shiqian's avatar
shiqian committed
2220
2221
2222
2223
bool SumIsEven2(int n1, int n2) {
  return IsEven(n1 + n2);
}

Krystian Kuzniarek's avatar
Krystian Kuzniarek committed
2224
// A functor that returns true if the sum of the arguments is an even
shiqian's avatar
shiqian committed
2225
2226
2227
2228
2229
2230
2231
2232
2233
// number.
struct SumIsEven3Functor {
  bool operator()(int n1, int n2, int n3) {
    return IsEven(n1 + n2 + n3);
  }
};

// A predicate-formatter function that asserts the sum of the
// arguments is an even number.
2234
2235
2236
AssertionResult AssertSumIsEven4(
    const char* e1, const char* e2, const char* e3, const char* e4,
    int n1, int n2, int n3, int n4) {
shiqian's avatar
shiqian committed
2237
2238
  const int sum = n1 + n2 + n3 + n4;
  if (IsEven(sum)) {
2239
    return AssertionSuccess();
shiqian's avatar
shiqian committed
2240
2241
  }

2242
  Message msg;
shiqian's avatar
shiqian committed
2243
2244
2245
  msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
      << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
      << ") evaluates to " << sum << ", which is not even.";
2246
  return AssertionFailure(msg);
shiqian's avatar
shiqian committed
2247
2248
2249
2250
2251
}

// A predicate-formatter functor that asserts the sum of the arguments
// is an even number.
struct AssertSumIsEven5Functor {
2252
2253
2254
  AssertionResult operator()(
      const char* e1, const char* e2, const char* e3, const char* e4,
      const char* e5, int n1, int n2, int n3, int n4, int n5) {
shiqian's avatar
shiqian committed
2255
2256
    const int sum = n1 + n2 + n3 + n4 + n5;
    if (IsEven(sum)) {
2257
      return AssertionSuccess();
shiqian's avatar
shiqian committed
2258
2259
    }

2260
    Message msg;
shiqian's avatar
shiqian committed
2261
2262
2263
2264
    msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
        << " ("
        << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
        << ") evaluates to " << sum << ", which is not even.";
2265
    return AssertionFailure(msg);
shiqian's avatar
shiqian committed
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
  }
};


// Tests unary predicate assertions.

// Tests unary predicate assertions that don't use a custom formatter.
TEST(Pred1Test, WithoutFormat) {
  // Success cases.
  EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
  ASSERT_PRED1(IsEven, 4);

  // Failure cases.
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
  }, "This failure is expected.");
  EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
                       "evaluates to false");
}

// Tests unary predicate assertions that use a custom formatter.
TEST(Pred1Test, WithFormat) {
  // Success cases.
  EXPECT_PRED_FORMAT1(AssertIsEven, 2);
  ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
    << "This failure is UNEXPECTED!";

  // Failure cases.
  const int n = 5;
  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
                          "n evaluates to 5, which is not even.");
  EXPECT_FATAL_FAILURE({  // NOLINT
    ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
  }, "This failure is expected.");
}

// Tests that unary predicate assertions evaluates their arguments
// exactly once.
TEST(Pred1Test, SingleEvaluationOnFailure) {
  // A success case.
  static int n = 0;
  EXPECT_PRED1(IsEven, n++);
  EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";

  // A failure case.
  EXPECT_FATAL_FAILURE({  // NOLINT
    ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
        << "This failure is expected.";
  }, "This failure is expected.");
  EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
}


// Tests predicate assertions whose arity is >= 2.

// Tests predicate assertions that don't use a custom formatter.
TEST(PredTest, WithoutFormat) {
  // Success cases.
  ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
  EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);

  // Failure cases.
  const int n1 = 1;
  const int n2 = 2;
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
  }, "This failure is expected.");
  EXPECT_FATAL_FAILURE({  // NOLINT
    ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
  }, "evaluates to false");
}

// Tests predicate assertions that use a custom formatter.
TEST(PredTest, WithFormat) {
  // Success cases.
  ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
    "This failure is UNEXPECTED!";
  EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);

  // Failure cases.
  const int n1 = 1;
  const int n2 = 2;
  const int n3 = 4;
  const int n4 = 6;
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
  }, "evaluates to 13, which is not even.");
  EXPECT_FATAL_FAILURE({  // NOLINT
    ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
        << "This failure is expected.";
  }, "This failure is expected.");
}

// Tests that predicate assertions evaluates their arguments
// exactly once.
TEST(PredTest, SingleEvaluationOnFailure) {
  // A success case.
  int n1 = 0;
  int n2 = 0;
  EXPECT_PRED2(SumIsEven2, n1++, n2++);
  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";

  // Another success case.
  n1 = n2 = 0;
  int n3 = 0;
  int n4 = 0;
  int n5 = 0;
  ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
                      n1++, n2++, n3++, n4++, n5++)
                        << "This failure is UNEXPECTED!";
  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
  EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
  EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";

  // A failure case.
  n1 = n2 = n3 = 0;
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
        << "This failure is expected.";
  }, "This failure is expected.");
  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";

  // Another failure case.
  n1 = n2 = n3 = n4 = 0;
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
  }, "evaluates to 1, which is not even.");
  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
  EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
}

misterg's avatar
misterg committed
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
// Test predicate assertions for sets
TEST(PredTest, ExpectPredEvalFailure) {
  std::set<int> set_a = {2, 1, 3, 4, 5};
  std::set<int> set_b = {0, 4, 8};
  const auto compare_sets = [] (std::set<int>, std::set<int>) { return false; };
  EXPECT_NONFATAL_FAILURE(
      EXPECT_PRED2(compare_sets, set_a, set_b),
      "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates "
      "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }");
}
shiqian's avatar
shiqian committed
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434

// Some helper functions for testing using overloaded/template
// functions with ASSERT_PREDn and EXPECT_PREDn.

bool IsPositive(double x) {
  return x > 0;
}

template <typename T>
bool IsNegative(T x) {
  return x < 0;
}

template <typename T1, typename T2>
bool GreaterThan(T1 x1, T2 x2) {
  return x1 > x2;
}

// Tests that overloaded functions can be used in *_PRED* as long as
// their types are explicitly specified.
TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2435
2436
2437
  // C++Builder requires C-style casts rather than static_cast.
  EXPECT_PRED1((bool (*)(int))(IsPositive), 5);  // NOLINT
  ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0);  // NOLINT
shiqian's avatar
shiqian committed
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
}

// Tests that template functions can be used in *_PRED* as long as
// their types are explicitly specified.
TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
  EXPECT_PRED1(IsNegative<int>, -5);
  // Makes sure that we can handle templates with more than one
  // parameter.
  ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
}


// Some helper functions for testing using overloaded/template
// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.

2453
AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2454
2455
  return n > 0 ? AssertionSuccess() :
      AssertionFailure(Message() << "Failure");
shiqian's avatar
shiqian committed
2456
2457
}

2458
AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2459
2460
  return x > 0 ? AssertionSuccess() :
      AssertionFailure(Message() << "Failure");
shiqian's avatar
shiqian committed
2461
2462
2463
}

template <typename T>
2464
AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2465
2466
  return x < 0 ? AssertionSuccess() :
      AssertionFailure(Message() << "Failure");
shiqian's avatar
shiqian committed
2467
2468
2469
}

template <typename T1, typename T2>
2470
AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2471
2472
2473
                             const T1& x1, const T2& x2) {
  return x1 == x2 ? AssertionSuccess() :
      AssertionFailure(Message() << "Failure");
shiqian's avatar
shiqian committed
2474
2475
2476
}

// Tests that overloaded functions can be used in *_PRED_FORMAT*
2477
// without explicitly specifying their types.
shiqian's avatar
shiqian committed
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
  EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
  ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
}

// Tests that template functions can be used in *_PRED_FORMAT* without
// explicitly specifying their types.
TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
  EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
  ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
}


// Tests string assertions.

// Tests ASSERT_STREQ with non-NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ) {
  const char * const p1 = "good";
  ASSERT_STREQ(p1, p1);

  // Let p2 have the same content as p1, but be at a different address.
  const char p2[] = "good";
  ASSERT_STREQ(p1, p2);

Gennadiy Civil's avatar
Gennadiy Civil committed
2502
2503
  EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
                       "  \"bad\"\n  \"good\"");
shiqian's avatar
shiqian committed
2504
2505
2506
2507
}

// Tests ASSERT_STREQ with NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2508
2509
  ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr);
  EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null");
shiqian's avatar
shiqian committed
2510
2511
2512
2513
}

// Tests ASSERT_STREQ with NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2514
  EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null");
shiqian's avatar
shiqian committed
2515
2516
2517
2518
2519
}

// Tests ASSERT_STRNE.
TEST(StringAssertionTest, ASSERT_STRNE) {
  ASSERT_STRNE("hi", "Hi");
2520
2521
2522
2523
  ASSERT_STRNE("Hi", nullptr);
  ASSERT_STRNE(nullptr, "Hi");
  ASSERT_STRNE("", nullptr);
  ASSERT_STRNE(nullptr, "");
shiqian's avatar
shiqian committed
2524
2525
2526
2527
2528
2529
2530
2531
2532
  ASSERT_STRNE("", "Hi");
  ASSERT_STRNE("Hi", "");
  EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
                       "\"Hi\" vs \"Hi\"");
}

// Tests ASSERT_STRCASEEQ.
TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
  ASSERT_STRCASEEQ("hi", "Hi");
2533
  ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);
shiqian's avatar
shiqian committed
2534
2535
2536

  ASSERT_STRCASEEQ("", "");
  EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2537
                       "Ignoring case");
shiqian's avatar
shiqian committed
2538
2539
2540
2541
2542
}

// Tests ASSERT_STRCASENE.
TEST(StringAssertionTest, ASSERT_STRCASENE) {
  ASSERT_STRCASENE("hi1", "Hi2");
2543
2544
2545
2546
  ASSERT_STRCASENE("Hi", nullptr);
  ASSERT_STRCASENE(nullptr, "Hi");
  ASSERT_STRCASENE("", nullptr);
  ASSERT_STRCASENE(nullptr, "");
shiqian's avatar
shiqian committed
2547
2548
2549
2550
2551
2552
2553
2554
2555
  ASSERT_STRCASENE("", "Hi");
  ASSERT_STRCASENE("Hi", "");
  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
                       "(ignoring case)");
}

// Tests *_STREQ on wide strings.
TEST(StringAssertionTest, STREQ_Wide) {
  // NULL strings.
2556
  ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr);
shiqian's avatar
shiqian committed
2557
2558
2559
2560
2561

  // Empty strings.
  ASSERT_STREQ(L"", L"");

  // Non-null vs NULL.
2562
  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null");
shiqian's avatar
shiqian committed
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573

  // Equal strings.
  EXPECT_STREQ(L"Hi", L"Hi");

  // Unequal strings.
  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
                          "Abc");

  // Strings containing wide characters.
  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
                          "abc");
2574
2575
2576
2577
2578

  // The streaming variation.
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
  }, "Expected failure");
shiqian's avatar
shiqian committed
2579
2580
2581
2582
2583
}

// Tests *_STRNE on wide strings.
TEST(StringAssertionTest, STRNE_Wide) {
  // NULL strings.
2584
2585
2586
2587
2588
  EXPECT_NONFATAL_FAILURE(
      {  // NOLINT
        EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr);
      },
      "");
shiqian's avatar
shiqian committed
2589
2590
2591
2592
2593
2594

  // Empty strings.
  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
                          "L\"\"");

  // Non-null vs NULL.
2595
  ASSERT_STRNE(L"non-null", nullptr);
shiqian's avatar
shiqian committed
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606

  // Equal strings.
  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
                          "L\"Hi\"");

  // Unequal strings.
  EXPECT_STRNE(L"abc", L"Abc");

  // Strings containing wide characters.
  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
                          "abc");
2607
2608
2609

  // The streaming variation.
  ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
shiqian's avatar
shiqian committed
2610
2611
2612
2613
2614
2615
2616
}

// Tests for ::testing::IsSubstring().

// Tests that IsSubstring() returns the correct result when the input
// argument type is const char*.
TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2617
2618
  EXPECT_FALSE(IsSubstring("", "", nullptr, "a"));
  EXPECT_FALSE(IsSubstring("", "", "b", nullptr));
shiqian's avatar
shiqian committed
2619
2620
  EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));

2621
  EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr));
shiqian's avatar
shiqian committed
2622
2623
2624
2625
2626
2627
  EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
}

// Tests that IsSubstring() returns the correct result when the input
// argument type is const wchar_t*.
TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2628
2629
  EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
  EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
shiqian's avatar
shiqian committed
2630
2631
  EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));

2632
2633
  EXPECT_TRUE(
      IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr));
shiqian's avatar
shiqian committed
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
  EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
}

// Tests that IsSubstring() generates the correct message when the input
// argument type is const char*.
TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
  EXPECT_STREQ("Value of: needle_expr\n"
               "  Actual: \"needle\"\n"
               "Expected: a substring of haystack_expr\n"
               "Which is: \"haystack\"",
2644
2645
               IsSubstring("needle_expr", "haystack_expr",
                           "needle", "haystack").failure_message());
shiqian's avatar
shiqian committed
2646
2647
2648
2649
2650
}

// Tests that IsSubstring returns the correct result when the input
// argument type is ::std::string.
TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2651
2652
  EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
  EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
shiqian's avatar
shiqian committed
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
}

#if GTEST_HAS_STD_WSTRING
// Tests that IsSubstring returns the correct result when the input
// argument type is ::std::wstring.
TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
  EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
  EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
}

// Tests that IsSubstring() generates the correct message when the input
// argument type is ::std::wstring.
TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
  EXPECT_STREQ("Value of: needle_expr\n"
               "  Actual: L\"needle\"\n"
               "Expected: a substring of haystack_expr\n"
               "Which is: L\"haystack\"",
2670
               IsSubstring(
shiqian's avatar
shiqian committed
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
                   "needle_expr", "haystack_expr",
                   ::std::wstring(L"needle"), L"haystack").failure_message());
}

#endif  // GTEST_HAS_STD_WSTRING

// Tests for ::testing::IsNotSubstring().

// Tests that IsNotSubstring() returns the correct result when the input
// argument type is const char*.
TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
  EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
  EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
}

// Tests that IsNotSubstring() returns the correct result when the input
// argument type is const wchar_t*.
TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
  EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
  EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
}

// Tests that IsNotSubstring() generates the correct message when the input
// argument type is const wchar_t*.
TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
  EXPECT_STREQ("Value of: needle_expr\n"
               "  Actual: L\"needle\"\n"
               "Expected: not a substring of haystack_expr\n"
               "Which is: L\"two needles\"",
2700
               IsNotSubstring(
shiqian's avatar
shiqian committed
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
                   "needle_expr", "haystack_expr",
                   L"needle", L"two needles").failure_message());
}

// Tests that IsNotSubstring returns the correct result when the input
// argument type is ::std::string.
TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
  EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
  EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
}

// Tests that IsNotSubstring() generates the correct message when the input
// argument type is ::std::string.
TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
  EXPECT_STREQ("Value of: needle_expr\n"
               "  Actual: \"needle\"\n"
               "Expected: not a substring of haystack_expr\n"
               "Which is: \"two needles\"",
2719
               IsNotSubstring(
shiqian's avatar
shiqian committed
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
                   "needle_expr", "haystack_expr",
                   ::std::string("needle"), "two needles").failure_message());
}

#if GTEST_HAS_STD_WSTRING

// Tests that IsNotSubstring returns the correct result when the input
// argument type is ::std::wstring.
TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
  EXPECT_FALSE(
      IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
  EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
}

#endif  // GTEST_HAS_STD_WSTRING

// Tests floating-point assertions.

template <typename RawType>
2739
class FloatingPointTest : public Test {
shiqian's avatar
shiqian committed
2740
 protected:
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
  // Pre-calculated numbers to be used by the tests.
  struct TestValues {
    RawType close_to_positive_zero;
    RawType close_to_negative_zero;
    RawType further_from_negative_zero;

    RawType close_to_one;
    RawType further_from_one;

    RawType infinity;
    RawType close_to_infinity;
    RawType further_from_infinity;

    RawType nan1;
    RawType nan2;
  };

shiqian's avatar
shiqian committed
2758
2759
2760
  typedef typename testing::internal::FloatingPoint<RawType> Floating;
  typedef typename Floating::Bits Bits;

Abseil Team's avatar
Abseil Team committed
2761
  void SetUp() override {
shiqian's avatar
shiqian committed
2762
2763
2764
2765
2766
2767
    const size_t max_ulps = Floating::kMaxUlps;

    // The bits that represent 0.0.
    const Bits zero_bits = Floating(0).bits();

    // Makes some numbers close to 0.0.
2768
2769
2770
    values_.close_to_positive_zero = Floating::ReinterpretBits(
        zero_bits + max_ulps/2);
    values_.close_to_negative_zero = -Floating::ReinterpretBits(
shiqian's avatar
shiqian committed
2771
        zero_bits + max_ulps - max_ulps/2);
2772
    values_.further_from_negative_zero = -Floating::ReinterpretBits(
shiqian's avatar
shiqian committed
2773
2774
2775
2776
2777
2778
        zero_bits + max_ulps + 1 - max_ulps/2);

    // The bits that represent 1.0.
    const Bits one_bits = Floating(1).bits();

    // Makes some numbers close to 1.0.
2779
2780
2781
    values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
    values_.further_from_one = Floating::ReinterpretBits(
        one_bits + max_ulps + 1);
shiqian's avatar
shiqian committed
2782
2783

    // +infinity.
2784
    values_.infinity = Floating::Infinity();
shiqian's avatar
shiqian committed
2785
2786

    // The bits that represent +infinity.
2787
    const Bits infinity_bits = Floating(values_.infinity).bits();
shiqian's avatar
shiqian committed
2788
2789

    // Makes some numbers close to infinity.
2790
2791
2792
    values_.close_to_infinity = Floating::ReinterpretBits(
        infinity_bits - max_ulps);
    values_.further_from_infinity = Floating::ReinterpretBits(
shiqian's avatar
shiqian committed
2793
2794
        infinity_bits - max_ulps - 1);

2795
2796
2797
2798
2799
2800
2801
    // Makes some NAN's.  Sets the most significant bit of the fraction so that
    // our NaN's are quiet; trying to process a signaling NaN would raise an
    // exception if our environment enables floating point exceptions.
    values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
        | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
    values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
        | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
shiqian's avatar
shiqian committed
2802
2803
2804
2805
2806
2807
  }

  void TestSize() {
    EXPECT_EQ(sizeof(RawType), sizeof(Bits));
  }

2808
  static TestValues values_;
shiqian's avatar
shiqian committed
2809
2810
2811
};

template <typename RawType>
2812
2813
typename FloatingPointTest<RawType>::TestValues
    FloatingPointTest<RawType>::values_;
shiqian's avatar
shiqian committed
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837

// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
typedef FloatingPointTest<float> FloatTest;

// Tests that the size of Float::Bits matches the size of float.
TEST_F(FloatTest, Size) {
  TestSize();
}

// Tests comparing with +0 and -0.
TEST_F(FloatTest, Zeros) {
  EXPECT_FLOAT_EQ(0.0, -0.0);
  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
                          "1.0");
  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
                       "1.5");
}

// Tests comparing numbers close to 0.
//
// This ensures that *_FLOAT_EQ handles the sign correctly and no
// overflow occurs when comparing numbers whose absolute value is very
// small.
TEST_F(FloatTest, AlmostZeros) {
2838
2839
2840
  // In C++Builder, names within local classes (such as used by
  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  // scoping class.  Use a static local alias as a workaround.
2841
2842
2843
2844
  // We use the assignment syntax since some compilers, like Sun Studio,
  // don't allow initializing references using construction syntax
  // (parentheses).
  static const FloatTest::TestValues& v = this->values_;
2845
2846
2847
2848

  EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
  EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
  EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian's avatar
shiqian committed
2849
2850

  EXPECT_FATAL_FAILURE({  // NOLINT
2851
2852
2853
    ASSERT_FLOAT_EQ(v.close_to_positive_zero,
                    v.further_from_negative_zero);
  }, "v.further_from_negative_zero");
shiqian's avatar
shiqian committed
2854
2855
2856
2857
}

// Tests comparing numbers close to each other.
TEST_F(FloatTest, SmallDiff) {
2858
2859
2860
  EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
                          "values_.further_from_one");
shiqian's avatar
shiqian committed
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
}

// Tests comparing numbers far apart.
TEST_F(FloatTest, LargeDiff) {
  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
                          "3.0");
}

// Tests comparing with infinity.
//
// This ensures that no overflow occurs when comparing numbers whose
// absolute value is very large.
TEST_F(FloatTest, Infinity) {
2874
2875
2876
2877
  EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
  EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
                          "-values_.infinity");
shiqian's avatar
shiqian committed
2878

2879
  // This is interesting as the representations of infinity and nan1
shiqian's avatar
shiqian committed
2880
  // are only 1 DLP apart.
2881
2882
  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
                          "values_.nan1");
shiqian's avatar
shiqian committed
2883
2884
2885
2886
}

// Tests that comparing with NAN always returns false.
TEST_F(FloatTest, NaN) {
2887
2888
2889
  // In C++Builder, names within local classes (such as used by
  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  // scoping class.  Use a static local alias as a workaround.
2890
2891
2892
2893
  // We use the assignment syntax since some compilers, like Sun Studio,
  // don't allow initializing references using construction syntax
  // (parentheses).
  static const FloatTest::TestValues& v = this->values_;
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903

  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
                          "v.nan1");
  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
                          "v.nan2");
  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
                          "v.nan1");

  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
                       "v.infinity");
shiqian's avatar
shiqian committed
2904
2905
2906
2907
2908
2909
}

// Tests that *_FLOAT_EQ are reflexive.
TEST_F(FloatTest, Reflexive) {
  EXPECT_FLOAT_EQ(0.0, 0.0);
  EXPECT_FLOAT_EQ(1.0, 1.0);
2910
  ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
shiqian's avatar
shiqian committed
2911
2912
2913
2914
}

// Tests that *_FLOAT_EQ are commutative.
TEST_F(FloatTest, Commutative) {
2915
2916
  // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
  EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
shiqian's avatar
shiqian committed
2917

2918
2919
  // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
shiqian's avatar
shiqian committed
2920
2921
2922
2923
2924
2925
2926
                          "1.0");
}

// Tests EXPECT_NEAR.
TEST_F(FloatTest, EXPECT_NEAR) {
  EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
  EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2927
2928
2929
  EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f),  // NOLINT
                          "The difference between 1.0f and 1.5f is 0.5, "
                          "which exceeds 0.25f");
shiqian's avatar
shiqian committed
2930
2931
2932
2933
2934
2935
2936
2937
  // To work around a bug in gcc 2.95.0, there is intentionally no
  // space after the first comma in the previous line.
}

// Tests ASSERT_NEAR.
TEST_F(FloatTest, ASSERT_NEAR) {
  ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
  ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2938
2939
2940
  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f),  // NOLINT
                       "The difference between 1.0f and 1.5f is 0.5, "
                       "which exceeds 0.25f");
shiqian's avatar
shiqian committed
2941
2942
2943
2944
2945
2946
  // To work around a bug in gcc 2.95.0, there is intentionally no
  // space after the first comma in the previous line.
}

// Tests the cases where FloatLE() should succeed.
TEST_F(FloatTest, FloatLESucceeds) {
2947
2948
  EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f);  // When val1 < val2,
  ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f);  // val1 == val2,
shiqian's avatar
shiqian committed
2949
2950

  // or when val1 is greater than, but almost equals to, val2.
2951
  EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
shiqian's avatar
shiqian committed
2952
2953
2954
2955
2956
}

// Tests the cases where FloatLE() should fail.
TEST_F(FloatTest, FloatLEFails) {
  // When val1 is greater than val2 by a large margin,
2957
  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
shiqian's avatar
shiqian committed
2958
2959
2960
2961
                          "(2.0f) <= (1.0f)");

  // or by a small yet non-negligible margin,
  EXPECT_NONFATAL_FAILURE({  // NOLINT
2962
2963
    EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
  }, "(values_.further_from_one) <= (1.0f)");
shiqian's avatar
shiqian committed
2964
2965

  EXPECT_NONFATAL_FAILURE({  // NOLINT
2966
2967
    EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
  }, "(values_.nan1) <= (values_.infinity)");
shiqian's avatar
shiqian committed
2968
  EXPECT_NONFATAL_FAILURE({  // NOLINT
2969
2970
    EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
  }, "(-values_.infinity) <= (values_.nan1)");
shiqian's avatar
shiqian committed
2971
  EXPECT_FATAL_FAILURE({  // NOLINT
2972
2973
    ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
  }, "(values_.nan1) <= (values_.nan1)");
shiqian's avatar
shiqian committed
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
}

// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
typedef FloatingPointTest<double> DoubleTest;

// Tests that the size of Double::Bits matches the size of double.
TEST_F(DoubleTest, Size) {
  TestSize();
}

// Tests comparing with +0 and -0.
TEST_F(DoubleTest, Zeros) {
  EXPECT_DOUBLE_EQ(0.0, -0.0);
  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
                          "1.0");
  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
                       "1.0");
}

// Tests comparing numbers close to 0.
//
// This ensures that *_DOUBLE_EQ handles the sign correctly and no
// overflow occurs when comparing numbers whose absolute value is very
// small.
TEST_F(DoubleTest, AlmostZeros) {
2999
3000
3001
  // In C++Builder, names within local classes (such as used by
  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  // scoping class.  Use a static local alias as a workaround.
3002
3003
3004
3005
  // We use the assignment syntax since some compilers, like Sun Studio,
  // don't allow initializing references using construction syntax
  // (parentheses).
  static const DoubleTest::TestValues& v = this->values_;
3006
3007
3008
3009

  EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
  EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
  EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
shiqian's avatar
shiqian committed
3010
3011

  EXPECT_FATAL_FAILURE({  // NOLINT
3012
3013
3014
    ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
                     v.further_from_negative_zero);
  }, "v.further_from_negative_zero");
shiqian's avatar
shiqian committed
3015
3016
3017
3018
}

// Tests comparing numbers close to each other.
TEST_F(DoubleTest, SmallDiff) {
3019
3020
3021
  EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
                          "values_.further_from_one");
shiqian's avatar
shiqian committed
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
}

// Tests comparing numbers far apart.
TEST_F(DoubleTest, LargeDiff) {
  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
                          "3.0");
}

// Tests comparing with infinity.
//
// This ensures that no overflow occurs when comparing numbers whose
// absolute value is very large.
TEST_F(DoubleTest, Infinity) {
3035
3036
3037
3038
  EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
  EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
                          "-values_.infinity");
shiqian's avatar
shiqian committed
3039
3040
3041

  // This is interesting as the representations of infinity_ and nan1_
  // are only 1 DLP apart.
3042
3043
  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
                          "values_.nan1");
shiqian's avatar
shiqian committed
3044
3045
3046
3047
}

// Tests that comparing with NAN always returns false.
TEST_F(DoubleTest, NaN) {
3048
  static const DoubleTest::TestValues& v = this->values_;
3049

shiqian's avatar
shiqian committed
3050
  // Nokia's STLport crashes if we try to output infinity or NaN.
3051
3052
3053
3054
3055
3056
  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
                          "v.nan1");
  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
                       "v.infinity");
shiqian's avatar
shiqian committed
3057
3058
3059
3060
3061
3062
}

// Tests that *_DOUBLE_EQ are reflexive.
TEST_F(DoubleTest, Reflexive) {
  EXPECT_DOUBLE_EQ(0.0, 0.0);
  EXPECT_DOUBLE_EQ(1.0, 1.0);
3063
  ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
shiqian's avatar
shiqian committed
3064
3065
3066
3067
}

// Tests that *_DOUBLE_EQ are commutative.
TEST_F(DoubleTest, Commutative) {
3068
3069
  // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
  EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
shiqian's avatar
shiqian committed
3070

3071
3072
3073
  // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
                          "1.0");
shiqian's avatar
shiqian committed
3074
3075
3076
3077
3078
3079
}

// Tests EXPECT_NEAR.
TEST_F(DoubleTest, EXPECT_NEAR) {
  EXPECT_NEAR(-1.0, -1.1, 0.2);
  EXPECT_NEAR(2.0, 3.0, 1.0);
3080
3081
3082
  EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25),  // NOLINT
                          "The difference between 1.0 and 1.5 is 0.5, "
                          "which exceeds 0.25");
shiqian's avatar
shiqian committed
3083
3084
3085
3086
3087
3088
3089
3090
  // To work around a bug in gcc 2.95.0, there is intentionally no
  // space after the first comma in the previous statement.
}

// Tests ASSERT_NEAR.
TEST_F(DoubleTest, ASSERT_NEAR) {
  ASSERT_NEAR(-1.0, -1.1, 0.2);
  ASSERT_NEAR(2.0, 3.0, 1.0);
3091
3092
3093
  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25),  // NOLINT
                       "The difference between 1.0 and 1.5 is 0.5, "
                       "which exceeds 0.25");
shiqian's avatar
shiqian committed
3094
3095
3096
3097
3098
3099
  // To work around a bug in gcc 2.95.0, there is intentionally no
  // space after the first comma in the previous statement.
}

// Tests the cases where DoubleLE() should succeed.
TEST_F(DoubleTest, DoubleLESucceeds) {
3100
3101
  EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0);  // When val1 < val2,
  ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0);  // val1 == val2,
shiqian's avatar
shiqian committed
3102
3103

  // or when val1 is greater than, but almost equals to, val2.
3104
  EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
shiqian's avatar
shiqian committed
3105
3106
3107
3108
3109
}

// Tests the cases where DoubleLE() should fail.
TEST_F(DoubleTest, DoubleLEFails) {
  // When val1 is greater than val2 by a large margin,
3110
  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
shiqian's avatar
shiqian committed
3111
3112
3113
3114
                          "(2.0) <= (1.0)");

  // or by a small yet non-negligible margin,
  EXPECT_NONFATAL_FAILURE({  // NOLINT
3115
3116
    EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
  }, "(values_.further_from_one) <= (1.0)");
shiqian's avatar
shiqian committed
3117
3118

  EXPECT_NONFATAL_FAILURE({  // NOLINT
3119
3120
    EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
  }, "(values_.nan1) <= (values_.infinity)");
shiqian's avatar
shiqian committed
3121
  EXPECT_NONFATAL_FAILURE({  // NOLINT
3122
3123
    EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
  }, " (-values_.infinity) <= (values_.nan1)");
shiqian's avatar
shiqian committed
3124
  EXPECT_FATAL_FAILURE({  // NOLINT
3125
3126
    ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
  }, "(values_.nan1) <= (values_.nan1)");
shiqian's avatar
shiqian committed
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
}


// Verifies that a test or test case whose name starts with DISABLED_ is
// not run.

// A test whose name starts with DISABLED_.
// Should not run.
TEST(DisabledTest, DISABLED_TestShouldNotRun) {
  FAIL() << "Unexpected failure: Disabled test should not be run.";
}

// A test whose name does not start with DISABLED_.
// Should run.
TEST(DisabledTest, NotDISABLED_TestShouldRun) {
  EXPECT_EQ(1, 1);
}

// A test case whose name starts with DISABLED_.
// Should not run.
misterg's avatar
misterg committed
3147
TEST(DISABLED_TestSuite, TestShouldNotRun) {
shiqian's avatar
shiqian committed
3148
3149
3150
3151
3152
  FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
}

// A test case and test whose names start with DISABLED_.
// Should not run.
misterg's avatar
misterg committed
3153
TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {
shiqian's avatar
shiqian committed
3154
3155
3156
  FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
}

misterg's avatar
misterg committed
3157
3158
// Check that when all tests in a test case are disabled, SetUpTestSuite() and
// TearDownTestSuite() are not called.
3159
class DisabledTestsTest : public Test {
shiqian's avatar
shiqian committed
3160
 protected:
misterg's avatar
misterg committed
3161
  static void SetUpTestSuite() {
shiqian's avatar
shiqian committed
3162
    FAIL() << "Unexpected failure: All tests disabled in test case. "
misterg's avatar
misterg committed
3163
              "SetUpTestSuite() should not be called.";
shiqian's avatar
shiqian committed
3164
3165
  }

misterg's avatar
misterg committed
3166
  static void TearDownTestSuite() {
shiqian's avatar
shiqian committed
3167
    FAIL() << "Unexpected failure: All tests disabled in test case. "
misterg's avatar
misterg committed
3168
              "TearDownTestSuite() should not be called.";
shiqian's avatar
shiqian committed
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
  }
};

TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
  FAIL() << "Unexpected failure: Disabled test should not be run.";
}

TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
  FAIL() << "Unexpected failure: Disabled test should not be run.";
}

3180
3181
// Tests that disabled typed tests aren't run.

zhanyong.wan's avatar
zhanyong.wan committed
3182
#if GTEST_HAS_TYPED_TEST
3183
3184
3185
3186
3187
3188

template <typename T>
class TypedTest : public Test {
};

typedef testing::Types<int, double> NumericTypes;
misterg's avatar
misterg committed
3189
TYPED_TEST_SUITE(TypedTest, NumericTypes);
3190
3191
3192
3193
3194
3195
3196
3197
3198

TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
  FAIL() << "Unexpected failure: Disabled typed test should not run.";
}

template <typename T>
class DISABLED_TypedTest : public Test {
};

misterg's avatar
misterg committed
3199
TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
3200
3201
3202
3203
3204
3205
3206
3207
3208

TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
  FAIL() << "Unexpected failure: Disabled typed test should not run.";
}

#endif  // GTEST_HAS_TYPED_TEST

// Tests that disabled type-parameterized tests aren't run.

zhanyong.wan's avatar
zhanyong.wan committed
3209
#if GTEST_HAS_TYPED_TEST_P
3210
3211
3212
3213
3214

template <typename T>
class TypedTestP : public Test {
};

misterg's avatar
misterg committed
3215
TYPED_TEST_SUITE_P(TypedTestP);
3216
3217
3218
3219
3220
3221

TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
  FAIL() << "Unexpected failure: "
         << "Disabled type-parameterized test should not run.";
}

misterg's avatar
misterg committed
3222
REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
3223

misterg's avatar
misterg committed
3224
INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);
3225
3226
3227
3228
3229

template <typename T>
class DISABLED_TypedTestP : public Test {
};

misterg's avatar
misterg committed
3230
TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
3231
3232
3233
3234
3235
3236

TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
  FAIL() << "Unexpected failure: "
         << "Disabled type-parameterized test should not run.";
}

misterg's avatar
misterg committed
3237
REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
3238

misterg's avatar
misterg committed
3239
INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
3240
3241

#endif  // GTEST_HAS_TYPED_TEST_P
shiqian's avatar
shiqian committed
3242
3243
3244

// Tests that assertion macros evaluate their arguments exactly once.

3245
class SingleEvaluationTest : public Test {
3246
 public:  // Must be public and not protected due to a bug in g++ 3.4.2.
shiqian's avatar
shiqian committed
3247
  // This helper function is needed by the FailedASSERT_STREQ test
3248
3249
  // below.  It's public to work around C++Builder's bug with scoping local
  // classes.
shiqian's avatar
shiqian committed
3250
3251
3252
3253
  static void CompareAndIncrementCharPtrs() {
    ASSERT_STREQ(p1_++, p2_++);
  }

3254
3255
  // This helper function is needed by the FailedASSERT_NE test below.  It's
  // public to work around C++Builder's bug with scoping local classes.
shiqian's avatar
shiqian committed
3256
3257
3258
3259
  static void CompareAndIncrementInts() {
    ASSERT_NE(a_++, b_++);
  }

3260
3261
3262
3263
3264
3265
3266
3267
 protected:
  SingleEvaluationTest() {
    p1_ = s1_;
    p2_ = s2_;
    a_ = 0;
    b_ = 0;
  }

shiqian's avatar
shiqian committed
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
  static const char* const s1_;
  static const char* const s2_;
  static const char* p1_;
  static const char* p2_;

  static int a_;
  static int b_;
};

const char* const SingleEvaluationTest::s1_ = "01234";
const char* const SingleEvaluationTest::s2_ = "abcde";
const char* SingleEvaluationTest::p1_;
const char* SingleEvaluationTest::p2_;
int SingleEvaluationTest::a_;
int SingleEvaluationTest::b_;

// Tests that when ASSERT_STREQ fails, it evaluates its arguments
// exactly once.
TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3287
  EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
shiqian's avatar
shiqian committed
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
                       "p2_++");
  EXPECT_EQ(s1_ + 1, p1_);
  EXPECT_EQ(s2_ + 1, p2_);
}

// Tests that string assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, ASSERT_STR) {
  // successful EXPECT_STRNE
  EXPECT_STRNE(p1_++, p2_++);
  EXPECT_EQ(s1_ + 1, p1_);
  EXPECT_EQ(s2_ + 1, p2_);

  // failed EXPECT_STRCASEEQ
  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3302
                          "Ignoring case");
shiqian's avatar
shiqian committed
3303
3304
3305
3306
3307
3308
3309
  EXPECT_EQ(s1_ + 2, p1_);
  EXPECT_EQ(s2_ + 2, p2_);
}

// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
// once.
TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3310
3311
  EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
                       "(a_++) != (b_++)");
shiqian's avatar
shiqian committed
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
  EXPECT_EQ(1, a_);
  EXPECT_EQ(1, b_);
}

// Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, OtherCases) {
  // successful EXPECT_TRUE
  EXPECT_TRUE(0 == a_++);  // NOLINT
  EXPECT_EQ(1, a_);

  // failed EXPECT_TRUE
  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
  EXPECT_EQ(2, a_);

  // successful EXPECT_GT
  EXPECT_GT(a_++, b_++);
  EXPECT_EQ(3, a_);
  EXPECT_EQ(1, b_);

  // failed EXPECT_LT
  EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
  EXPECT_EQ(4, a_);
  EXPECT_EQ(2, b_);

  // successful ASSERT_TRUE
  ASSERT_TRUE(0 < a_++);  // NOLINT
  EXPECT_EQ(5, a_);

  // successful ASSERT_GT
  ASSERT_GT(a_++, b_++);
  EXPECT_EQ(6, a_);
  EXPECT_EQ(3, b_);
}

3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
#if GTEST_HAS_EXCEPTIONS

void ThrowAnInteger() {
  throw 1;
}

// Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, ExceptionTests) {
  // successful EXPECT_THROW
  EXPECT_THROW({  // NOLINT
    a_++;
    ThrowAnInteger();
  }, int);
  EXPECT_EQ(1, a_);

  // failed EXPECT_THROW, throws different
  EXPECT_NONFATAL_FAILURE(EXPECT_THROW({  // NOLINT
    a_++;
    ThrowAnInteger();
  }, bool), "throws a different type");
  EXPECT_EQ(2, a_);

  // failed EXPECT_THROW, throws nothing
  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
  EXPECT_EQ(3, a_);

  // successful EXPECT_NO_THROW
  EXPECT_NO_THROW(a_++);
  EXPECT_EQ(4, a_);

  // failed EXPECT_NO_THROW
  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({  // NOLINT
    a_++;
    ThrowAnInteger();
  }), "it throws");
  EXPECT_EQ(5, a_);

  // successful EXPECT_ANY_THROW
  EXPECT_ANY_THROW({  // NOLINT
    a_++;
    ThrowAnInteger();
  });
  EXPECT_EQ(6, a_);

  // failed EXPECT_ANY_THROW
  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
  EXPECT_EQ(7, a_);
}

#endif  // GTEST_HAS_EXCEPTIONS
shiqian's avatar
shiqian committed
3396

shiqian's avatar
shiqian committed
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
class NoFatalFailureTest : public Test {
 protected:
  void Succeeds() {}
  void FailsNonFatal() {
    ADD_FAILURE() << "some non-fatal failure";
  }
  void Fails() {
    FAIL() << "some fatal failure";
  }

  void DoAssertNoFatalFailureOnFails() {
    ASSERT_NO_FATAL_FAILURE(Fails());
Gennadiy Civil's avatar
 
Gennadiy Civil committed
3410
    ADD_FAILURE() << "should not reach here.";
shiqian's avatar
shiqian committed
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
  }

  void DoExpectNoFatalFailureOnFails() {
    EXPECT_NO_FATAL_FAILURE(Fails());
    ADD_FAILURE() << "other failure";
  }
};

TEST_F(NoFatalFailureTest, NoFailure) {
  EXPECT_NO_FATAL_FAILURE(Succeeds());
  ASSERT_NO_FATAL_FAILURE(Succeeds());
}

TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
  EXPECT_NONFATAL_FAILURE(
      EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
      "some non-fatal failure");
  EXPECT_NONFATAL_FAILURE(
      ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
      "some non-fatal failure");
}

TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
  TestPartResultArray gtest_failures;
  {
    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
    DoAssertNoFatalFailureOnFails();
  }
  ASSERT_EQ(2, gtest_failures.size());
3440
  EXPECT_EQ(TestPartResult::kFatalFailure,
shiqian's avatar
shiqian committed
3441
            gtest_failures.GetTestPartResult(0).type());
3442
  EXPECT_EQ(TestPartResult::kFatalFailure,
shiqian's avatar
shiqian committed
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
            gtest_failures.GetTestPartResult(1).type());
  EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
                      gtest_failures.GetTestPartResult(0).message());
  EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
                      gtest_failures.GetTestPartResult(1).message());
}

TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
  TestPartResultArray gtest_failures;
  {
    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
    DoExpectNoFatalFailureOnFails();
  }
  ASSERT_EQ(3, gtest_failures.size());
3457
  EXPECT_EQ(TestPartResult::kFatalFailure,
shiqian's avatar
shiqian committed
3458
            gtest_failures.GetTestPartResult(0).type());
3459
  EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqian's avatar
shiqian committed
3460
            gtest_failures.GetTestPartResult(1).type());
3461
  EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqian's avatar
shiqian committed
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
            gtest_failures.GetTestPartResult(2).type());
  EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
                      gtest_failures.GetTestPartResult(0).message());
  EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
                      gtest_failures.GetTestPartResult(1).message());
  EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
                      gtest_failures.GetTestPartResult(2).message());
}

TEST_F(NoFatalFailureTest, MessageIsStreamable) {
  TestPartResultArray gtest_failures;
  {
    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
    EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
  }
  ASSERT_EQ(2, gtest_failures.size());
3478
  EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqian's avatar
shiqian committed
3479
            gtest_failures.GetTestPartResult(0).type());
3480
  EXPECT_EQ(TestPartResult::kNonFatalFailure,
shiqian's avatar
shiqian committed
3481
3482
3483
3484
3485
3486
3487
            gtest_failures.GetTestPartResult(1).type());
  EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
                      gtest_failures.GetTestPartResult(0).message());
  EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
                      gtest_failures.GetTestPartResult(1).message());
}

shiqian's avatar
shiqian committed
3488
3489
// Tests non-string assertions.

3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
std::string EditsToString(const std::vector<EditType>& edits) {
  std::string out;
  for (size_t i = 0; i < edits.size(); ++i) {
    static const char kEdits[] = " +-/";
    out.append(1, kEdits[edits[i]]);
  }
  return out;
}

std::vector<size_t> CharsToIndices(const std::string& str) {
  std::vector<size_t> out;
  for (size_t i = 0; i < str.size(); ++i) {
3502
    out.push_back(static_cast<size_t>(str[i]));
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
  }
  return out;
}

std::vector<std::string> CharsToLines(const std::string& str) {
  std::vector<std::string> out;
  for (size_t i = 0; i < str.size(); ++i) {
    out.push_back(str.substr(i, 1));
  }
  return out;
}

misterg's avatar
misterg committed
3515
TEST(EditDistance, TestSuites) {
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
  struct Case {
    int line;
    const char* left;
    const char* right;
    const char* expected_edits;
    const char* expected_diff;
  };
  static const Case kCases[] = {
      // No change.
      {__LINE__, "A", "A", " ", ""},
      {__LINE__, "ABCDE", "ABCDE", "     ", ""},
      // Simple adds.
      {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
      {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
      // Simple removes.
      {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
      {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
      // Simple replaces.
      {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
      {__LINE__, "ABCD", "abcd", "////",
       "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
      // Path finding.
      {__LINE__, "ABCDEFGH", "ABXEGH1", "  -/ -  +",
       "@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"},
      {__LINE__, "AAAABCCCC", "ABABCDCDC", "- /   + / ",
       "@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"},
      {__LINE__, "ABCDE", "BCDCD", "-   +/",
       "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
      {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++     --   ++",
       "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
       "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
      {}};
  for (const Case* c = kCases; c->left; ++c) {
    EXPECT_TRUE(c->expected_edits ==
                EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
                                                    CharsToIndices(c->right))))
        << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
        << EditsToString(CalculateOptimalEdits(
               CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
    EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
                                                      CharsToLines(c->right)))
        << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
        << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
        << ">";
  }
}

shiqian's avatar
shiqian committed
3563
3564
// Tests EqFailure(), used for implementing *EQ* assertions.
TEST(AssertionTest, EqFailure) {
3565
3566
  const std::string foo_val("5"), bar_val("6");
  const std::string msg1(
shiqian's avatar
shiqian committed
3567
3568
3569
      EqFailure("foo", "bar", foo_val, bar_val, false)
      .failure_message());
  EXPECT_STREQ(
3570
3571
3572
3573
3574
      "Expected equality of these values:\n"
      "  foo\n"
      "    Which is: 5\n"
      "  bar\n"
      "    Which is: 6",
shiqian's avatar
shiqian committed
3575
3576
      msg1.c_str());

3577
  const std::string msg2(
shiqian's avatar
shiqian committed
3578
3579
3580
      EqFailure("foo", "6", foo_val, bar_val, false)
      .failure_message());
  EXPECT_STREQ(
3581
3582
3583
3584
      "Expected equality of these values:\n"
      "  foo\n"
      "    Which is: 5\n"
      "  6",
shiqian's avatar
shiqian committed
3585
3586
      msg2.c_str());

3587
  const std::string msg3(
shiqian's avatar
shiqian committed
3588
3589
3590
      EqFailure("5", "bar", foo_val, bar_val, false)
      .failure_message());
  EXPECT_STREQ(
3591
3592
3593
3594
      "Expected equality of these values:\n"
      "  5\n"
      "  bar\n"
      "    Which is: 6",
shiqian's avatar
shiqian committed
3595
3596
      msg3.c_str());

3597
  const std::string msg4(
shiqian's avatar
shiqian committed
3598
3599
      EqFailure("5", "6", foo_val, bar_val, false).failure_message());
  EXPECT_STREQ(
3600
3601
3602
      "Expected equality of these values:\n"
      "  5\n"
      "  6",
shiqian's avatar
shiqian committed
3603
3604
      msg4.c_str());

3605
  const std::string msg5(
shiqian's avatar
shiqian committed
3606
      EqFailure("foo", "bar",
3607
                std::string("\"x\""), std::string("\"y\""),
shiqian's avatar
shiqian committed
3608
3609
                true).failure_message());
  EXPECT_STREQ(
3610
3611
3612
3613
3614
      "Expected equality of these values:\n"
      "  foo\n"
      "    Which is: \"x\"\n"
      "  bar\n"
      "    Which is: \"y\"\n"
3615
      "Ignoring case",
shiqian's avatar
shiqian committed
3616
3617
3618
      msg5.c_str());
}

3619
3620
3621
3622
3623
3624
3625
3626
TEST(AssertionTest, EqFailureWithDiff) {
  const std::string left(
      "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
  const std::string right(
      "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
  const std::string msg1(
      EqFailure("left", "right", left, right, false).failure_message());
  EXPECT_STREQ(
3627
3628
3629
      "Expected equality of these values:\n"
      "  left\n"
      "    Which is: "
3630
      "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3631
3632
      "  right\n"
      "    Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3633
3634
3635
3636
3637
      "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
      "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
      msg1.c_str());
}

shiqian's avatar
shiqian committed
3638
3639
// Tests AppendUserMessage(), used for implementing the *EQ* macros.
TEST(AssertionTest, AppendUserMessage) {
3640
  const std::string foo("foo");
shiqian's avatar
shiqian committed
3641

3642
  Message msg;
shiqian's avatar
shiqian committed
3643
3644
3645
3646
3647
3648
3649
3650
  EXPECT_STREQ("foo",
               AppendUserMessage(foo, msg).c_str());

  msg << "bar";
  EXPECT_STREQ("foo\nbar",
               AppendUserMessage(foo, msg).c_str());
}

3651
3652
#ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code"
3653
# pragma option push -w-ccc -w-rch
3654
3655
#endif

shiqian's avatar
shiqian committed
3656
3657
3658
3659
3660
3661
3662
// Tests ASSERT_TRUE.
TEST(AssertionTest, ASSERT_TRUE) {
  ASSERT_TRUE(2 > 1);  // NOLINT
  EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
                       "2 < 1");
}

3663
3664
3665
// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
TEST(AssertionTest, AssertTrueWithAssertionResult) {
  ASSERT_TRUE(ResultIsEven(2));
3666
3667
#ifndef __BORLANDC__
  // ICE's in C++Builder.
3668
3669
3670
3671
  EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
                       "Value of: ResultIsEven(3)\n"
                       "  Actual: false (3 is odd)\n"
                       "Expected: true");
3672
#endif
3673
3674
3675
3676
3677
3678
3679
  ASSERT_TRUE(ResultIsEvenNoExplanation(2));
  EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
                       "Value of: ResultIsEvenNoExplanation(3)\n"
                       "  Actual: false (3 is odd)\n"
                       "Expected: true");
}

shiqian's avatar
shiqian committed
3680
3681
3682
3683
3684
3685
3686
3687
3688
// Tests ASSERT_FALSE.
TEST(AssertionTest, ASSERT_FALSE) {
  ASSERT_FALSE(2 < 1);  // NOLINT
  EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
                       "Value of: 2 > 1\n"
                       "  Actual: true\n"
                       "Expected: false");
}

3689
3690
3691
// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
TEST(AssertionTest, AssertFalseWithAssertionResult) {
  ASSERT_FALSE(ResultIsEven(3));
3692
3693
#ifndef __BORLANDC__
  // ICE's in C++Builder.
3694
3695
3696
3697
  EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
                       "Value of: ResultIsEven(2)\n"
                       "  Actual: true (2 is even)\n"
                       "Expected: false");
3698
#endif
3699
3700
3701
3702
3703
3704
3705
  ASSERT_FALSE(ResultIsEvenNoExplanation(3));
  EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
                       "Value of: ResultIsEvenNoExplanation(2)\n"
                       "  Actual: true\n"
                       "Expected: false");
}

3706
#ifdef __BORLANDC__
Troy Holsapple's avatar
Troy Holsapple committed
3707
// Restores warnings after previous "#pragma option push" suppressed them
3708
# pragma option pop
3709
3710
#endif

shiqian's avatar
shiqian committed
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
// Tests using ASSERT_EQ on double values.  The purpose is to make
// sure that the specialization we did for integer and anonymous enums
// isn't used for double arguments.
TEST(ExpectTest, ASSERT_EQ_Double) {
  // A success.
  ASSERT_EQ(5.6, 5.6);

  // A failure.
  EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
                       "5.1");
}

// Tests ASSERT_EQ.
TEST(AssertionTest, ASSERT_EQ) {
  ASSERT_EQ(5, 2 + 3);
  EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3727
3728
3729
3730
                       "Expected equality of these values:\n"
                       "  5\n"
                       "  2*3\n"
                       "    Which is: 6");
shiqian's avatar
shiqian committed
3731
3732
3733
3734
3735
}

// Tests ASSERT_EQ(NULL, pointer).
TEST(AssertionTest, ASSERT_EQ_NULL) {
  // A success.
3736
  const char* p = nullptr;
vpfautz's avatar
vpfautz committed
3737
  // Some older GCC versions may issue a spurious warning in this or the next
3738
3739
3740
  // assertion statement. This warning should not be suppressed with
  // static_cast since the test verifies the ability to use bare NULL as the
  // expected parameter to the macro.
3741
  ASSERT_EQ(nullptr, p);
shiqian's avatar
shiqian committed
3742
3743
3744

  // A failure.
  static int n = 0;
3745
  EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), "  &n\n    Which is:");
shiqian's avatar
shiqian committed
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
}

// Tests ASSERT_EQ(0, non_pointer).  Since the literal 0 can be
// treated as a null pointer by the compiler, we need to make sure
// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest, ASSERT_EQ_0) {
  int n = 0;

  // A success.
  ASSERT_EQ(0, n);

  // A failure.
  EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3760
                       "  0\n  5.6");
shiqian's avatar
shiqian committed
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
}

// Tests ASSERT_NE.
TEST(AssertionTest, ASSERT_NE) {
  ASSERT_NE(6, 7);
  EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
                       "Expected: ('a') != ('a'), "
                       "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
}

// Tests ASSERT_LE.
TEST(AssertionTest, ASSERT_LE) {
  ASSERT_LE(2, 3);
  ASSERT_LE(2, 2);
  EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
                       "Expected: (2) <= (0), actual: 2 vs 0");
}

// Tests ASSERT_LT.
TEST(AssertionTest, ASSERT_LT) {
  ASSERT_LT(2, 3);
  EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
                       "Expected: (2) < (2), actual: 2 vs 2");
}

// Tests ASSERT_GE.
TEST(AssertionTest, ASSERT_GE) {
  ASSERT_GE(2, 1);
  ASSERT_GE(2, 2);
  EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
                       "Expected: (2) >= (3), actual: 2 vs 3");
}

// Tests ASSERT_GT.
TEST(AssertionTest, ASSERT_GT) {
  ASSERT_GT(2, 1);
  EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
                       "Expected: (2) > (2), actual: 2 vs 2");
}

3801
3802
#if GTEST_HAS_EXCEPTIONS

3803
3804
void ThrowNothing() {}

3805
3806
3807
// Tests ASSERT_THROW.
TEST(AssertionTest, ASSERT_THROW) {
  ASSERT_THROW(ThrowAnInteger(), int);
3808

3809
3810
# ifndef __BORLANDC__

3811
  // ICE's in C++Builder 2007 and 2009.
3812
3813
3814
3815
  EXPECT_FATAL_FAILURE(
      ASSERT_THROW(ThrowAnInteger(), bool),
      "Expected: ThrowAnInteger() throws an exception of type bool.\n"
      "  Actual: it throws a different type.");
3816
# endif
3817

3818
3819
3820
3821
  EXPECT_FATAL_FAILURE(
      ASSERT_THROW(ThrowNothing(), bool),
      "Expected: ThrowNothing() throws an exception of type bool.\n"
      "  Actual: it throws nothing.");
3822
3823
3824
3825
}

// Tests ASSERT_NO_THROW.
TEST(AssertionTest, ASSERT_NO_THROW) {
3826
  ASSERT_NO_THROW(ThrowNothing());
3827
  EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3828
                       "Expected: ThrowAnInteger() doesn't throw an exception."
3829
3830
3831
3832
3833
3834
                       "\n  Actual: it throws.");
}

// Tests ASSERT_ANY_THROW.
TEST(AssertionTest, ASSERT_ANY_THROW) {
  ASSERT_ANY_THROW(ThrowAnInteger());
3835
3836
3837
3838
  EXPECT_FATAL_FAILURE(
      ASSERT_ANY_THROW(ThrowNothing()),
      "Expected: ThrowNothing() throws an exception.\n"
      "  Actual: it doesn't.");
3839
3840
3841
3842
}

#endif  // GTEST_HAS_EXCEPTIONS

shiqian's avatar
shiqian committed
3843
3844
3845
3846
// Makes sure we deal with the precedence of <<.  This test should
// compile.
TEST(AssertionTest, AssertPrecedence) {
  ASSERT_EQ(1 < 2, true);
3847
3848
  bool false_value = false;
  ASSERT_EQ(true && false_value, false);
shiqian's avatar
shiqian committed
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
}

// A subroutine used by the following test.
void TestEq1(int x) {
  ASSERT_EQ(1, x);
}

// Tests calling a test subroutine that's not part of a fixture.
TEST(AssertionTest, NonFixtureSubroutine) {
  EXPECT_FATAL_FAILURE(TestEq1(2),
Gennadiy Civil's avatar
Gennadiy Civil committed
3859
                       "  x\n    Which is: 2");
shiqian's avatar
shiqian committed
3860
3861
3862
3863
3864
}

// An uncopyable class.
class Uncopyable {
 public:
3865
  explicit Uncopyable(int a_value) : value_(a_value) {}
shiqian's avatar
shiqian committed
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907

  int value() const { return value_; }
  bool operator==(const Uncopyable& rhs) const {
    return value() == rhs.value();
  }
 private:
  // This constructor deliberately has no implementation, as we don't
  // want this class to be copyable.
  Uncopyable(const Uncopyable&);  // NOLINT

  int value_;
};

::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
  return os << value.value();
}


bool IsPositiveUncopyable(const Uncopyable& x) {
  return x.value() > 0;
}

// A subroutine used by the following test.
void TestAssertNonPositive() {
  Uncopyable y(-1);
  ASSERT_PRED1(IsPositiveUncopyable, y);
}
// A subroutine used by the following test.
void TestAssertEqualsUncopyable() {
  Uncopyable x(5);
  Uncopyable y(-1);
  ASSERT_EQ(x, y);
}

// Tests that uncopyable objects can be used in assertions.
TEST(AssertionTest, AssertWorksWithUncopyableObject) {
  Uncopyable x(5);
  ASSERT_PRED1(IsPositiveUncopyable, x);
  ASSERT_EQ(x, x);
  EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
    "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
  EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3908
3909
                       "Expected equality of these values:\n"
                       "  x\n    Which is: 5\n  y\n    Which is: -1");
shiqian's avatar
shiqian committed
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
}

// Tests that uncopyable objects can be used in expects.
TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
  Uncopyable x(5);
  EXPECT_PRED1(IsPositiveUncopyable, x);
  Uncopyable y(-1);
  EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
    "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
  EXPECT_EQ(x, x);
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3921
3922
                          "Expected equality of these values:\n"
                          "  x\n    Which is: 5\n  y\n    Which is: -1");
shiqian's avatar
shiqian committed
3923
3924
}

3925
3926
enum NamedEnum {
  kE1 = 0,
3927
  kE2 = 1
3928
3929
3930
3931
3932
3933
};

TEST(AssertionTest, NamedEnum) {
  EXPECT_EQ(kE1, kE1);
  EXPECT_LT(kE1, kE2);
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3934
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
3935
}
shiqian's avatar
shiqian committed
3936

Abseil Team's avatar
Abseil Team committed
3937
3938
// Sun Studio and HP aCC2reject this code.
#if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
shiqian's avatar
shiqian committed
3939
3940
3941

// Tests using assertions with anonymous enums.
enum {
3942
  kCaseA = -1,
3943
3944
3945

# if GTEST_OS_LINUX

shiqian's avatar
shiqian committed
3946
3947
3948
3949
3950
3951
  // We want to test the case where the size of the anonymous enum is
  // larger than sizeof(int), to make sure our implementation of the
  // assertions doesn't truncate the enums.  However, MSVC
  // (incorrectly) doesn't allow an enum value to exceed the range of
  // an int, so this has to be conditionally compiled.
  //
3952
  // On Linux, kCaseB and kCaseA have the same value when truncated to
shiqian's avatar
shiqian committed
3953
3954
  // int size.  We want to test whether this will confuse the
  // assertions.
3955
  kCaseB = testing::internal::kMaxBiggestInt,
3956
3957
3958

# else

3959
  kCaseB = INT_MAX,
3960
3961
3962

# endif  // GTEST_OS_LINUX

3963
  kCaseC = 42
shiqian's avatar
shiqian committed
3964
3965
3966
};

TEST(AssertionTest, AnonymousEnum) {
3967
3968
# if GTEST_OS_LINUX

3969
  EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
3970
3971

# endif  // GTEST_OS_LINUX
shiqian's avatar
shiqian committed
3972

3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
  EXPECT_EQ(kCaseA, kCaseA);
  EXPECT_NE(kCaseA, kCaseB);
  EXPECT_LT(kCaseA, kCaseB);
  EXPECT_LE(kCaseA, kCaseB);
  EXPECT_GT(kCaseB, kCaseA);
  EXPECT_GE(kCaseA, kCaseA);
  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
                          "(kCaseA) >= (kCaseB)");
  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
                          "-1 vs 42");

  ASSERT_EQ(kCaseA, kCaseA);
  ASSERT_NE(kCaseA, kCaseB);
  ASSERT_LT(kCaseA, kCaseB);
  ASSERT_LE(kCaseA, kCaseB);
  ASSERT_GT(kCaseB, kCaseA);
  ASSERT_GE(kCaseA, kCaseA);
3990
3991
3992
3993

# ifndef __BORLANDC__

  // ICE's in C++Builder.
3994
  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
Gennadiy Civil's avatar
Gennadiy Civil committed
3995
                       "  kCaseB\n    Which is: ");
3996
  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
Gennadiy Civil's avatar
Gennadiy Civil committed
3997
                       "\n    Which is: 42");
3998
3999
# endif

4000
  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
Gennadiy Civil's avatar
Gennadiy Civil committed
4001
                       "\n    Which is: -1");
shiqian's avatar
shiqian committed
4002
4003
}

4004
#endif  // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
shiqian's avatar
shiqian committed
4005

zhanyong.wan's avatar
zhanyong.wan committed
4006
#if GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028

static HRESULT UnexpectedHRESULTFailure() {
  return E_UNEXPECTED;
}

static HRESULT OkHRESULTSuccess() {
  return S_OK;
}

static HRESULT FalseHRESULTSuccess() {
  return S_FALSE;
}

// HRESULT assertion tests test both zero and non-zero
// success codes as well as failure message for each.
//
// Windows CE doesn't support message texts.
TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
  EXPECT_HRESULT_SUCCEEDED(S_OK);
  EXPECT_HRESULT_SUCCEEDED(S_FALSE);

  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4029
4030
    "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
    "  Actual: 0x8000FFFF");
shiqian's avatar
shiqian committed
4031
4032
4033
4034
4035
4036
4037
}

TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
  ASSERT_HRESULT_SUCCEEDED(S_OK);
  ASSERT_HRESULT_SUCCEEDED(S_FALSE);

  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4038
4039
    "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
    "  Actual: 0x8000FFFF");
shiqian's avatar
shiqian committed
4040
4041
4042
4043
4044
4045
}

TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
  EXPECT_HRESULT_FAILED(E_UNEXPECTED);

  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
4046
    "Expected: (OkHRESULTSuccess()) fails.\n"
4047
    "  Actual: 0x0");
shiqian's avatar
shiqian committed
4048
  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
4049
    "Expected: (FalseHRESULTSuccess()) fails.\n"
4050
    "  Actual: 0x1");
shiqian's avatar
shiqian committed
4051
4052
4053
4054
4055
}

TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
  ASSERT_HRESULT_FAILED(E_UNEXPECTED);

4056
4057
# ifndef __BORLANDC__

4058
  // ICE's in C++Builder 2007 and 2009.
shiqian's avatar
shiqian committed
4059
  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4060
    "Expected: (OkHRESULTSuccess()) fails.\n"
4061
    "  Actual: 0x0");
4062
4063
# endif

shiqian's avatar
shiqian committed
4064
  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4065
    "Expected: (FalseHRESULTSuccess()) fails.\n"
4066
    "  Actual: 0x1");
shiqian's avatar
shiqian committed
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
}

// Tests that streaming to the HRESULT macros works.
TEST(HRESULTAssertionTest, Streaming) {
  EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
  ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
  EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
  ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";

  EXPECT_NONFATAL_FAILURE(
      EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
      "expected failure");

4080
4081
# ifndef __BORLANDC__

4082
  // ICE's in C++Builder 2007 and 2009.
shiqian's avatar
shiqian committed
4083
4084
4085
  EXPECT_FATAL_FAILURE(
      ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
      "expected failure");
4086
# endif
shiqian's avatar
shiqian committed
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096

  EXPECT_NONFATAL_FAILURE(
      EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
      "expected failure");

  EXPECT_FATAL_FAILURE(
      ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
      "expected failure");
}

zhanyong.wan's avatar
zhanyong.wan committed
4097
#endif  // GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
4098

4099
4100
#ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code"
4101
# pragma option push -w-ccc -w-rch
4102
4103
#endif

shiqian's avatar
shiqian committed
4104
// Tests that the assertion macros behave like single statements.
shiqian's avatar
shiqian committed
4105
TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4106
  if (AlwaysFalse())
shiqian's avatar
shiqian committed
4107
4108
4109
    ASSERT_TRUE(false) << "This should never be executed; "
                          "It's a compilation test only.";

4110
  if (AlwaysTrue())
shiqian's avatar
shiqian committed
4111
4112
    EXPECT_FALSE(false);
  else
4113
    ;  // NOLINT
shiqian's avatar
shiqian committed
4114

4115
  if (AlwaysFalse())
shiqian's avatar
shiqian committed
4116
4117
    ASSERT_LT(1, 3);

4118
  if (AlwaysFalse())
4119
    ;  // NOLINT
shiqian's avatar
shiqian committed
4120
4121
  else
    EXPECT_GT(3, 2) << "";
shiqian's avatar
shiqian committed
4122
}
4123
4124

#if GTEST_HAS_EXCEPTIONS
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
// Tests that the compiler will not complain about unreachable code in the
// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
  int n = 0;

  EXPECT_THROW(throw 1, int);
  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
  EXPECT_NO_THROW(n++);
  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
  EXPECT_ANY_THROW(throw 1);
  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
}

shiqian's avatar
shiqian committed
4139
TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4140
  if (AlwaysFalse())
4141
    EXPECT_THROW(ThrowNothing(), bool);
4142

4143
  if (AlwaysTrue())
4144
4145
    EXPECT_THROW(ThrowAnInteger(), int);
  else
4146
    ;  // NOLINT
4147

4148
  if (AlwaysFalse())
4149
4150
    EXPECT_NO_THROW(ThrowAnInteger());

4151
  if (AlwaysTrue())
4152
    EXPECT_NO_THROW(ThrowNothing());
4153
  else
4154
    ;  // NOLINT
4155

4156
  if (AlwaysFalse())
4157
    EXPECT_ANY_THROW(ThrowNothing());
4158

4159
  if (AlwaysTrue())
4160
4161
    EXPECT_ANY_THROW(ThrowAnInteger());
  else
4162
    ;  // NOLINT
shiqian's avatar
shiqian committed
4163
}
4164
#endif  // GTEST_HAS_EXCEPTIONS
shiqian's avatar
shiqian committed
4165
4166

TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4167
  if (AlwaysFalse())
shiqian's avatar
shiqian committed
4168
4169
4170
    EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
                                    << "It's a compilation test only.";
  else
4171
    ;  // NOLINT
shiqian's avatar
shiqian committed
4172

4173
  if (AlwaysFalse())
shiqian's avatar
shiqian committed
4174
4175
    ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
  else
4176
    ;  // NOLINT
shiqian's avatar
shiqian committed
4177

4178
  if (AlwaysTrue())
shiqian's avatar
shiqian committed
4179
4180
    EXPECT_NO_FATAL_FAILURE(SUCCEED());
  else
4181
    ;  // NOLINT
shiqian's avatar
shiqian committed
4182

4183
  if (AlwaysFalse())
4184
    ;  // NOLINT
shiqian's avatar
shiqian committed
4185
4186
  else
    ASSERT_NO_FATAL_FAILURE(SUCCEED());
shiqian's avatar
shiqian committed
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
}

// Tests that the assertion macros work well with switch statements.
TEST(AssertionSyntaxTest, WorksWithSwitch) {
  switch (0) {
    case 1:
      break;
    default:
      ASSERT_TRUE(true);
  }

  switch (0)
    case 0:
      EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";

  // Binary assertions are implemented using a different code path
  // than the Boolean assertions.  Hence we test them separately.
  switch (0) {
    case 1:
    default:
      ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
  }

  switch (0)
    case 0:
      EXPECT_NE(1, 2);
}

4215
4216
4217
#if GTEST_HAS_EXCEPTIONS

void ThrowAString() {
4218
    throw "std::string";
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
}

// Test that the exception assertion macros compile and work with const
// type qualifier.
TEST(AssertionSyntaxTest, WorksWithConst) {
    ASSERT_THROW(ThrowAString(), const char*);

    EXPECT_THROW(ThrowAString(), const char*);
}

#endif  // GTEST_HAS_EXCEPTIONS

shiqian's avatar
shiqian committed
4231
4232
4233
4234
4235
4236
4237
4238
}  // namespace

namespace testing {

// Tests that Google Test tracks SUCCEED*.
TEST(SuccessfulAssertionTest, SUCCEED) {
  SUCCEED();
  SUCCEED() << "OK";
4239
  EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian's avatar
shiqian committed
4240
4241
4242
4243
4244
}

// Tests that Google Test doesn't track successful EXPECT_*.
TEST(SuccessfulAssertionTest, EXPECT) {
  EXPECT_TRUE(true);
4245
  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian's avatar
shiqian committed
4246
4247
4248
4249
4250
}

// Tests that Google Test doesn't track successful EXPECT_STR*.
TEST(SuccessfulAssertionTest, EXPECT_STR) {
  EXPECT_STREQ("", "");
4251
  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian's avatar
shiqian committed
4252
4253
4254
4255
4256
}

// Tests that Google Test doesn't track successful ASSERT_*.
TEST(SuccessfulAssertionTest, ASSERT) {
  ASSERT_TRUE(true);
4257
  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian's avatar
shiqian committed
4258
4259
4260
4261
4262
}

// Tests that Google Test doesn't track successful ASSERT_STR*.
TEST(SuccessfulAssertionTest, ASSERT_STR) {
  ASSERT_STREQ("", "");
4263
  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian's avatar
shiqian committed
4264
4265
4266
4267
4268
4269
}

}  // namespace testing

namespace {

4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
// Tests the message streaming variation of assertions.

TEST(AssertionWithMessageTest, EXPECT) {
  EXPECT_EQ(1, 1) << "This should succeed.";
  EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
                          "Expected failure #1");
  EXPECT_LE(1, 2) << "This should succeed.";
  EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
                          "Expected failure #2.");
  EXPECT_GE(1, 0) << "This should succeed.";
  EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
                          "Expected failure #3.");

  EXPECT_STREQ("1", "1") << "This should succeed.";
  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
                          "Expected failure #4.");
  EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
                          "Expected failure #5.");

  EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
                          "Expected failure #6.");
  EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
}

TEST(AssertionWithMessageTest, ASSERT) {
  ASSERT_EQ(1, 1) << "This should succeed.";
  ASSERT_NE(1, 2) << "This should succeed.";
  ASSERT_LE(1, 2) << "This should succeed.";
  ASSERT_LT(1, 2) << "This should succeed.";
  ASSERT_GE(1, 0) << "This should succeed.";
  EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
                       "Expected failure.");
}

TEST(AssertionWithMessageTest, ASSERT_STR) {
  ASSERT_STREQ("1", "1") << "This should succeed.";
  ASSERT_STRNE("1", "2") << "This should succeed.";
  ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
                       "Expected failure.");
}

TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
  ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
  ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.",  // NOLINT
                       "Expect failure.");
  // To work around a bug in gcc 2.95.0, there is intentionally no
  // space after the first comma in the previous statement.
}

// Tests using ASSERT_FALSE with a streamed message.
TEST(AssertionWithMessageTest, ASSERT_FALSE) {
  ASSERT_FALSE(false) << "This shouldn't fail.";
  EXPECT_FATAL_FAILURE({  // NOLINT
    ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
                       << " evaluates to " << true;
  }, "Expected failure");
}

// Tests using FAIL with a streamed message.
TEST(AssertionWithMessageTest, FAIL) {
  EXPECT_FATAL_FAILURE(FAIL() << 0,
                       "0");
}

// Tests using SUCCEED with a streamed message.
TEST(AssertionWithMessageTest, SUCCEED) {
  SUCCEED() << "Success == " << 1;
}

// Tests using ASSERT_TRUE with a streamed message.
TEST(AssertionWithMessageTest, ASSERT_TRUE) {
  ASSERT_TRUE(true) << "This should succeed.";
  ASSERT_TRUE(true) << true;
4347
4348
4349
4350
4351
4352
  EXPECT_FATAL_FAILURE(
      {  // NOLINT
        ASSERT_TRUE(false) << static_cast<const char*>(nullptr)
                           << static_cast<char*>(nullptr);
      },
      "(null)(null)");
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
}

#if GTEST_OS_WINDOWS
// Tests using wide strings in assertion messages.
TEST(AssertionWithMessageTest, WideStringMessage) {
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_TRUE(false) << L"This failure is expected.\x8119";
  }, "This failure is expected.");
  EXPECT_FATAL_FAILURE({  // NOLINT
    ASSERT_EQ(1, 2) << "This failure is "
                    << L"expected too.\x8120";
  }, "This failure is expected too.");
}
#endif  // GTEST_OS_WINDOWS

shiqian's avatar
shiqian committed
4368
4369
// Tests EXPECT_TRUE.
TEST(ExpectTest, EXPECT_TRUE) {
4370
4371
4372
4373
4374
  EXPECT_TRUE(true) << "Intentional success";
  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
                          "Intentional failure #1.");
  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
                          "Intentional failure #2.");
shiqian's avatar
shiqian committed
4375
4376
4377
4378
4379
4380
4381
4382
4383
  EXPECT_TRUE(2 > 1);  // NOLINT
  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
                          "Value of: 2 < 1\n"
                          "  Actual: false\n"
                          "Expected: true");
  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
                          "2 > 3");
}

4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
TEST(ExpectTest, ExpectTrueWithAssertionResult) {
  EXPECT_TRUE(ResultIsEven(2));
  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
                          "Value of: ResultIsEven(3)\n"
                          "  Actual: false (3 is odd)\n"
                          "Expected: true");
  EXPECT_TRUE(ResultIsEvenNoExplanation(2));
  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
                          "Value of: ResultIsEvenNoExplanation(3)\n"
                          "  Actual: false (3 is odd)\n"
                          "Expected: true");
}

4398
// Tests EXPECT_FALSE with a streamed message.
shiqian's avatar
shiqian committed
4399
4400
TEST(ExpectTest, EXPECT_FALSE) {
  EXPECT_FALSE(2 < 1);  // NOLINT
4401
4402
4403
4404
4405
  EXPECT_FALSE(false) << "Intentional success";
  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
                          "Intentional failure #1.");
  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
                          "Intentional failure #2.");
shiqian's avatar
shiqian committed
4406
4407
4408
4409
4410
4411
4412
4413
  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
                          "Value of: 2 > 1\n"
                          "  Actual: true\n"
                          "Expected: false");
  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
                          "2 < 3");
}

4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
TEST(ExpectTest, ExpectFalseWithAssertionResult) {
  EXPECT_FALSE(ResultIsEven(3));
  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
                          "Value of: ResultIsEven(2)\n"
                          "  Actual: true (2 is even)\n"
                          "Expected: false");
  EXPECT_FALSE(ResultIsEvenNoExplanation(3));
  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
                          "Value of: ResultIsEvenNoExplanation(2)\n"
                          "  Actual: true\n"
                          "Expected: false");
}

4428
#ifdef __BORLANDC__
Troy Holsapple's avatar
Troy Holsapple committed
4429
// Restores warnings after previous "#pragma option push" suppressed them
4430
# pragma option pop
4431
4432
#endif

shiqian's avatar
shiqian committed
4433
4434
4435
4436
// Tests EXPECT_EQ.
TEST(ExpectTest, EXPECT_EQ) {
  EXPECT_EQ(5, 2 + 3);
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4437
4438
4439
4440
                          "Expected equality of these values:\n"
                          "  5\n"
                          "  2*3\n"
                          "    Which is: 6");
shiqian's avatar
shiqian committed
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
                          "2 - 3");
}

// Tests using EXPECT_EQ on double values.  The purpose is to make
// sure that the specialization we did for integer and anonymous enums
// isn't used for double arguments.
TEST(ExpectTest, EXPECT_EQ_Double) {
  // A success.
  EXPECT_EQ(5.6, 5.6);

  // A failure.
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
                          "5.1");
}

// Tests EXPECT_EQ(NULL, pointer).
TEST(ExpectTest, EXPECT_EQ_NULL) {
  // A success.
4460
  const char* p = nullptr;
4461
  // Some older GCC versions may issue a spurious warning in this or the next
4462
4463
4464
  // assertion statement. This warning should not be suppressed with
  // static_cast since the test verifies the ability to use bare NULL as the
  // expected parameter to the macro.
4465
  EXPECT_EQ(nullptr, p);
shiqian's avatar
shiqian committed
4466
4467
4468

  // A failure.
  int n = 0;
4469
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), "  &n\n    Which is:");
shiqian's avatar
shiqian committed
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
}

// Tests EXPECT_EQ(0, non_pointer).  Since the literal 0 can be
// treated as a null pointer by the compiler, we need to make sure
// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest, EXPECT_EQ_0) {
  int n = 0;

  // A success.
  EXPECT_EQ(0, n);

  // A failure.
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
Gennadiy Civil's avatar
Gennadiy Civil committed
4484
                          "  0\n  5.6");
shiqian's avatar
shiqian committed
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
}

// Tests EXPECT_NE.
TEST(ExpectTest, EXPECT_NE) {
  EXPECT_NE(6, 7);

  EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
                          "Expected: ('a') != ('a'), "
                          "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
  EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
                          "2");
4496
  char* const p0 = nullptr;
shiqian's avatar
shiqian committed
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
                          "p0");
  // Only way to get the Nokia compiler to compile the cast
  // is to have a separate void* variable first. Putting
  // the two casts on the same line doesn't work, neither does
  // a direct C-style to char*.
  void* pv1 = (void*)0x1234;  // NOLINT
  char* const p1 = reinterpret_cast<char*>(pv1);
  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
                          "p1");
}

// Tests EXPECT_LE.
TEST(ExpectTest, EXPECT_LE) {
  EXPECT_LE(2, 3);
  EXPECT_LE(2, 2);
  EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
                          "Expected: (2) <= (0), actual: 2 vs 0");
  EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
                          "(1.1) <= (0.9)");
}

// Tests EXPECT_LT.
TEST(ExpectTest, EXPECT_LT) {
  EXPECT_LT(2, 3);
  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
                          "Expected: (2) < (2), actual: 2 vs 2");
  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
                          "(2) < (1)");
}

// Tests EXPECT_GE.
TEST(ExpectTest, EXPECT_GE) {
  EXPECT_GE(2, 1);
  EXPECT_GE(2, 2);
  EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
                          "Expected: (2) >= (3), actual: 2 vs 3");
  EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
                          "(0.9) >= (1.1)");
}

// Tests EXPECT_GT.
TEST(ExpectTest, EXPECT_GT) {
  EXPECT_GT(2, 1);
  EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
                          "Expected: (2) > (2), actual: 2 vs 2");
  EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
                          "(2) > (3)");
}

4547
4548
4549
4550
4551
4552
#if GTEST_HAS_EXCEPTIONS

// Tests EXPECT_THROW.
TEST(ExpectTest, EXPECT_THROW) {
  EXPECT_THROW(ThrowAnInteger(), int);
  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4553
4554
                          "Expected: ThrowAnInteger() throws an exception of "
                          "type bool.\n  Actual: it throws a different type.");
Abseil Team's avatar
Abseil Team committed
4555
4556
4557
4558
  EXPECT_NONFATAL_FAILURE(
      EXPECT_THROW(ThrowNothing(), bool),
      "Expected: ThrowNothing() throws an exception of type bool.\n"
      "  Actual: it throws nothing.");
4559
4560
4561
4562
}

// Tests EXPECT_NO_THROW.
TEST(ExpectTest, EXPECT_NO_THROW) {
4563
  EXPECT_NO_THROW(ThrowNothing());
4564
  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4565
                          "Expected: ThrowAnInteger() doesn't throw an "
4566
4567
4568
4569
4570
4571
                          "exception.\n  Actual: it throws.");
}

// Tests EXPECT_ANY_THROW.
TEST(ExpectTest, EXPECT_ANY_THROW) {
  EXPECT_ANY_THROW(ThrowAnInteger());
4572
4573
4574
4575
  EXPECT_NONFATAL_FAILURE(
      EXPECT_ANY_THROW(ThrowNothing()),
      "Expected: ThrowNothing() throws an exception.\n"
      "  Actual: it doesn't.");
4576
4577
4578
4579
}

#endif  // GTEST_HAS_EXCEPTIONS

shiqian's avatar
shiqian committed
4580
4581
4582
4583
// Make sure we deal with the precedence of <<.
TEST(ExpectTest, ExpectPrecedence) {
  EXPECT_EQ(1 < 2, true);
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
Gennadiy Civil's avatar
Gennadiy Civil committed
4584
                          "  true && false\n    Which is: false");
shiqian's avatar
shiqian committed
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
}


// Tests the StreamableToString() function.

// Tests using StreamableToString() on a scalar.
TEST(StreamableToStringTest, Scalar) {
  EXPECT_STREQ("5", StreamableToString(5).c_str());
}

// Tests using StreamableToString() on a non-char pointer.
TEST(StreamableToStringTest, Pointer) {
  int n = 0;
  int* p = &n;
  EXPECT_STRNE("(null)", StreamableToString(p).c_str());
}

// Tests using StreamableToString() on a NULL non-char pointer.
TEST(StreamableToStringTest, NullPointer) {
4604
  int* p = nullptr;
shiqian's avatar
shiqian committed
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
  EXPECT_STREQ("(null)", StreamableToString(p).c_str());
}

// Tests using StreamableToString() on a C string.
TEST(StreamableToStringTest, CString) {
  EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
}

// Tests using StreamableToString() on a NULL C string.
TEST(StreamableToStringTest, NullCString) {
4615
  char* p = nullptr;
shiqian's avatar
shiqian committed
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
  EXPECT_STREQ("(null)", StreamableToString(p).c_str());
}

// Tests using streamable values as assertion messages.

// Tests using std::string as an assertion message.
TEST(StreamableTest, string) {
  static const std::string str(
      "This failure message is a std::string, and is expected.");
  EXPECT_FATAL_FAILURE(FAIL() << str,
                       str.c_str());
}

// Tests that we can output strings containing embedded NULs.
// Limited to Linux because we can only do this with std::string's.
TEST(StreamableTest, stringWithEmbeddedNUL) {
  static const char char_array_with_nul[] =
      "Here's a NUL\0 and some more string";
  static const std::string string_with_nul(char_array_with_nul,
                                           sizeof(char_array_with_nul)
                                           - 1);  // drops the trailing NUL
  EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
                       "Here's a NUL\\0 and some more string");
}

// Tests that we can output a NUL char.
TEST(StreamableTest, NULChar) {
  EXPECT_FATAL_FAILURE({  // NOLINT
    FAIL() << "A NUL" << '\0' << " and some more string";
  }, "A NUL\\0 and some more string");
}

// Tests using int as an assertion message.
TEST(StreamableTest, int) {
  EXPECT_FATAL_FAILURE(FAIL() << 900913,
                       "900913");
}

// Tests using NULL char pointer as an assertion message.
//
// In MSVC, streaming a NULL char * causes access violation.  Google Test
// implemented a workaround (substituting "(null)" for NULL).  This
// tests whether the workaround works.
TEST(StreamableTest, NullCharPtr) {
4660
  EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)");
shiqian's avatar
shiqian committed
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
}

// Tests that basic IO manipulators (endl, ends, and flush) can be
// streamed to testing::Message.
TEST(StreamableTest, BasicIoManip) {
  EXPECT_FATAL_FAILURE({  // NOLINT
    FAIL() << "Line 1." << std::endl
           << "A NUL char " << std::ends << std::flush << " in line 2.";
  }, "Line 1.\nA NUL char \\0 in line 2.");
}

// Tests the macros that haven't been covered so far.

void AddFailureHelper(bool* aborted) {
  *aborted = true;
4676
  ADD_FAILURE() << "Intentional failure.";
shiqian's avatar
shiqian committed
4677
4678
4679
4680
4681
4682
4683
  *aborted = false;
}

// Tests ADD_FAILURE.
TEST(MacroTest, ADD_FAILURE) {
  bool aborted = true;
  EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4684
                          "Intentional failure.");
shiqian's avatar
shiqian committed
4685
4686
4687
  EXPECT_FALSE(aborted);
}

4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
// Tests ADD_FAILURE_AT.
TEST(MacroTest, ADD_FAILURE_AT) {
  // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
  // the failure message contains the user-streamed part.
  EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");

  // Verifies that the user-streamed part is optional.
  EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");

  // Unfortunately, we cannot verify that the failure message contains
  // the right file path and line number the same way, as
  // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
Gennadiy Civil's avatar
 
Gennadiy Civil committed
4700
  // line number.  Instead, we do that in googletest-output-test_.cc.
4701
4702
}

shiqian's avatar
shiqian committed
4703
4704
4705
4706
4707
4708
4709
4710
// Tests FAIL.
TEST(MacroTest, FAIL) {
  EXPECT_FATAL_FAILURE(FAIL(),
                       "Failed");
  EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
                       "Intentional failure.");
}

Abseil Team's avatar
Abseil Team committed
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
// Tests GTEST_FAIL_AT.
TEST(MacroTest, GTEST_FAIL_AT) {
  // Verifies that GTEST_FAIL_AT does generate a fatal failure and
  // the failure message contains the user-streamed part.
  EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!");

  // Verifies that the user-streamed part is optional.
  EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed");

  // See the ADD_FAIL_AT test above to see how we test that the failure message
  // contains the right filename and line number -- the same applies here.
}

shiqian's avatar
shiqian committed
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
// Tests SUCCEED
TEST(MacroTest, SUCCEED) {
  SUCCEED();
  SUCCEED() << "Explicit success.";
}

// Tests for EXPECT_EQ() and ASSERT_EQ().
//
// These tests fail *intentionally*, s.t. the failure messages can be
// generated and tested.
//
// We have different tests for different argument types.

// Tests using bool values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Bool) {
  EXPECT_EQ(true,  true);
4740
4741
4742
  EXPECT_FATAL_FAILURE({
      bool false_value = false;
      ASSERT_EQ(false_value, true);
Gennadiy Civil's avatar
Gennadiy Civil committed
4743
    }, "  false_value\n    Which is: false\n  true");
shiqian's avatar
shiqian committed
4744
4745
4746
4747
4748
4749
}

// Tests using int values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Int) {
  ASSERT_EQ(32, 32);
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
Gennadiy Civil's avatar
Gennadiy Civil committed
4750
                          "  32\n  33");
shiqian's avatar
shiqian committed
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
}

// Tests using time_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Time_T) {
  EXPECT_EQ(static_cast<time_t>(0),
            static_cast<time_t>(0));
  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
                                 static_cast<time_t>(1234)),
                       "1234");
}

// Tests using char values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Char) {
  ASSERT_EQ('z', 'z');
  const char ch = 'b';
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
Gennadiy Civil's avatar
Gennadiy Civil committed
4767
                          "  ch\n    Which is: 'b'");
shiqian's avatar
shiqian committed
4768
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
Gennadiy Civil's avatar
Gennadiy Civil committed
4769
                          "  ch\n    Which is: 'b'");
shiqian's avatar
shiqian committed
4770
4771
4772
4773
4774
4775
4776
}

// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, WideChar) {
  EXPECT_EQ(L'b', L'b');

  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4777
4778
4779
4780
4781
                          "Expected equality of these values:\n"
                          "  L'\0'\n"
                          "    Which is: L'\0' (0, 0x0)\n"
                          "  L'x'\n"
                          "    Which is: L'x' (120, 0x78)");
shiqian's avatar
shiqian committed
4782
4783
4784
4785
4786

  static wchar_t wchar;
  wchar = L'b';
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
                          "wchar");
4787
4788
  wchar = 0x8119;
  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
Gennadiy Civil's avatar
Gennadiy Civil committed
4789
                       "  wchar\n    Which is: L'");
shiqian's avatar
shiqian committed
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
}

// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, StdString) {
  // Compares a const char* to an std::string that has identical
  // content.
  ASSERT_EQ("Test", ::std::string("Test"));

  // Compares two identical std::strings.
  static const ::std::string str1("A * in the middle");
  static const ::std::string str2(str1);
  EXPECT_EQ(str1, str2);

  // Compares a const char* to an std::string that has different
  // content
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4806
                          "\"test\"");
shiqian's avatar
shiqian committed
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817

  // Compares an std::string to a char* that has different content.
  char* const p1 = const_cast<char*>("foo");
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
                          "p1");

  // Compares two std::strings that have different contents, one of
  // which having a NUL character in the middle.  This should fail.
  static ::std::string str3(str1);
  str3.at(2) = '\0';
  EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
Gennadiy Civil's avatar
Gennadiy Civil committed
4818
                       "  str3\n    Which is: \"A \\0 in the middle\"");
shiqian's avatar
shiqian committed
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
}

#if GTEST_HAS_STD_WSTRING

// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, StdWideString) {
  // Compares two identical std::wstrings.
  const ::std::wstring wstr1(L"A * in the middle");
  const ::std::wstring wstr2(wstr1);
  ASSERT_EQ(wstr1, wstr2);

4830
4831
4832
4833
4834
  // Compares an std::wstring to a const wchar_t* that has identical
  // content.
  const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
  EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);

shiqian's avatar
shiqian committed
4835
4836
  // Compares an std::wstring to a const wchar_t* that has different
  // content.
4837
  const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
shiqian's avatar
shiqian committed
4838
  EXPECT_NONFATAL_FAILURE({  // NOLINT
4839
4840
    EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
  }, "kTestX8120");
shiqian's avatar
shiqian committed
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859

  // Compares two std::wstrings that have different contents, one of
  // which having a NUL character in the middle.
  ::std::wstring wstr3(wstr1);
  wstr3.at(2) = L'\0';
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
                          "wstr3");

  // Compares a wchar_t* to an std::wstring that has different
  // content.
  EXPECT_FATAL_FAILURE({  // NOLINT
    ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
  }, "");
}

#endif  // GTEST_HAS_STD_WSTRING

// Tests using char pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, CharPointer) {
4860
  char* const p0 = nullptr;
shiqian's avatar
shiqian committed
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
  // Only way to get the Nokia compiler to compile the cast
  // is to have a separate void* variable first. Putting
  // the two casts on the same line doesn't work, neither does
  // a direct C-style to char*.
  void* pv1 = (void*)0x1234;  // NOLINT
  void* pv2 = (void*)0xABC0;  // NOLINT
  char* const p1 = reinterpret_cast<char*>(pv1);
  char* const p2 = reinterpret_cast<char*>(pv2);
  ASSERT_EQ(p1, p1);

  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
Gennadiy Civil's avatar
Gennadiy Civil committed
4872
                          "  p2\n    Which is:");
shiqian's avatar
shiqian committed
4873
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
Gennadiy Civil's avatar
Gennadiy Civil committed
4874
                          "  p2\n    Which is:");
shiqian's avatar
shiqian committed
4875
4876
4877
4878
4879
4880
4881
  EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
                                 reinterpret_cast<char*>(0xABC0)),
                       "ABC0");
}

// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, WideCharPointer) {
4882
  wchar_t* const p0 = nullptr;
shiqian's avatar
shiqian committed
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
  // Only way to get the Nokia compiler to compile the cast
  // is to have a separate void* variable first. Putting
  // the two casts on the same line doesn't work, neither does
  // a direct C-style to char*.
  void* pv1 = (void*)0x1234;  // NOLINT
  void* pv2 = (void*)0xABC0;  // NOLINT
  wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
  wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
  EXPECT_EQ(p0, p0);

  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
Gennadiy Civil's avatar
Gennadiy Civil committed
4894
                          "  p2\n    Which is:");
shiqian's avatar
shiqian committed
4895
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
Gennadiy Civil's avatar
Gennadiy Civil committed
4896
                          "  p2\n    Which is:");
shiqian's avatar
shiqian committed
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
  void* pv3 = (void*)0x1234;  // NOLINT
  void* pv4 = (void*)0xABC0;  // NOLINT
  const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
  const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
                          "p4");
}

// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, OtherPointer) {
4907
4908
  ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));
  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),
shiqian's avatar
shiqian committed
4909
4910
4911
4912
                                 reinterpret_cast<const int*>(0x1234)),
                       "0x1234");
}

4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
// A class that supports binary comparison operators but not streaming.
class UnprintableChar {
 public:
  explicit UnprintableChar(char ch) : char_(ch) {}

  bool operator==(const UnprintableChar& rhs) const {
    return char_ == rhs.char_;
  }
  bool operator!=(const UnprintableChar& rhs) const {
    return char_ != rhs.char_;
  }
  bool operator<(const UnprintableChar& rhs) const {
    return char_ < rhs.char_;
  }
  bool operator<=(const UnprintableChar& rhs) const {
    return char_ <= rhs.char_;
  }
  bool operator>(const UnprintableChar& rhs) const {
    return char_ > rhs.char_;
  }
  bool operator>=(const UnprintableChar& rhs) const {
    return char_ >= rhs.char_;
  }

 private:
  char char_;
};

// Tests that ASSERT_EQ() and friends don't require the arguments to
// be printable.
TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
  const UnprintableChar x('x'), y('y');
  ASSERT_EQ(x, x);
  EXPECT_NE(x, y);
  ASSERT_LT(x, y);
  EXPECT_LE(x, y);
  ASSERT_GT(y, x);
  EXPECT_GE(x, x);

  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
  EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
  EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
  EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");

  // Code tested by EXPECT_FATAL_FAILURE cannot reference local
  // variables, so we have to write UnprintableChar('x') instead of x.
4960
4961
#ifndef __BORLANDC__
  // ICE's in C++Builder.
4962
4963
4964
4965
  EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
                       "1-byte object <78>");
  EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
                       "1-byte object <78>");
4966
#endif
4967
4968
4969
4970
4971
4972
4973
4974
  EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
                       "1-byte object <79>");
  EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
                       "1-byte object <78>");
  EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
                       "1-byte object <79>");
}

shiqian's avatar
shiqian committed
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
// Tests the FRIEND_TEST macro.

// This class has a private member we want to test.  We will test it
// both in a TEST and in a TEST_F.
class Foo {
 public:
  Foo() {}

 private:
  int Bar() const { return 1; }

  // Declares the friend tests that can access the private member
  // Bar().
  FRIEND_TEST(FRIEND_TEST_Test, TEST);
  FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
};

// Tests that the FRIEND_TEST declaration allows a TEST to access a
// class's private members.  This should compile.
TEST(FRIEND_TEST_Test, TEST) {
  ASSERT_EQ(1, Foo().Bar());
}

// The fixture needed to test using FRIEND_TEST with TEST_F.
4999
class FRIEND_TEST_Test2 : public Test {
shiqian's avatar
shiqian committed
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
 protected:
  Foo foo;
};

// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
// class's private members.  This should compile.
TEST_F(FRIEND_TEST_Test2, TEST_F) {
  ASSERT_EQ(1, foo.Bar());
}

// Tests the life cycle of Test objects.

// The test fixture for testing the life cycle of Test objects.
//
// This class counts the number of live test objects that uses this
// fixture.
5016
class TestLifeCycleTest : public Test {
shiqian's avatar
shiqian committed
5017
5018
5019
5020
5021
5022
5023
 protected:
  // Constructor.  Increments the number of test objects that uses
  // this fixture.
  TestLifeCycleTest() { count_++; }

  // Destructor.  Decrements the number of test objects that uses this
  // fixture.
Abseil Team's avatar
Abseil Team committed
5024
  ~TestLifeCycleTest() override { count_--; }
shiqian's avatar
shiqian committed
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051

  // Returns the number of live test objects that uses this fixture.
  int count() const { return count_; }

 private:
  static int count_;
};

int TestLifeCycleTest::count_ = 0;

// Tests the life cycle of test objects.
TEST_F(TestLifeCycleTest, Test1) {
  // There should be only one test object in this test case that's
  // currently alive.
  ASSERT_EQ(1, count());
}

// Tests the life cycle of test objects.
TEST_F(TestLifeCycleTest, Test2) {
  // After Test1 is done and Test2 is started, there should still be
  // only one live test object, as the object for Test1 should've been
  // deleted.
  ASSERT_EQ(1, count());
}

}  // namespace

5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
// Tests that the copy constructor works when it is NOT optimized away by
// the compiler.
TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
  // Checks that the copy constructor doesn't try to dereference NULL pointers
  // in the source object.
  AssertionResult r1 = AssertionSuccess();
  AssertionResult r2 = r1;
  // The following line is added to prevent the compiler from optimizing
  // away the constructor call.
  r1 << "abc";

  AssertionResult r3 = r1;
  EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
  EXPECT_STREQ("abc", r1.message());
}

// Tests that AssertionSuccess and AssertionFailure construct
// AssertionResult objects as expected.
TEST(AssertionResultTest, ConstructionWorks) {
  AssertionResult r1 = AssertionSuccess();
  EXPECT_TRUE(r1);
  EXPECT_STREQ("", r1.message());

  AssertionResult r2 = AssertionSuccess() << "abc";
  EXPECT_TRUE(r2);
  EXPECT_STREQ("abc", r2.message());

  AssertionResult r3 = AssertionFailure();
  EXPECT_FALSE(r3);
  EXPECT_STREQ("", r3.message());

  AssertionResult r4 = AssertionFailure() << "def";
  EXPECT_FALSE(r4);
  EXPECT_STREQ("def", r4.message());

  AssertionResult r5 = AssertionFailure(Message() << "ghi");
  EXPECT_FALSE(r5);
  EXPECT_STREQ("ghi", r5.message());
}

5092
// Tests that the negation flips the predicate result but keeps the message.
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
TEST(AssertionResultTest, NegationWorks) {
  AssertionResult r1 = AssertionSuccess() << "abc";
  EXPECT_FALSE(!r1);
  EXPECT_STREQ("abc", (!r1).message());

  AssertionResult r2 = AssertionFailure() << "def";
  EXPECT_TRUE(!r2);
  EXPECT_STREQ("def", (!r2).message());
}

TEST(AssertionResultTest, StreamingWorks) {
  AssertionResult r = AssertionSuccess();
  r << "abc" << 'd' << 0 << true;
  EXPECT_STREQ("abcd0true", r.message());
5107
5108
5109
5110
5111
5112
}

TEST(AssertionResultTest, CanStreamOstreamManipulators) {
  AssertionResult r = AssertionSuccess();
  r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
  EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5113
5114
}

misterg's avatar
misterg committed
5115
// The next test uses explicit conversion operators
billydonahue's avatar
billydonahue committed
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136

TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
  struct ExplicitlyConvertibleToBool {
    explicit operator bool() const { return value; }
    bool value;
  };
  ExplicitlyConvertibleToBool v1 = {false};
  ExplicitlyConvertibleToBool v2 = {true};
  EXPECT_FALSE(v1);
  EXPECT_TRUE(v2);
}

struct ConvertibleToAssertionResult {
  operator AssertionResult() const { return AssertionResult(true); }
};

TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
  ConvertibleToAssertionResult obj;
  EXPECT_TRUE(obj);
}

shiqian's avatar
shiqian committed
5137
5138
5139
5140
// Tests streaming a user type whose definition and operator << are
// both in the global namespace.
class Base {
 public:
5141
  explicit Base(int an_x) : x_(an_x) {}
shiqian's avatar
shiqian committed
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
  int x() const { return x_; }
 private:
  int x_;
};
std::ostream& operator<<(std::ostream& os,
                         const Base& val) {
  return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
                         const Base* pointer) {
  return os << "(" << pointer->x() << ")";
}

TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5156
  Message msg;
shiqian's avatar
shiqian committed
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
  Base a(1);

  msg << a << &a;  // Uses ::operator<<.
  EXPECT_STREQ("1(1)", msg.GetString().c_str());
}

// Tests streaming a user type whose definition and operator<< are
// both in an unnamed namespace.
namespace {
class MyTypeInUnnamedNameSpace : public Base {
 public:
5168
  explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
shiqian's avatar
shiqian committed
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
};
std::ostream& operator<<(std::ostream& os,
                         const MyTypeInUnnamedNameSpace& val) {
  return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
                         const MyTypeInUnnamedNameSpace* pointer) {
  return os << "(" << pointer->x() << ")";
}
}  // namespace

TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5181
  Message msg;
shiqian's avatar
shiqian committed
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
  MyTypeInUnnamedNameSpace a(1);

  msg << a << &a;  // Uses <unnamed_namespace>::operator<<.
  EXPECT_STREQ("1(1)", msg.GetString().c_str());
}

// Tests streaming a user type whose definition and operator<< are
// both in a user namespace.
namespace namespace1 {
class MyTypeInNameSpace1 : public Base {
 public:
5193
  explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
shiqian's avatar
shiqian committed
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
};
std::ostream& operator<<(std::ostream& os,
                         const MyTypeInNameSpace1& val) {
  return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
                         const MyTypeInNameSpace1* pointer) {
  return os << "(" << pointer->x() << ")";
}
}  // namespace namespace1

TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5206
  Message msg;
shiqian's avatar
shiqian committed
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
  namespace1::MyTypeInNameSpace1 a(1);

  msg << a << &a;  // Uses namespace1::operator<<.
  EXPECT_STREQ("1(1)", msg.GetString().c_str());
}

// Tests streaming a user type whose definition is in a user namespace
// but whose operator<< is in the global namespace.
namespace namespace2 {
class MyTypeInNameSpace2 : public ::Base {
 public:
5218
  explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
shiqian's avatar
shiqian committed
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
};
}  // namespace namespace2
std::ostream& operator<<(std::ostream& os,
                         const namespace2::MyTypeInNameSpace2& val) {
  return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
                         const namespace2::MyTypeInNameSpace2* pointer) {
  return os << "(" << pointer->x() << ")";
}

TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5231
  Message msg;
shiqian's avatar
shiqian committed
5232
5233
5234
5235
5236
5237
5238
5239
  namespace2::MyTypeInNameSpace2 a(1);

  msg << a << &a;  // Uses ::operator<<.
  EXPECT_STREQ("1(1)", msg.GetString().c_str());
}

// Tests streaming NULL pointers to testing::Message.
TEST(MessageTest, NullPointers) {
5240
  Message msg;
5241
5242
5243
5244
5245
5246
  char* const p1 = nullptr;
  unsigned char* const p2 = nullptr;
  int* p3 = nullptr;
  double* p4 = nullptr;
  bool* p5 = nullptr;
  Message* p6 = nullptr;
shiqian's avatar
shiqian committed
5247
5248
5249
5250
5251
5252
5253
5254
5255

  msg << p1 << p2 << p3 << p4 << p5 << p6;
  ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
               msg.GetString().c_str());
}

// Tests streaming wide strings to testing::Message.
TEST(MessageTest, WideStrings) {
  // Streams a NULL of type const wchar_t*.
5256
  const wchar_t* const_wstr = nullptr;
shiqian's avatar
shiqian committed
5257
5258
5259
5260
  EXPECT_STREQ("(null)",
               (Message() << const_wstr).GetString().c_str());

  // Streams a NULL of type wchar_t*.
5261
  wchar_t* wstr = nullptr;
shiqian's avatar
shiqian committed
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
  EXPECT_STREQ("(null)",
               (Message() << wstr).GetString().c_str());

  // Streams a non-NULL of type const wchar_t*.
  const_wstr = L"abc\x8119";
  EXPECT_STREQ("abc\xe8\x84\x99",
               (Message() << const_wstr).GetString().c_str());

  // Streams a non-NULL of type wchar_t*.
  wstr = const_cast<wchar_t*>(const_wstr);
  EXPECT_STREQ("abc\xe8\x84\x99",
               (Message() << wstr).GetString().c_str());
}


// This line tests that we can define tests in the testing namespace.
namespace testing {

// Tests the TestInfo class.

5282
class TestInfoTest : public Test {
shiqian's avatar
shiqian committed
5283
 protected:
5284
  static const TestInfo* GetTestInfo(const char* test_name) {
misterg's avatar
misterg committed
5285
5286
    const TestSuite* const test_suite =
        GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr);
5287

misterg's avatar
misterg committed
5288
5289
    for (int i = 0; i < test_suite->total_test_count(); ++i) {
      const TestInfo* const test_info = test_suite->GetTestInfo(i);
5290
5291
5292
      if (strcmp(test_name, test_info->name()) == 0)
        return test_info;
    }
5293
    return nullptr;
shiqian's avatar
shiqian committed
5294
5295
5296
  }

  static const TestResult* GetTestResult(
5297
      const TestInfo* test_info) {
shiqian's avatar
shiqian committed
5298
5299
5300
5301
5302
5303
    return test_info->result();
  }
};

// Tests TestInfo::test_case_name() and TestInfo::name().
TEST_F(TestInfoTest, Names) {
5304
  const TestInfo* const test_info = GetTestInfo("Names");
shiqian's avatar
shiqian committed
5305
5306
5307
5308
5309
5310
5311

  ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
  ASSERT_STREQ("Names", test_info->name());
}

// Tests TestInfo::result().
TEST_F(TestInfoTest, result) {
5312
  const TestInfo* const test_info = GetTestInfo("result");
shiqian's avatar
shiqian committed
5313
5314

  // Initially, there is no TestPartResult for this test.
5315
  ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian's avatar
shiqian committed
5316
5317

  // After the previous assertion, there is still none.
5318
  ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
shiqian's avatar
shiqian committed
5319
5320
}

kosak's avatar
kosak committed
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
#define VERIFY_CODE_LOCATION \
  const int expected_line = __LINE__ - 1; \
  const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
  ASSERT_TRUE(test_info); \
  EXPECT_STREQ(__FILE__, test_info->file()); \
  EXPECT_EQ(expected_line, test_info->line())

TEST(CodeLocationForTEST, Verify) {
  VERIFY_CODE_LOCATION;
}

class CodeLocationForTESTF : public Test {
};

TEST_F(CodeLocationForTESTF, Verify) {
  VERIFY_CODE_LOCATION;
}

class CodeLocationForTESTP : public TestWithParam<int> {
};

TEST_P(CodeLocationForTESTP, Verify) {
  VERIFY_CODE_LOCATION;
}

misterg's avatar
misterg committed
5346
INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
kosak's avatar
kosak committed
5347
5348
5349
5350
5351

template <typename T>
class CodeLocationForTYPEDTEST : public Test {
};

misterg's avatar
misterg committed
5352
TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);
kosak's avatar
kosak committed
5353
5354
5355
5356
5357
5358
5359
5360
5361

TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
  VERIFY_CODE_LOCATION;
}

template <typename T>
class CodeLocationForTYPEDTESTP : public Test {
};

misterg's avatar
misterg committed
5362
TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
kosak's avatar
kosak committed
5363
5364
5365
5366
5367

TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
  VERIFY_CODE_LOCATION;
}

misterg's avatar
misterg committed
5368
REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
kosak's avatar
kosak committed
5369

misterg's avatar
misterg committed
5370
INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
kosak's avatar
kosak committed
5371
5372
5373

#undef VERIFY_CODE_LOCATION

shiqian's avatar
shiqian committed
5374
// Tests setting up and tearing down a test case.
misterg's avatar
misterg committed
5375
5376
// Legacy API is deprecated but still available
#ifndef REMOVE_LEGACY_TEST_CASEAPI
5377
class SetUpTestCaseTest : public Test {
shiqian's avatar
shiqian committed
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
 protected:
  // This will be called once before the first test in this test case
  // is run.
  static void SetUpTestCase() {
    printf("Setting up the test case . . .\n");

    // Initializes some shared resource.  In this simple example, we
    // just create a C string.  More complex stuff can be done if
    // desired.
    shared_resource_ = "123";

    // Increments the number of test cases that have been set up.
    counter_++;

    // SetUpTestCase() should be called only once.
    EXPECT_EQ(1, counter_);
  }

  // This will be called once after the last test in this test case is
  // run.
  static void TearDownTestCase() {
    printf("Tearing down the test case . . .\n");

    // Decrements the number of test cases that have been set up.
    counter_--;

    // TearDownTestCase() should be called only once.
    EXPECT_EQ(0, counter_);

    // Cleans up the shared resource.
5408
    shared_resource_ = nullptr;
shiqian's avatar
shiqian committed
5409
5410
5411
  }

  // This will be called before each test in this test case.
Abseil Team's avatar
Abseil Team committed
5412
  void SetUp() override {
shiqian's avatar
shiqian committed
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
    // SetUpTestCase() should be called only once, so counter_ should
    // always be 1.
    EXPECT_EQ(1, counter_);
  }

  // Number of test cases that have been set up.
  static int counter_;

  // Some resource to be shared by all tests in this test case.
  static const char* shared_resource_;
};

int SetUpTestCaseTest::counter_ = 0;
5426
const char* SetUpTestCaseTest::shared_resource_ = nullptr;
shiqian's avatar
shiqian committed
5427
5428

// A test that uses the shared resource.
5429
TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
shiqian's avatar
shiqian committed
5430
5431
5432
5433
5434

// Another test that uses the shared resource.
TEST_F(SetUpTestCaseTest, Test2) {
  EXPECT_STREQ("123", shared_resource_);
}
misterg's avatar
misterg committed
5435
#endif  //  REMOVE_LEGACY_TEST_CASEAPI
shiqian's avatar
shiqian committed
5436

misterg's avatar
misterg committed
5437
// Tests SetupTestSuite/TearDown TestSuite
misterg's avatar
misterg committed
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
class SetUpTestSuiteTest : public Test {
 protected:
  // This will be called once before the first test in this test case
  // is run.
  static void SetUpTestSuite() {
    printf("Setting up the test suite . . .\n");

    // Initializes some shared resource.  In this simple example, we
    // just create a C string.  More complex stuff can be done if
    // desired.
    shared_resource_ = "123";

    // Increments the number of test cases that have been set up.
    counter_++;

    // SetUpTestSuite() should be called only once.
    EXPECT_EQ(1, counter_);
  }

  // This will be called once after the last test in this test case is
  // run.
  static void TearDownTestSuite() {
    printf("Tearing down the test suite . . .\n");

    // Decrements the number of test suites that have been set up.
    counter_--;

    // TearDownTestSuite() should be called only once.
    EXPECT_EQ(0, counter_);

    // Cleans up the shared resource.
    shared_resource_ = nullptr;
  }

  // This will be called before each test in this test case.
  void SetUp() override {
    // SetUpTestSuite() should be called only once, so counter_ should
    // always be 1.
    EXPECT_EQ(1, counter_);
  }

  // Number of test suites that have been set up.
  static int counter_;

  // Some resource to be shared by all tests in this test case.
  static const char* shared_resource_;
};

int SetUpTestSuiteTest::counter_ = 0;
const char* SetUpTestSuiteTest::shared_resource_ = nullptr;

// A test that uses the shared resource.
TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) {
  EXPECT_STRNE(nullptr, shared_resource_);
}

// Another test that uses the shared resource.
TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
  EXPECT_STREQ("123", shared_resource_);
}
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5498
5499

// The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.
shiqian's avatar
shiqian committed
5500
5501
5502
5503

// The Flags struct stores a copy of all Google Test flags.
struct Flags {
  // Constructs a Flags struct where each flag has its default value.
5504
5505
  Flags() : also_run_disabled_tests(false),
            break_on_failure(false),
shiqian's avatar
shiqian committed
5506
            catch_exceptions(false),
5507
            death_test_use_fork(false),
shiqian's avatar
shiqian committed
5508
5509
5510
            filter(""),
            list_tests(false),
            output(""),
5511
            print_time(true),
5512
            random_seed(0),
5513
            repeat(1),
5514
            shuffle(false),
5515
            stack_trace_depth(kMaxStackTraceDepth),
5516
            stream_result_to(""),
5517
            throw_on_failure(false) {}
shiqian's avatar
shiqian committed
5518
5519
5520

  // Factory methods.

Gennadiy Civil's avatar
Gennadiy Civil committed
5521
  // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5522
5523
5524
5525
5526
5527
5528
  // the given value.
  static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
    Flags flags;
    flags.also_run_disabled_tests = also_run_disabled_tests;
    return flags;
  }

Gennadiy Civil's avatar
Gennadiy Civil committed
5529
  // Creates a Flags struct where the gtest_break_on_failure flag has
shiqian's avatar
shiqian committed
5530
5531
5532
5533
5534
5535
5536
  // the given value.
  static Flags BreakOnFailure(bool break_on_failure) {
    Flags flags;
    flags.break_on_failure = break_on_failure;
    return flags;
  }

Gennadiy Civil's avatar
Gennadiy Civil committed
5537
  // Creates a Flags struct where the gtest_catch_exceptions flag has
shiqian's avatar
shiqian committed
5538
5539
5540
5541
5542
5543
5544
  // the given value.
  static Flags CatchExceptions(bool catch_exceptions) {
    Flags flags;
    flags.catch_exceptions = catch_exceptions;
    return flags;
  }

Gennadiy Civil's avatar
Gennadiy Civil committed
5545
  // Creates a Flags struct where the gtest_death_test_use_fork flag has
5546
5547
5548
5549
5550
5551
5552
  // the given value.
  static Flags DeathTestUseFork(bool death_test_use_fork) {
    Flags flags;
    flags.death_test_use_fork = death_test_use_fork;
    return flags;
  }

Gennadiy Civil's avatar
Gennadiy Civil committed
5553
  // Creates a Flags struct where the gtest_filter flag has the given
shiqian's avatar
shiqian committed
5554
5555
5556
5557
5558
5559
5560
  // value.
  static Flags Filter(const char* filter) {
    Flags flags;
    flags.filter = filter;
    return flags;
  }

Gennadiy Civil's avatar
Gennadiy Civil committed
5561
  // Creates a Flags struct where the gtest_list_tests flag has the
shiqian's avatar
shiqian committed
5562
5563
5564
5565
5566
5567
5568
  // given value.
  static Flags ListTests(bool list_tests) {
    Flags flags;
    flags.list_tests = list_tests;
    return flags;
  }

Gennadiy Civil's avatar
Gennadiy Civil committed
5569
  // Creates a Flags struct where the gtest_output flag has the given
shiqian's avatar
shiqian committed
5570
5571
5572
5573
5574
5575
5576
  // value.
  static Flags Output(const char* output) {
    Flags flags;
    flags.output = output;
    return flags;
  }

Gennadiy Civil's avatar
Gennadiy Civil committed
5577
  // Creates a Flags struct where the gtest_print_time flag has the given
5578
5579
5580
5581
5582
5583
5584
  // value.
  static Flags PrintTime(bool print_time) {
    Flags flags;
    flags.print_time = print_time;
    return flags;
  }

Gennadiy Civil's avatar
Gennadiy Civil committed
5585
  // Creates a Flags struct where the gtest_random_seed flag has the given
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5586
  // value.
5587
5588
5589
5590
5591
5592
  static Flags RandomSeed(Int32 random_seed) {
    Flags flags;
    flags.random_seed = random_seed;
    return flags;
  }

Gennadiy Civil's avatar
Gennadiy Civil committed
5593
  // Creates a Flags struct where the gtest_repeat flag has the given
shiqian's avatar
shiqian committed
5594
5595
5596
5597
5598
5599
5600
  // value.
  static Flags Repeat(Int32 repeat) {
    Flags flags;
    flags.repeat = repeat;
    return flags;
  }

Gennadiy Civil's avatar
Gennadiy Civil committed
5601
  // Creates a Flags struct where the gtest_shuffle flag has the given
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5602
  // value.
5603
5604
5605
5606
5607
5608
  static Flags Shuffle(bool shuffle) {
    Flags flags;
    flags.shuffle = shuffle;
    return flags;
  }

5609
5610
5611
5612
5613
5614
5615
5616
  // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
  // the given value.
  static Flags StackTraceDepth(Int32 stack_trace_depth) {
    Flags flags;
    flags.stack_trace_depth = stack_trace_depth;
    return flags;
  }

5617
5618
5619
5620
5621
5622
5623
5624
  // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
  // the given value.
  static Flags StreamResultTo(const char* stream_result_to) {
    Flags flags;
    flags.stream_result_to = stream_result_to;
    return flags;
  }

Gennadiy Civil's avatar
Gennadiy Civil committed
5625
  // Creates a Flags struct where the gtest_throw_on_failure flag has
5626
5627
5628
5629
5630
5631
5632
  // the given value.
  static Flags ThrowOnFailure(bool throw_on_failure) {
    Flags flags;
    flags.throw_on_failure = throw_on_failure;
    return flags;
  }

shiqian's avatar
shiqian committed
5633
  // These fields store the flag values.
5634
  bool also_run_disabled_tests;
shiqian's avatar
shiqian committed
5635
5636
  bool break_on_failure;
  bool catch_exceptions;
5637
  bool death_test_use_fork;
shiqian's avatar
shiqian committed
5638
5639
5640
  const char* filter;
  bool list_tests;
  const char* output;
5641
  bool print_time;
5642
  Int32 random_seed;
shiqian's avatar
shiqian committed
5643
  Int32 repeat;
5644
  bool shuffle;
5645
  Int32 stack_trace_depth;
5646
  const char* stream_result_to;
5647
  bool throw_on_failure;
shiqian's avatar
shiqian committed
5648
5649
};

Gennadiy Civil's avatar
 
Gennadiy Civil committed
5650
5651
// Fixture for testing ParseGoogleTestFlagsOnly().
class ParseFlagsTest : public Test {
shiqian's avatar
shiqian committed
5652
5653
 protected:
  // Clears the flags before each test.
Abseil Team's avatar
Abseil Team committed
5654
  void SetUp() override {
5655
    GTEST_FLAG(also_run_disabled_tests) = false;
shiqian's avatar
shiqian committed
5656
5657
    GTEST_FLAG(break_on_failure) = false;
    GTEST_FLAG(catch_exceptions) = false;
5658
    GTEST_FLAG(death_test_use_fork) = false;
shiqian's avatar
shiqian committed
5659
5660
5661
    GTEST_FLAG(filter) = "";
    GTEST_FLAG(list_tests) = false;
    GTEST_FLAG(output) = "";
5662
    GTEST_FLAG(print_time) = true;
5663
    GTEST_FLAG(random_seed) = 0;
shiqian's avatar
shiqian committed
5664
    GTEST_FLAG(repeat) = 1;
5665
    GTEST_FLAG(shuffle) = false;
5666
    GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
5667
    GTEST_FLAG(stream_result_to) = "";
5668
    GTEST_FLAG(throw_on_failure) = false;
shiqian's avatar
shiqian committed
5669
5670
5671
5672
  }

  // Asserts that two narrow or wide string arrays are equal.
  template <typename CharType>
5673
5674
  static void AssertStringArrayEq(int size1, CharType** array1, int size2,
                                  CharType** array2) {
shiqian's avatar
shiqian committed
5675
5676
    ASSERT_EQ(size1, size2) << " Array sizes different.";

5677
    for (int i = 0; i != size1; i++) {
shiqian's avatar
shiqian committed
5678
5679
5680
5681
5682
5683
      ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
    }
  }

  // Verifies that the flag values match the expected values.
  static void CheckFlags(const Flags& expected) {
5684
5685
    EXPECT_EQ(expected.also_run_disabled_tests,
              GTEST_FLAG(also_run_disabled_tests));
shiqian's avatar
shiqian committed
5686
5687
    EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
    EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
5688
    EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
shiqian's avatar
shiqian committed
5689
5690
5691
    EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
    EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
    EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
5692
    EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
5693
    EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
shiqian's avatar
shiqian committed
5694
    EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
5695
    EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
5696
    EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
5697
5698
5699
    EXPECT_STREQ(expected.stream_result_to,
                 GTEST_FLAG(stream_result_to).c_str());
    EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
shiqian's avatar
shiqian committed
5700
5701
5702
5703
5704
5705
5706
5707
  }

  // Parses a command line (specified by argc1 and argv1), then
  // verifies that the flag values are expected and that the
  // recognized flags are removed from the command line.
  template <typename CharType>
  static void TestParsingFlags(int argc1, const CharType** argv1,
                               int argc2, const CharType** argv2,
5708
5709
5710
5711
                               const Flags& expected, bool should_print_help) {
    const bool saved_help_flag = ::testing::internal::g_help_flag;
    ::testing::internal::g_help_flag = false;

Gennadiy Civil's avatar
 
Gennadiy Civil committed
5712
# if GTEST_HAS_STREAM_REDIRECTION
5713
    CaptureStdout();
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5714
# endif
5715

shiqian's avatar
shiqian committed
5716
    // Parses the command line.
5717
    internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
shiqian's avatar
shiqian committed
5718

Gennadiy Civil's avatar
 
Gennadiy Civil committed
5719
# if GTEST_HAS_STREAM_REDIRECTION
5720
    const std::string captured_stdout = GetCapturedStdout();
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5721
# endif
5722

shiqian's avatar
shiqian committed
5723
5724
5725
5726
5727
5728
    // Verifies the flag values.
    CheckFlags(expected);

    // Verifies that the recognized flags are removed from the command
    // line.
    AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5729
5730
5731
5732
5733

    // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
    // help message for the flags it recognizes.
    EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);

Gennadiy Civil's avatar
 
Gennadiy Civil committed
5734
# if GTEST_HAS_STREAM_REDIRECTION
5735
5736
5737
5738
5739
5740
5741
5742
    const char* const expected_help_fragment =
        "This program contains tests written using";
    if (should_print_help) {
      EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
    } else {
      EXPECT_PRED_FORMAT2(IsNotSubstring,
                          expected_help_fragment, captured_stdout);
    }
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5743
# endif  // GTEST_HAS_STREAM_REDIRECTION
5744
5745

    ::testing::internal::g_help_flag = saved_help_flag;
shiqian's avatar
shiqian committed
5746
5747
5748
5749
  }

  // This macro wraps TestParsingFlags s.t. the user doesn't need
  // to specify the array sizes.
5750

Gennadiy Civil's avatar
 
Gennadiy Civil committed
5751
# define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
shiqian's avatar
shiqian committed
5752
  TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5753
5754
                   sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
                   expected, should_print_help)
shiqian's avatar
shiqian committed
5755
5756
5757
};

// Tests parsing an empty command line.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5758
TEST_F(ParseFlagsTest, Empty) {
5759
  const char* argv[] = {nullptr};
shiqian's avatar
shiqian committed
5760

5761
  const char* argv2[] = {nullptr};
shiqian's avatar
shiqian committed
5762

5763
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
shiqian's avatar
shiqian committed
5764
5765
5766
}

// Tests parsing a command line that has no flag.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5767
TEST_F(ParseFlagsTest, NoFlag) {
5768
  const char* argv[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5769

5770
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5771

5772
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
shiqian's avatar
shiqian committed
5773
5774
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5775
// Tests parsing a bad --gtest_filter flag.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5776
TEST_F(ParseFlagsTest, FilterBad) {
5777
  const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
shiqian's avatar
shiqian committed
5778

5779
  const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
shiqian's avatar
shiqian committed
5780

5781
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
shiqian's avatar
shiqian committed
5782
5783
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5784
// Tests parsing an empty --gtest_filter flag.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5785
TEST_F(ParseFlagsTest, FilterEmpty) {
5786
  const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
shiqian's avatar
shiqian committed
5787

5788
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5789

5790
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
shiqian's avatar
shiqian committed
5791
5792
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5793
// Tests parsing a non-empty --gtest_filter flag.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5794
TEST_F(ParseFlagsTest, FilterNonEmpty) {
5795
  const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr};
shiqian's avatar
shiqian committed
5796

5797
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5798

5799
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
shiqian's avatar
shiqian committed
5800
5801
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5802
// Tests parsing --gtest_break_on_failure.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5803
TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {
5804
  const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr};
shiqian's avatar
shiqian committed
5805

5806
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5807

5808
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
shiqian's avatar
shiqian committed
5809
5810
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5811
// Tests parsing --gtest_break_on_failure=0.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5812
TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {
5813
  const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr};
shiqian's avatar
shiqian committed
5814

5815
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5816

5817
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian's avatar
shiqian committed
5818
5819
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5820
// Tests parsing --gtest_break_on_failure=f.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5821
TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {
5822
  const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr};
shiqian's avatar
shiqian committed
5823

5824
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5825

5826
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian's avatar
shiqian committed
5827
5828
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5829
// Tests parsing --gtest_break_on_failure=F.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5830
TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {
5831
  const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr};
shiqian's avatar
shiqian committed
5832

5833
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5834

5835
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
shiqian's avatar
shiqian committed
5836
5837
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5838
// Tests parsing a --gtest_break_on_failure flag that has a "true"
shiqian's avatar
shiqian committed
5839
// definition.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5840
TEST_F(ParseFlagsTest, BreakOnFailureTrue) {
5841
  const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr};
shiqian's avatar
shiqian committed
5842

5843
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5844

5845
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
shiqian's avatar
shiqian committed
5846
5847
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5848
// Tests parsing --gtest_catch_exceptions.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5849
TEST_F(ParseFlagsTest, CatchExceptions) {
5850
  const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr};
shiqian's avatar
shiqian committed
5851

5852
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5853

5854
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
shiqian's avatar
shiqian committed
5855
5856
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5857
// Tests parsing --gtest_death_test_use_fork.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5858
TEST_F(ParseFlagsTest, DeathTestUseFork) {
5859
  const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr};
5860

5861
  const char* argv2[] = {"foo.exe", nullptr};
5862

5863
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5864
5865
}

shiqian's avatar
shiqian committed
5866
5867
// Tests having the same flag twice with different values.  The
// expected behavior is that the one coming last takes precedence.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5868
TEST_F(ParseFlagsTest, DuplicatedFlags) {
5869
5870
  const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b",
                        nullptr};
shiqian's avatar
shiqian committed
5871

5872
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5873

5874
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
shiqian's avatar
shiqian committed
5875
5876
5877
}

// Tests having an unrecognized flag on the command line.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5878
TEST_F(ParseFlagsTest, UnrecognizedFlag) {
5879
5880
5881
  const char* argv[] = {"foo.exe", "--gtest_break_on_failure",
                        "bar",  // Unrecognized by Google Test.
                        "--gtest_filter=b", nullptr};
shiqian's avatar
shiqian committed
5882

5883
  const char* argv2[] = {"foo.exe", "bar", nullptr};
shiqian's avatar
shiqian committed
5884
5885
5886
5887

  Flags flags;
  flags.break_on_failure = true;
  flags.filter = "b";
5888
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
shiqian's avatar
shiqian committed
5889
5890
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5891
// Tests having a --gtest_list_tests flag
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5892
TEST_F(ParseFlagsTest, ListTestsFlag) {
5893
  const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr};
shiqian's avatar
shiqian committed
5894

5895
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5896

5897
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
shiqian's avatar
shiqian committed
5898
5899
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5900
// Tests having a --gtest_list_tests flag with a "true" value
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5901
TEST_F(ParseFlagsTest, ListTestsTrue) {
5902
  const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr};
shiqian's avatar
shiqian committed
5903

5904
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5905

5906
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
shiqian's avatar
shiqian committed
5907
5908
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5909
// Tests having a --gtest_list_tests flag with a "false" value
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5910
TEST_F(ParseFlagsTest, ListTestsFalse) {
5911
  const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr};
shiqian's avatar
shiqian committed
5912

5913
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5914

5915
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian's avatar
shiqian committed
5916
5917
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5918
// Tests parsing --gtest_list_tests=f.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5919
TEST_F(ParseFlagsTest, ListTestsFalse_f) {
5920
  const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr};
shiqian's avatar
shiqian committed
5921

5922
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5923

5924
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian's avatar
shiqian committed
5925
5926
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5927
// Tests parsing --gtest_list_tests=F.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5928
TEST_F(ParseFlagsTest, ListTestsFalse_F) {
5929
  const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr};
shiqian's avatar
shiqian committed
5930

5931
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5932

5933
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
shiqian's avatar
shiqian committed
5934
5935
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5936
// Tests parsing --gtest_output (invalid).
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5937
TEST_F(ParseFlagsTest, OutputEmpty) {
5938
  const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
shiqian's avatar
shiqian committed
5939

5940
  const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
shiqian's avatar
shiqian committed
5941

5942
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
shiqian's avatar
shiqian committed
5943
5944
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5945
// Tests parsing --gtest_output=xml
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5946
TEST_F(ParseFlagsTest, OutputXml) {
5947
  const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
shiqian's avatar
shiqian committed
5948

5949
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5950

5951
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
shiqian's avatar
shiqian committed
5952
5953
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5954
// Tests parsing --gtest_output=xml:file
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5955
TEST_F(ParseFlagsTest, OutputXmlFile) {
5956
  const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr};
shiqian's avatar
shiqian committed
5957

5958
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5959

5960
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
shiqian's avatar
shiqian committed
5961
5962
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5963
// Tests parsing --gtest_output=xml:directory/path/
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5964
TEST_F(ParseFlagsTest, OutputXmlDirectory) {
5965
5966
  const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/",
                        nullptr};
shiqian's avatar
shiqian committed
5967

5968
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
5969

5970
5971
  GTEST_TEST_PARSING_FLAGS_(argv, argv2,
                            Flags::Output("xml:directory/path/"), false);
shiqian's avatar
shiqian committed
5972
5973
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5974
// Tests having a --gtest_print_time flag
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5975
TEST_F(ParseFlagsTest, PrintTimeFlag) {
5976
  const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
5977

5978
  const char* argv2[] = {"foo.exe", nullptr};
5979

5980
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
5981
5982
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5983
// Tests having a --gtest_print_time flag with a "true" value
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5984
TEST_F(ParseFlagsTest, PrintTimeTrue) {
5985
  const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr};
5986

5987
  const char* argv2[] = {"foo.exe", nullptr};
5988

5989
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
5990
5991
}

Gennadiy Civil's avatar
Gennadiy Civil committed
5992
// Tests having a --gtest_print_time flag with a "false" value
Gennadiy Civil's avatar
 
Gennadiy Civil committed
5993
TEST_F(ParseFlagsTest, PrintTimeFalse) {
5994
  const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr};
5995

5996
  const char* argv2[] = {"foo.exe", nullptr};
5997

5998
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
5999
6000
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6001
// Tests parsing --gtest_print_time=f.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6002
TEST_F(ParseFlagsTest, PrintTimeFalse_f) {
6003
  const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr};
6004

6005
  const char* argv2[] = {"foo.exe", nullptr};
6006

6007
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6008
6009
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6010
// Tests parsing --gtest_print_time=F.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6011
TEST_F(ParseFlagsTest, PrintTimeFalse_F) {
6012
  const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr};
6013

6014
  const char* argv2[] = {"foo.exe", nullptr};
6015

6016
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6017
6018
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6019
// Tests parsing --gtest_random_seed=number
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6020
TEST_F(ParseFlagsTest, RandomSeed) {
6021
  const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr};
6022

6023
  const char* argv2[] = {"foo.exe", nullptr};
6024

6025
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6026
6027
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6028
// Tests parsing --gtest_repeat=number
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6029
TEST_F(ParseFlagsTest, Repeat) {
6030
  const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr};
shiqian's avatar
shiqian committed
6031

6032
  const char* argv2[] = {"foo.exe", nullptr};
shiqian's avatar
shiqian committed
6033

6034
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
shiqian's avatar
shiqian committed
6035
6036
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6037
// Tests having a --gtest_also_run_disabled_tests flag
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6038
TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
6039
  const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
6040

6041
  const char* argv2[] = {"foo.exe", nullptr};
6042

6043
6044
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
                            false);
6045
6046
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6047
// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6048
TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {
6049
6050
  const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1",
                        nullptr};
6051

6052
  const char* argv2[] = {"foo.exe", nullptr};
6053

6054
6055
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
                            false);
6056
6057
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6058
// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6059
TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {
6060
6061
  const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0",
                        nullptr};
6062

6063
  const char* argv2[] = {"foo.exe", nullptr};
6064

6065
6066
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false),
                            false);
6067
6068
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6069
// Tests parsing --gtest_shuffle.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6070
TEST_F(ParseFlagsTest, ShuffleWithoutValue) {
6071
  const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr};
6072

6073
  const char* argv2[] = {"foo.exe", nullptr};
6074

6075
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6076
6077
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6078
// Tests parsing --gtest_shuffle=0.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6079
TEST_F(ParseFlagsTest, ShuffleFalse_0) {
6080
  const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr};
6081

6082
  const char* argv2[] = {"foo.exe", nullptr};
6083

6084
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6085
6086
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6087
// Tests parsing a --gtest_shuffle flag that has a "true" definition.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6088
TEST_F(ParseFlagsTest, ShuffleTrue) {
6089
  const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr};
6090

6091
  const char* argv2[] = {"foo.exe", nullptr};
6092

6093
6094
6095
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6096
// Tests parsing --gtest_stack_trace_depth=number.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6097
TEST_F(ParseFlagsTest, StackTraceDepth) {
6098
  const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr};
6099

6100
  const char* argv2[] = {"foo.exe", nullptr};
6101
6102

  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6103
}
6104

Gennadiy Civil's avatar
 
Gennadiy Civil committed
6105
TEST_F(ParseFlagsTest, StreamResultTo) {
6106
6107
  const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234",
                        nullptr};
6108

6109
  const char* argv2[] = {"foo.exe", nullptr};
6110
6111
6112
6113
6114

  GTEST_TEST_PARSING_FLAGS_(
      argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6115
// Tests parsing --gtest_throw_on_failure.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6116
TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
6117
  const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr};
6118

6119
  const char* argv2[] = {"foo.exe", nullptr};
6120

6121
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6122
6123
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6124
// Tests parsing --gtest_throw_on_failure=0.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6125
TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {
6126
  const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr};
6127

6128
  const char* argv2[] = {"foo.exe", nullptr};
6129

6130
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
6131
6132
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6133
// Tests parsing a --gtest_throw_on_failure flag that has a "true"
6134
// definition.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6135
TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
6136
  const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr};
6137

6138
  const char* argv2[] = {"foo.exe", nullptr};
6139

6140
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6141
6142
}

Gennadiy Civil's avatar
 
Gennadiy Civil committed
6143
# if GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
6144
// Tests parsing wide strings.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6145
TEST_F(ParseFlagsTest, WideStrings) {
shiqian's avatar
shiqian committed
6146
6147
  const wchar_t* argv[] = {
    L"foo.exe",
Gennadiy Civil's avatar
Gennadiy Civil committed
6148
6149
6150
6151
    L"--gtest_filter=Foo*",
    L"--gtest_list_tests=1",
    L"--gtest_break_on_failure",
    L"--non_gtest_flag",
shiqian's avatar
shiqian committed
6152
6153
6154
6155
6156
    NULL
  };

  const wchar_t* argv2[] = {
    L"foo.exe",
Gennadiy Civil's avatar
Gennadiy Civil committed
6157
    L"--non_gtest_flag",
shiqian's avatar
shiqian committed
6158
6159
6160
6161
6162
6163
6164
6165
    NULL
  };

  Flags expected_flags;
  expected_flags.break_on_failure = true;
  expected_flags.filter = "Foo*";
  expected_flags.list_tests = true;

6166
  GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
shiqian's avatar
shiqian committed
6167
}
kosak's avatar
kosak committed
6168
# endif  // GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
6169

kosak's avatar
kosak committed
6170
#if GTEST_USE_OWN_FLAGFILE_FLAG_
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6171
class FlagfileTest : public ParseFlagsTest {
kosak's avatar
kosak committed
6172
6173
 public:
  virtual void SetUp() {
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6174
    ParseFlagsTest::SetUp();
kosak's avatar
kosak committed
6175
6176

    testdata_path_.Set(internal::FilePath(
6177
        testing::TempDir() + internal::GetCurrentExecutableName().string() +
kosak's avatar
kosak committed
6178
6179
6180
6181
6182
6183
6184
        "_flagfile_test"));
    testing::internal::posix::RmDir(testdata_path_.c_str());
    EXPECT_TRUE(testdata_path_.CreateFolder());
  }

  virtual void TearDown() {
    testing::internal::posix::RmDir(testdata_path_.c_str());
Gennadiy Civil's avatar
 
Gennadiy Civil committed
6185
    ParseFlagsTest::TearDown();
kosak's avatar
kosak committed
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
  }

  internal::FilePath CreateFlagfile(const char* contents) {
    internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
        testdata_path_, internal::FilePath("unique"), "txt"));
    FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
    fprintf(f, "%s", contents);
    fclose(f);
    return file_path;
  }

 private:
  internal::FilePath testdata_path_;
};

// Tests an empty flagfile.
TEST_F(FlagfileTest, Empty) {
  internal::FilePath flagfile_path(CreateFlagfile(""));
  std::string flagfile_flag =
      std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();

6207
  const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
kosak's avatar
kosak committed
6208

6209
  const char* argv2[] = {"foo.exe", nullptr};
kosak's avatar
kosak committed
6210
6211
6212
6213

  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6214
// Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
kosak's avatar
kosak committed
6215
6216
6217
6218
6219
6220
TEST_F(FlagfileTest, FilterNonEmpty) {
  internal::FilePath flagfile_path(CreateFlagfile(
      "--"  GTEST_FLAG_PREFIX_  "filter=abc"));
  std::string flagfile_flag =
      std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();

6221
  const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
kosak's avatar
kosak committed
6222

6223
  const char* argv2[] = {"foo.exe", nullptr};
kosak's avatar
kosak committed
6224
6225
6226
6227

  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
}

Gennadiy Civil's avatar
Gennadiy Civil committed
6228
// Tests passing several flags via --gtest_flagfile.
kosak's avatar
kosak committed
6229
6230
6231
6232
6233
6234
6235
6236
TEST_F(FlagfileTest, SeveralFlags) {
  internal::FilePath flagfile_path(CreateFlagfile(
      "--"  GTEST_FLAG_PREFIX_  "filter=abc\n"
      "--"  GTEST_FLAG_PREFIX_  "break_on_failure\n"
      "--"  GTEST_FLAG_PREFIX_  "list_tests"));
  std::string flagfile_flag =
      std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();

6237
  const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
kosak's avatar
kosak committed
6238

6239
  const char* argv2[] = {"foo.exe", nullptr};
kosak's avatar
kosak committed
6240
6241
6242
6243
6244
6245
6246
6247

  Flags expected_flags;
  expected_flags.break_on_failure = true;
  expected_flags.filter = "abc";
  expected_flags.list_tests = true;

  GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
}
kosak's avatar
kosak committed
6248
#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
kosak's avatar
kosak committed
6249

shiqian's avatar
shiqian committed
6250
6251
6252
6253
6254
// Tests current_test_info() in UnitTest.
class CurrentTestInfoTest : public Test {
 protected:
  // Tests that current_test_info() returns NULL before the first test in
  // the test case is run.
misterg's avatar
misterg committed
6255
  static void SetUpTestSuite() {
shiqian's avatar
shiqian committed
6256
6257
6258
    // There should be no tests running at this point.
    const TestInfo* test_info =
      UnitTest::GetInstance()->current_test_info();
6259
    EXPECT_TRUE(test_info == nullptr)
shiqian's avatar
shiqian committed
6260
6261
6262
6263
6264
        << "There should be no tests running at this point.";
  }

  // Tests that current_test_info() returns NULL after the last test in
  // the test case has run.
misterg's avatar
misterg committed
6265
  static void TearDownTestSuite() {
shiqian's avatar
shiqian committed
6266
6267
    const TestInfo* test_info =
      UnitTest::GetInstance()->current_test_info();
6268
    EXPECT_TRUE(test_info == nullptr)
shiqian's avatar
shiqian committed
6269
6270
6271
6272
6273
6274
        << "There should be no tests running at this point.";
  }
};

// Tests that current_test_info() returns TestInfo for currently running
// test by checking the expected test name against the actual one.
misterg's avatar
misterg committed
6275
TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
shiqian's avatar
shiqian committed
6276
6277
  const TestInfo* test_info =
    UnitTest::GetInstance()->current_test_info();
6278
  ASSERT_TRUE(nullptr != test_info)
shiqian's avatar
shiqian committed
6279
6280
6281
      << "There is a test running so we should have a valid TestInfo.";
  EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
      << "Expected the name of the currently running test case.";
misterg's avatar
misterg committed
6282
  EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
shiqian's avatar
shiqian committed
6283
6284
6285
6286
6287
6288
6289
      << "Expected the name of the currently running test.";
}

// Tests that current_test_info() returns TestInfo for currently running
// test by checking the expected test name against the actual one.  We
// use this test to see that the TestInfo object actually changed from
// the previous invocation.
misterg's avatar
misterg committed
6290
TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
shiqian's avatar
shiqian committed
6291
6292
  const TestInfo* test_info =
    UnitTest::GetInstance()->current_test_info();
6293
  ASSERT_TRUE(nullptr != test_info)
shiqian's avatar
shiqian committed
6294
6295
6296
      << "There is a test running so we should have a valid TestInfo.";
  EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
      << "Expected the name of the currently running test case.";
misterg's avatar
misterg committed
6297
  EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
shiqian's avatar
shiqian committed
6298
6299
6300
6301
6302
      << "Expected the name of the currently running test.";
}

}  // namespace testing

Gennadiy Civil's avatar
 
Gennadiy Civil committed
6303

shiqian's avatar
shiqian committed
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
// These two lines test that we can define tests in a namespace that
// has the name "testing" and is nested in another namespace.
namespace my_namespace {
namespace testing {

// Makes sure that TEST knows to use ::testing::Test instead of
// ::my_namespace::testing::Test.
class Test {};

// Makes sure that an assertion knows to use ::testing::Message instead of
// ::my_namespace::testing::Message.
class Message {};

// Makes sure that an assertion knows to use
// ::testing::AssertionResult instead of
// ::my_namespace::testing::AssertionResult.
class AssertionResult {};

// Tests that an assertion that should succeed works as expected.
TEST(NestedTestingNamespaceTest, Success) {
  EXPECT_EQ(1, 1) << "This shouldn't fail.";
}

// Tests that an assertion that should fail works as expected.
TEST(NestedTestingNamespaceTest, Failure) {
  EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
                       "This failure is expected.");
}

}  // namespace testing
}  // namespace my_namespace

// Tests that one can call superclass SetUp and TearDown methods--
// that is, that they are not private.
// No tests are based on this fixture; the test "passes" if it compiles
// successfully.
6340
class ProtectedFixtureMethodsTest : public Test {
shiqian's avatar
shiqian committed
6341
 protected:
Abseil Team's avatar
Abseil Team committed
6342
6343
  void SetUp() override { Test::SetUp(); }
  void TearDown() override { Test::TearDown(); }
shiqian's avatar
shiqian committed
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
};

// StreamingAssertionsTest tests the streaming versions of a representative
// sample of assertions.
TEST(StreamingAssertionsTest, Unconditional) {
  SUCCEED() << "expected success";
  EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
                          "expected failure");
  EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
                       "expected failure");
}

6356
6357
#ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code"
6358
# pragma option push -w-ccc -w-rch
6359
6360
#endif

shiqian's avatar
shiqian committed
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
TEST(StreamingAssertionsTest, Truth) {
  EXPECT_TRUE(true) << "unexpected failure";
  ASSERT_TRUE(true) << "unexpected failure";
  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
                          "expected failure");
  EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
                       "expected failure");
}

TEST(StreamingAssertionsTest, Truth2) {
  EXPECT_FALSE(false) << "unexpected failure";
  ASSERT_FALSE(false) << "unexpected failure";
  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
                          "expected failure");
  EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
                       "expected failure");
}

6379
#ifdef __BORLANDC__
Troy Holsapple's avatar
Troy Holsapple committed
6380
// Restores warnings after previous "#pragma option push" suppressed them
6381
# pragma option pop
6382
6383
#endif

shiqian's avatar
shiqian committed
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
TEST(StreamingAssertionsTest, IntegerEquals) {
  EXPECT_EQ(1, 1) << "unexpected failure";
  ASSERT_EQ(1, 1) << "unexpected failure";
  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
                          "expected failure");
  EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
                       "expected failure");
}

TEST(StreamingAssertionsTest, IntegerLessThan) {
  EXPECT_LT(1, 2) << "unexpected failure";
  ASSERT_LT(1, 2) << "unexpected failure";
  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
                          "expected failure");
  EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
                       "expected failure");
}

TEST(StreamingAssertionsTest, StringsEqual) {
  EXPECT_STREQ("foo", "foo") << "unexpected failure";
  ASSERT_STREQ("foo", "foo") << "unexpected failure";
  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
                          "expected failure");
  EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
                       "expected failure");
}

TEST(StreamingAssertionsTest, StringsNotEqual) {
  EXPECT_STRNE("foo", "bar") << "unexpected failure";
  ASSERT_STRNE("foo", "bar") << "unexpected failure";
  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
                          "expected failure");
  EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
                       "expected failure");
}

TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
  EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
  ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
                          "expected failure");
  EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
                       "expected failure");
}

TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
  EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
  ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
                          "expected failure");
  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
                       "expected failure");
}

TEST(StreamingAssertionsTest, FloatingPointEquals) {
  EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
  ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
                          "expected failure");
  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
                       "expected failure");
}

6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
#if GTEST_HAS_EXCEPTIONS

TEST(StreamingAssertionsTest, Throw) {
  EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
  ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
                          "expected failure", "expected failure");
  EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
                       "expected failure", "expected failure");
}

TEST(StreamingAssertionsTest, NoThrow) {
6459
6460
  EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
  ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6461
6462
6463
6464
6465
6466
6467
6468
6469
  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
                          "expected failure", "expected failure");
  EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
                       "expected failure", "expected failure");
}

TEST(StreamingAssertionsTest, AnyThrow) {
  EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
  ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6470
  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
6471
                          "expected failure", "expected failure");
6472
  EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
6473
6474
6475
6476
6477
                       "expected failure", "expected failure");
}

#endif  // GTEST_HAS_EXCEPTIONS

shiqian's avatar
shiqian committed
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
// Tests that Google Test correctly decides whether to use colors in the output.

TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
  GTEST_FLAG(color) = "yes";

  SetEnv("TERM", "xterm");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.

  SetEnv("TERM", "dumb");  // TERM doesn't support colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
}

TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
  SetEnv("TERM", "dumb");  // TERM doesn't support colors.

  GTEST_FLAG(color) = "True";
  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.

  GTEST_FLAG(color) = "t";
  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.

  GTEST_FLAG(color) = "1";
  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
}

TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
  GTEST_FLAG(color) = "no";

  SetEnv("TERM", "xterm");  // TERM supports colors.
  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
  EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.

  SetEnv("TERM", "dumb");  // TERM doesn't support colors.
  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
  EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
}

TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
  SetEnv("TERM", "xterm");  // TERM supports colors.

  GTEST_FLAG(color) = "F";
  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.

  GTEST_FLAG(color) = "0";
  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.

  GTEST_FLAG(color) = "unknown";
  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
}

TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
  GTEST_FLAG(color) = "auto";

  SetEnv("TERM", "xterm");  // TERM supports colors.
  EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
  EXPECT_TRUE(ShouldUseColor(true));    // Stdout is a TTY.
}

TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
  GTEST_FLAG(color) = "auto";

6541
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
shiqian's avatar
shiqian committed
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
  // On Windows, we ignore the TERM variable as it's usually not set.

  SetEnv("TERM", "dumb");
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.

  SetEnv("TERM", "");
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.

  SetEnv("TERM", "xterm");
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
#else
  // On non-Windows platforms, we rely on TERM to determine if the
  // terminal supports colors.

  SetEnv("TERM", "dumb");  // TERM doesn't support colors.
  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.

  SetEnv("TERM", "emacs");  // TERM doesn't support colors.
  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.

  SetEnv("TERM", "vt100");  // TERM doesn't support colors.
  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.

  SetEnv("TERM", "xterm-mono");  // TERM doesn't support colors.
  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.

  SetEnv("TERM", "xterm");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.

  SetEnv("TERM", "xterm-color");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6573

6574
6575
6576
6577
6578
6579
  SetEnv("TERM", "xterm-256color");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.

  SetEnv("TERM", "screen");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.

6580
6581
6582
  SetEnv("TERM", "screen-256color");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.

6583
6584
6585
6586
6587
6588
  SetEnv("TERM", "tmux");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.

  SetEnv("TERM", "tmux-256color");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.

kosak's avatar
kosak committed
6589
6590
6591
6592
6593
6594
  SetEnv("TERM", "rxvt-unicode");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.

  SetEnv("TERM", "rxvt-unicode-256color");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.

6595
6596
  SetEnv("TERM", "linux");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6597
6598
6599

  SetEnv("TERM", "cygwin");  // TERM supports colors.
  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
shiqian's avatar
shiqian committed
6600
6601
6602
#endif  // GTEST_OS_WINDOWS
}

6603
6604
// Verifies that StaticAssertTypeEq works in a namespace scope.

6605
6606
6607
static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
    StaticAssertTypeEq<const int, const int>();
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629

// Verifies that StaticAssertTypeEq works in a class.

template <typename T>
class StaticAssertTypeEqTestHelper {
 public:
  StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
};

TEST(StaticAssertTypeEqTest, WorksInClass) {
  StaticAssertTypeEqTestHelper<bool>();
}

// Verifies that StaticAssertTypeEq works inside a function.

typedef int IntAlias;

TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
  StaticAssertTypeEq<int, IntAlias>();
  StaticAssertTypeEq<int*, IntAlias*>();
}

6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
  EXPECT_FALSE(HasNonfatalFailure());
}

static void FailFatally() { FAIL(); }

TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
  FailFatally();
  const bool has_nonfatal_failure = HasNonfatalFailure();
  ClearCurrentTestPartResults();
  EXPECT_FALSE(has_nonfatal_failure);
}

TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
  ADD_FAILURE();
  const bool has_nonfatal_failure = HasNonfatalFailure();
  ClearCurrentTestPartResults();
  EXPECT_TRUE(has_nonfatal_failure);
}

TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
  FailFatally();
  ADD_FAILURE();
  const bool has_nonfatal_failure = HasNonfatalFailure();
  ClearCurrentTestPartResults();
  EXPECT_TRUE(has_nonfatal_failure);
}

// A wrapper for calling HasNonfatalFailure outside of a test body.
static bool HasNonfatalFailureHelper() {
  return testing::Test::HasNonfatalFailure();
}

TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
  EXPECT_FALSE(HasNonfatalFailureHelper());
}

TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
  ADD_FAILURE();
  const bool has_nonfatal_failure = HasNonfatalFailureHelper();
  ClearCurrentTestPartResults();
  EXPECT_TRUE(has_nonfatal_failure);
}

TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
  EXPECT_FALSE(HasFailure());
}

TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
  FailFatally();
  const bool has_failure = HasFailure();
  ClearCurrentTestPartResults();
  EXPECT_TRUE(has_failure);
}

TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
  ADD_FAILURE();
  const bool has_failure = HasFailure();
  ClearCurrentTestPartResults();
  EXPECT_TRUE(has_failure);
}

TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
  FailFatally();
  ADD_FAILURE();
  const bool has_failure = HasFailure();
  ClearCurrentTestPartResults();
  EXPECT_TRUE(has_failure);
}

// A wrapper for calling HasFailure outside of a test body.
static bool HasFailureHelper() { return testing::Test::HasFailure(); }

TEST(HasFailureTest, WorksOutsideOfTestBody) {
  EXPECT_FALSE(HasFailureHelper());
}

TEST(HasFailureTest, WorksOutsideOfTestBody2) {
  ADD_FAILURE();
  const bool has_failure = HasFailureHelper();
  ClearCurrentTestPartResults();
  EXPECT_TRUE(has_failure);
}
6713
6714
6715

class TestListener : public EmptyTestEventListener {
 public:
6716
  TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
6717
6718
6719
6720
  TestListener(int* on_start_counter, bool* is_destroyed)
      : on_start_counter_(on_start_counter),
        is_destroyed_(is_destroyed) {}

Abseil Team's avatar
Abseil Team committed
6721
  ~TestListener() override {
6722
6723
6724
6725
6726
    if (is_destroyed_)
      *is_destroyed_ = true;
  }

 protected:
Abseil Team's avatar
Abseil Team committed
6727
  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6728
    if (on_start_counter_ != nullptr) (*on_start_counter_)++;
6729
6730
6731
6732
6733
6734
6735
6736
  }

 private:
  int* on_start_counter_;
  bool* is_destroyed_;
};

// Tests the constructor.
6737
6738
TEST(TestEventListenersTest, ConstructionWorks) {
  TestEventListeners listeners;
6739

6740
6741
6742
  EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr);
  EXPECT_TRUE(listeners.default_result_printer() == nullptr);
  EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
6743
6744
}

6745
// Tests that the TestEventListeners destructor deletes all the listeners it
6746
// owns.
6747
TEST(TestEventListenersTest, DestructionWorks) {
6748
6749
6750
  bool default_result_printer_is_destroyed = false;
  bool default_xml_printer_is_destroyed = false;
  bool extra_listener_is_destroyed = false;
6751
6752
6753
6754
6755
6756
  TestListener* default_result_printer =
      new TestListener(nullptr, &default_result_printer_is_destroyed);
  TestListener* default_xml_printer =
      new TestListener(nullptr, &default_xml_printer_is_destroyed);
  TestListener* extra_listener =
      new TestListener(nullptr, &extra_listener_is_destroyed);
6757
6758

  {
6759
6760
6761
6762
6763
    TestEventListeners listeners;
    TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
                                                        default_result_printer);
    TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
                                                       default_xml_printer);
6764
6765
6766
6767
6768
6769
6770
    listeners.Append(extra_listener);
  }
  EXPECT_TRUE(default_result_printer_is_destroyed);
  EXPECT_TRUE(default_xml_printer_is_destroyed);
  EXPECT_TRUE(extra_listener_is_destroyed);
}

6771
// Tests that a listener Append'ed to a TestEventListeners list starts
6772
// receiving events.
6773
TEST(TestEventListenersTest, Append) {
6774
6775
6776
6777
  int on_start_counter = 0;
  bool is_destroyed = false;
  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  {
6778
    TestEventListeners listeners;
6779
    listeners.Append(listener);
6780
    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6781
6782
6783
6784
6785
6786
        *UnitTest::GetInstance());
    EXPECT_EQ(1, on_start_counter);
  }
  EXPECT_TRUE(is_destroyed);
}

6787
6788
6789
// Tests that listeners receive events in the order they were appended to
// the list, except for *End requests, which must be received in the reverse
// order.
6790
6791
class SequenceTestingListener : public EmptyTestEventListener {
 public:
6792
  SequenceTestingListener(std::vector<std::string>* vector, const char* id)
6793
      : vector_(vector), id_(id) {}
6794
6795

 protected:
Abseil Team's avatar
Abseil Team committed
6796
  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6797
    vector_->push_back(GetEventDescription("OnTestProgramStart"));
6798
6799
  }

Abseil Team's avatar
Abseil Team committed
6800
  void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {
6801
    vector_->push_back(GetEventDescription("OnTestProgramEnd"));
6802
6803
  }

Abseil Team's avatar
Abseil Team committed
6804
6805
  void OnTestIterationStart(const UnitTest& /*unit_test*/,
                            int /*iteration*/) override {
6806
    vector_->push_back(GetEventDescription("OnTestIterationStart"));
6807
6808
  }

Abseil Team's avatar
Abseil Team committed
6809
6810
  void OnTestIterationEnd(const UnitTest& /*unit_test*/,
                          int /*iteration*/) override {
6811
    vector_->push_back(GetEventDescription("OnTestIterationEnd"));
6812
6813
6814
  }

 private:
6815
  std::string GetEventDescription(const char* method) {
6816
6817
6818
6819
6820
    Message message;
    message << id_ << "." << method;
    return message.GetString();
  }

6821
  std::vector<std::string>* vector_;
6822
  const char* const id_;
6823
6824

  GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
6825
6826
6827
};

TEST(EventListenerTest, AppendKeepsOrder) {
6828
  std::vector<std::string> vec;
6829
  TestEventListeners listeners;
6830
6831
6832
6833
  listeners.Append(new SequenceTestingListener(&vec, "1st"));
  listeners.Append(new SequenceTestingListener(&vec, "2nd"));
  listeners.Append(new SequenceTestingListener(&vec, "3rd"));

6834
  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6835
      *UnitTest::GetInstance());
6836
6837
6838
6839
  ASSERT_EQ(3U, vec.size());
  EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
  EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
  EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
6840

6841
  vec.clear();
6842
  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
6843
      *UnitTest::GetInstance());
6844
6845
6846
6847
  ASSERT_EQ(3U, vec.size());
  EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
  EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
  EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
6848

6849
  vec.clear();
6850
  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
6851
      *UnitTest::GetInstance(), 0);
6852
6853
6854
6855
  ASSERT_EQ(3U, vec.size());
  EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
  EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
  EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
6856

6857
  vec.clear();
6858
  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
6859
      *UnitTest::GetInstance(), 0);
6860
6861
6862
6863
  ASSERT_EQ(3U, vec.size());
  EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
  EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
  EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
6864
6865
}

6866
// Tests that a listener removed from a TestEventListeners list stops receiving
6867
// events and is not deleted when the list is destroyed.
6868
TEST(TestEventListenersTest, Release) {
6869
6870
6871
6872
6873
6874
6875
  int on_start_counter = 0;
  bool is_destroyed = false;
  // Although Append passes the ownership of this object to the list,
  // the following calls release it, and we need to delete it before the
  // test ends.
  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  {
6876
    TestEventListeners listeners;
6877
6878
    listeners.Append(listener);
    EXPECT_EQ(listener, listeners.Release(listener));
6879
    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6880
        *UnitTest::GetInstance());
6881
    EXPECT_TRUE(listeners.Release(listener) == nullptr);
6882
6883
6884
6885
6886
6887
6888
6889
6890
  }
  EXPECT_EQ(0, on_start_counter);
  EXPECT_FALSE(is_destroyed);
  delete listener;
}

// Tests that no events are forwarded when event forwarding is disabled.
TEST(EventListenerTest, SuppressEventForwarding) {
  int on_start_counter = 0;
6891
  TestListener* listener = new TestListener(&on_start_counter, nullptr);
6892

6893
  TestEventListeners listeners;
6894
  listeners.Append(listener);
6895
6896
6897
6898
  ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
  TestEventListenersAccessor::SuppressEventForwarding(&listeners);
  ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6899
6900
6901
6902
6903
6904
6905
      *UnitTest::GetInstance());
  EXPECT_EQ(0, on_start_counter);
}

// Tests that events generated by Google Test are not forwarded in
// death test subprocesses.
TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
6906
  EXPECT_DEATH_IF_SUPPORTED({
6907
      GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
          *GetUnitTestImpl()->listeners())) << "expected failure";},
      "expected failure");
}

// Tests that a listener installed via SetDefaultResultPrinter() starts
// receiving events and is returned via default_result_printer() and that
// the previous default_result_printer is removed from the list and deleted.
TEST(EventListenerTest, default_result_printer) {
  int on_start_counter = 0;
  bool is_destroyed = false;
  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);

6920
6921
  TestEventListeners listeners;
  TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
6922
6923
6924

  EXPECT_EQ(listener, listeners.default_result_printer());

6925
  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6926
6927
6928
6929
6930
6931
      *UnitTest::GetInstance());

  EXPECT_EQ(1, on_start_counter);

  // Replacing default_result_printer with something else should remove it
  // from the list and destroy it.
6932
  TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr);
6933

6934
  EXPECT_TRUE(listeners.default_result_printer() == nullptr);
6935
6936
6937
6938
  EXPECT_TRUE(is_destroyed);

  // After broadcasting an event the counter is still the same, indicating
  // the listener is not in the list anymore.
6939
  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
      *UnitTest::GetInstance());
  EXPECT_EQ(1, on_start_counter);
}

// Tests that the default_result_printer listener stops receiving events
// when removed via Release and that is not owned by the list anymore.
TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
  int on_start_counter = 0;
  bool is_destroyed = false;
  // Although Append passes the ownership of this object to the list,
  // the following calls release it, and we need to delete it before the
  // test ends.
  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  {
6954
6955
    TestEventListeners listeners;
    TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
6956
6957

    EXPECT_EQ(listener, listeners.Release(listener));
6958
    EXPECT_TRUE(listeners.default_result_printer() == nullptr);
6959
6960
6961
    EXPECT_FALSE(is_destroyed);

    // Broadcasting events now should not affect default_result_printer.
6962
    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
        *UnitTest::GetInstance());
    EXPECT_EQ(0, on_start_counter);
  }
  // Destroying the list should not affect the listener now, too.
  EXPECT_FALSE(is_destroyed);
  delete listener;
}

// Tests that a listener installed via SetDefaultXmlGenerator() starts
// receiving events and is returned via default_xml_generator() and that
// the previous default_xml_generator is removed from the list and deleted.
TEST(EventListenerTest, default_xml_generator) {
  int on_start_counter = 0;
  bool is_destroyed = false;
  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);

6979
6980
  TestEventListeners listeners;
  TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
6981
6982
6983

  EXPECT_EQ(listener, listeners.default_xml_generator());

6984
  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6985
6986
6987
6988
6989
6990
      *UnitTest::GetInstance());

  EXPECT_EQ(1, on_start_counter);

  // Replacing default_xml_generator with something else should remove it
  // from the list and destroy it.
6991
  TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr);
6992

6993
  EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
6994
6995
6996
6997
  EXPECT_TRUE(is_destroyed);

  // After broadcasting an event the counter is still the same, indicating
  // the listener is not in the list anymore.
6998
  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
      *UnitTest::GetInstance());
  EXPECT_EQ(1, on_start_counter);
}

// Tests that the default_xml_generator listener stops receiving events
// when removed via Release and that is not owned by the list anymore.
TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
  int on_start_counter = 0;
  bool is_destroyed = false;
  // Although Append passes the ownership of this object to the list,
  // the following calls release it, and we need to delete it before the
  // test ends.
  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  {
7013
7014
    TestEventListeners listeners;
    TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7015
7016

    EXPECT_EQ(listener, listeners.Release(listener));
7017
    EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7018
7019
7020
    EXPECT_FALSE(is_destroyed);

    // Broadcasting events now should not affect default_xml_generator.
7021
    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7022
7023
7024
7025
7026
7027
7028
        *UnitTest::GetInstance());
    EXPECT_EQ(0, on_start_counter);
  }
  // Destroying the list should not affect the listener now, too.
  EXPECT_FALSE(is_destroyed);
  delete listener;
}
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040

// Sanity tests to ensure that the alternative, verbose spellings of
// some of the macros work.  We don't test them thoroughly as that
// would be quite involved.  Since their implementations are
// straightforward, and they are rarely used, we'll just rely on the
// users to tell us when they are broken.
GTEST_TEST(AlternativeNameTest, Works) {  // GTEST_TEST is the same as TEST.
  GTEST_SUCCEED() << "OK";  // GTEST_SUCCEED is the same as SUCCEED.

  // GTEST_FAIL is the same as FAIL.
  EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
                       "An expected failure");
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075

  // GTEST_ASSERT_XY is the same as ASSERT_XY.

  GTEST_ASSERT_EQ(0, 0);
  EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
                       "An expected failure");
  EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
                       "An expected failure");

  GTEST_ASSERT_NE(0, 1);
  GTEST_ASSERT_NE(1, 0);
  EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
                       "An expected failure");

  GTEST_ASSERT_LE(0, 0);
  GTEST_ASSERT_LE(0, 1);
  EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
                       "An expected failure");

  GTEST_ASSERT_LT(0, 1);
  EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
                       "An expected failure");
  EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
                       "An expected failure");

  GTEST_ASSERT_GE(0, 0);
  GTEST_ASSERT_GE(1, 0);
  EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
                       "An expected failure");

  GTEST_ASSERT_GT(1, 0);
  EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
                       "An expected failure");
  EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
                       "An expected failure");
7076
}
7077
7078
7079
7080
7081
7082
7083
7084
7085

// Tests for internal utilities necessary for implementation of the universal
// printing.

class ConversionHelperBase {};
class ConversionHelperDerived : public ConversionHelperBase {};

// Tests that IsAProtocolMessage<T>::value is a compile-time constant.
TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
Abseil Team's avatar
Abseil Team committed
7086
  GTEST_COMPILE_ASSERT_(IsAProtocolMessage<::proto2::Message>::value,
7087
7088
7089
7090
7091
                        const_true);
  GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
}

// Tests that IsAProtocolMessage<T>::value is true when T is
7092
// proto2::Message or a sub-class of it.
7093
7094
7095
7096
7097
TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
  EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
}

// Tests that IsAProtocolMessage<T>::value is false when T is neither
Abseil Team's avatar
Abseil Team committed
7098
// ::proto2::Message nor a sub-class of it.
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
  EXPECT_FALSE(IsAProtocolMessage<int>::value);
  EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
}

// Tests that CompileAssertTypesEqual compiles when the type arguments are
// equal.
TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) {
  CompileAssertTypesEqual<void, void>();
  CompileAssertTypesEqual<int*, int*>();
}

// Tests that RemoveReference does not affect non-reference types.
TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) {
  CompileAssertTypesEqual<int, RemoveReference<int>::type>();
  CompileAssertTypesEqual<const char, RemoveReference<const char>::type>();
}

// Tests that RemoveReference removes reference from reference types.
TEST(RemoveReferenceTest, RemovesReference) {
  CompileAssertTypesEqual<int, RemoveReference<int&>::type>();
  CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>();
}

// Tests GTEST_REMOVE_REFERENCE_.

template <typename T1, typename T2>
void TestGTestRemoveReference() {
  CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>();
}

TEST(RemoveReferenceTest, MacroVersion) {
  TestGTestRemoveReference<int, int>();
  TestGTestRemoveReference<const char, const char&>();
}


// Tests that RemoveConst does not affect non-const types.
TEST(RemoveConstTest, DoesNotAffectNonConstType) {
  CompileAssertTypesEqual<int, RemoveConst<int>::type>();
  CompileAssertTypesEqual<char&, RemoveConst<char&>::type>();
}

// Tests that RemoveConst removes const from const types.
TEST(RemoveConstTest, RemovesConst) {
  CompileAssertTypesEqual<int, RemoveConst<const int>::type>();
  CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>();
  CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>();
}

// Tests GTEST_REMOVE_CONST_.

template <typename T1, typename T2>
void TestGTestRemoveConst() {
  CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>();
}

TEST(RemoveConstTest, MacroVersion) {
  TestGTestRemoveConst<int, int>();
  TestGTestRemoveConst<double&, double&>();
  TestGTestRemoveConst<char, const char>();
}

7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.

template <typename T1, typename T2>
void TestGTestRemoveReferenceAndConst() {
  CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>();
}

TEST(RemoveReferenceToConstTest, Works) {
  TestGTestRemoveReferenceAndConst<int, int>();
  TestGTestRemoveReferenceAndConst<double, double&>();
  TestGTestRemoveReferenceAndConst<char, const char>();
  TestGTestRemoveReferenceAndConst<char, const char&>();
  TestGTestRemoveReferenceAndConst<const char*, const char*>();
}

7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
// Tests that AddReference does not affect reference types.
TEST(AddReferenceTest, DoesNotAffectReferenceType) {
  CompileAssertTypesEqual<int&, AddReference<int&>::type>();
  CompileAssertTypesEqual<const char&, AddReference<const char&>::type>();
}

// Tests that AddReference adds reference to non-reference types.
TEST(AddReferenceTest, AddsReference) {
  CompileAssertTypesEqual<int&, AddReference<int>::type>();
  CompileAssertTypesEqual<const char&, AddReference<const char>::type>();
}

// Tests GTEST_ADD_REFERENCE_.

template <typename T1, typename T2>
void TestGTestAddReference() {
  CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>();
}

TEST(AddReferenceTest, MacroVersion) {
  TestGTestAddReference<int&, int>();
  TestGTestAddReference<const char&, const char&>();
}

// Tests GTEST_REFERENCE_TO_CONST_.

template <typename T1, typename T2>
void TestGTestReferenceToConst() {
  CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>();
}

TEST(GTestReferenceToConstTest, Works) {
  TestGTestReferenceToConst<const char&, char>();
  TestGTestReferenceToConst<const int&, const int>();
  TestGTestReferenceToConst<const double&, double>();
7212
  TestGTestReferenceToConst<const std::string&, const std::string&>();
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
}


// Tests IsContainerTest.

class NonContainer {};

TEST(IsContainerTestTest, WorksForNonContainer) {
  EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
  EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
  EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
}

TEST(IsContainerTestTest, WorksForContainer) {
  EXPECT_EQ(sizeof(IsContainer),
            sizeof(IsContainerTest<std::vector<bool> >(0)));
  EXPECT_EQ(sizeof(IsContainer),
            sizeof(IsContainerTest<std::map<int, double> >(0)));
}

7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
struct ConstOnlyContainerWithPointerIterator {
  using const_iterator = int*;
  const_iterator begin() const;
  const_iterator end() const;
};

struct ConstOnlyContainerWithClassIterator {
  struct const_iterator {
    const int& operator*() const;
    const_iterator& operator++(/* pre-increment */);
  };
  const_iterator begin() const;
  const_iterator end() const;
};

TEST(IsContainerTestTest, ConstOnlyContainer) {
  EXPECT_EQ(sizeof(IsContainer),
            sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
  EXPECT_EQ(sizeof(IsContainer),
            sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
}

// Tests IsHashTable.
struct AHashTable {
  typedef void hasher;
};
struct NotReallyAHashTable {
  typedef void hasher;
  typedef void reverse_iterator;
};
TEST(IsHashTable, Basic) {
  EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value);
  EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value);
  EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value);
  EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value);
}

7270
7271
7272
7273
7274
7275
7276
7277
// Tests ArrayEq().

TEST(ArrayEqTest, WorksForDegeneratedArrays) {
  EXPECT_TRUE(ArrayEq(5, 5L));
  EXPECT_FALSE(ArrayEq('a', 0));
}

TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7278
  // Note that a and b are distinct but compatible types.
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
  const int a[] = { 0, 1 };
  long b[] = { 0, 1 };
  EXPECT_TRUE(ArrayEq(a, b));
  EXPECT_TRUE(ArrayEq(a, 2, b));

  b[0] = 2;
  EXPECT_FALSE(ArrayEq(a, b));
  EXPECT_FALSE(ArrayEq(a, 1, b));
}

TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
  const char a[][3] = { "hi", "lo" };
  const char b[][3] = { "hi", "lo" };
  const char c[][3] = { "hi", "li" };

  EXPECT_TRUE(ArrayEq(a, b));
  EXPECT_TRUE(ArrayEq(a, 2, b));

  EXPECT_FALSE(ArrayEq(a, c));
  EXPECT_FALSE(ArrayEq(a, 2, c));
}

// Tests ArrayAwareFind().

TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
  const char a[] = "hello";
  EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
  EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
}

TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
  int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
  const int b[2] = { 2, 3 };
  EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));

  const int c[2] = { 6, 7 };
  EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
}

// Tests CopyArray().

TEST(CopyArrayTest, WorksForDegeneratedArrays) {
  int n = 0;
  CopyArray('a', &n);
  EXPECT_EQ('a', n);
}

TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
  const char a[3] = "hi";
  int b[3];
7329
#ifndef __BORLANDC__  // C++Builder cannot compile some array size deductions.
7330
7331
  CopyArray(a, &b);
  EXPECT_TRUE(ArrayEq(a, b));
7332
#endif
7333
7334
7335
7336
7337
7338
7339
7340
7341

  int c[3];
  CopyArray(a, 3, c);
  EXPECT_TRUE(ArrayEq(a, c));
}

TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
  const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
  int b[2][3];
7342
#ifndef __BORLANDC__  // C++Builder cannot compile some array size deductions.
7343
7344
  CopyArray(a, &b);
  EXPECT_TRUE(ArrayEq(a, b));
7345
#endif
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355

  int c[2][3];
  CopyArray(a, 2, c);
  EXPECT_TRUE(ArrayEq(a, c));
}

// Tests NativeArray.

TEST(NativeArrayTest, ConstructorFromArrayWorks) {
  const int a[3] = { 0, 1, 2 };
billydonahue's avatar
billydonahue committed
7356
  NativeArray<int> na(a, 3, RelationToSourceReference());
7357
7358
7359
7360
7361
7362
7363
7364
7365
  EXPECT_EQ(3U, na.size());
  EXPECT_EQ(a, na.begin());
}

TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
  typedef int Array[2];
  Array* a = new Array[1];
  (*a)[0] = 0;
  (*a)[1] = 1;
billydonahue's avatar
billydonahue committed
7366
  NativeArray<int> na(*a, 2, RelationToSourceCopy());
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
  EXPECT_NE(*a, na.begin());
  delete[] a;
  EXPECT_EQ(0, na.begin()[0]);
  EXPECT_EQ(1, na.begin()[1]);

  // We rely on the heap checker to verify that na deletes the copy of
  // array.
}

TEST(NativeArrayTest, TypeMembersAreCorrect) {
  StaticAssertTypeEq<char, NativeArray<char>::value_type>();
  StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();

  StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
  StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
}

TEST(NativeArrayTest, MethodsWork) {
  const int a[3] = { 0, 1, 2 };
billydonahue's avatar
billydonahue committed
7386
  NativeArray<int> na(a, 3, RelationToSourceCopy());
7387
7388
7389
7390
7391
7392
7393
  ASSERT_EQ(3U, na.size());
  EXPECT_EQ(3, na.end() - na.begin());

  NativeArray<int>::const_iterator it = na.begin();
  EXPECT_EQ(0, *it);
  ++it;
  EXPECT_EQ(1, *it);
Gennadiy Civil's avatar
 
Gennadiy Civil committed
7394
  it++;
7395
7396
7397
7398
7399
7400
  EXPECT_EQ(2, *it);
  ++it;
  EXPECT_EQ(na.end(), it);

  EXPECT_TRUE(na == na);

billydonahue's avatar
billydonahue committed
7401
  NativeArray<int> na2(a, 3, RelationToSourceReference());
7402
7403
7404
7405
  EXPECT_TRUE(na == na2);

  const int b1[3] = { 0, 1, 1 };
  const int b2[4] = { 0, 1, 2, 3 };
billydonahue's avatar
billydonahue committed
7406
7407
  EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
  EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
7408
7409
7410
7411
}

TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
  const char a[2][3] = { "hi", "lo" };
billydonahue's avatar
billydonahue committed
7412
  NativeArray<char[3]> na(a, 2, RelationToSourceReference());
7413
7414
7415
  ASSERT_EQ(2U, na.size());
  EXPECT_EQ(a, na.begin());
}
zhanyong.wan's avatar
zhanyong.wan committed
7416

Abseil Team's avatar
Abseil Team committed
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
// IndexSequence
TEST(IndexSequence, MakeIndexSequence) {
  using testing::internal::IndexSequence;
  using testing::internal::MakeIndexSequence;
  EXPECT_TRUE(
      (std::is_same<IndexSequence<>, MakeIndexSequence<0>::type>::value));
  EXPECT_TRUE(
      (std::is_same<IndexSequence<0>, MakeIndexSequence<1>::type>::value));
  EXPECT_TRUE(
      (std::is_same<IndexSequence<0, 1>, MakeIndexSequence<2>::type>::value));
  EXPECT_TRUE((
      std::is_same<IndexSequence<0, 1, 2>, MakeIndexSequence<3>::type>::value));
  EXPECT_TRUE(
      (std::is_base_of<IndexSequence<0, 1, 2>, MakeIndexSequence<3>>::value));
}

// ElemFromList
TEST(ElemFromList, Basic) {
  using testing::internal::ElemFromList;
  using Idx = testing::internal::MakeIndexSequence<3>::type;
  EXPECT_TRUE((
      std::is_same<int, ElemFromList<0, Idx, int, double, char>::type>::value));
  EXPECT_TRUE(
      (std::is_same<double,
                    ElemFromList<1, Idx, int, double, char>::type>::value));
  EXPECT_TRUE(
      (std::is_same<char,
                    ElemFromList<2, Idx, int, double, char>::type>::value));
  EXPECT_TRUE(
      (std::is_same<
          char, ElemFromList<7, testing::internal::MakeIndexSequence<12>::type,
                             int, int, int, int, int, int, int, char, int, int,
                             int, int>::type>::value));
}

// FlatTuple
TEST(FlatTuple, Basic) {
  using testing::internal::FlatTuple;

  FlatTuple<int, double, const char*> tuple = {};
  EXPECT_EQ(0, tuple.Get<0>());
  EXPECT_EQ(0.0, tuple.Get<1>());
  EXPECT_EQ(nullptr, tuple.Get<2>());

  tuple = FlatTuple<int, double, const char*>(7, 3.2, "Foo");
  EXPECT_EQ(7, tuple.Get<0>());
  EXPECT_EQ(3.2, tuple.Get<1>());
  EXPECT_EQ(std::string("Foo"), tuple.Get<2>());

  tuple.Get<1>() = 5.1;
  EXPECT_EQ(5.1, tuple.Get<1>());
}

TEST(FlatTuple, ManyTypes) {
  using testing::internal::FlatTuple;

  // Instantiate FlatTuple with 257 ints.
  // Tests show that we can do it with thousands of elements, but very long
  // compile times makes it unusuitable for this test.
#define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int,
#define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8
#define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16
#define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32
#define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64
#define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128

  // Let's make sure that we can have a very long list of types without blowing
  // up the template instantiation depth.
  FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple;

  tuple.Get<0>() = 7;
  tuple.Get<99>() = 17;
  tuple.Get<256>() = 1000;
  EXPECT_EQ(7, tuple.Get<0>());
  EXPECT_EQ(17, tuple.Get<99>());
  EXPECT_EQ(1000, tuple.Get<256>());
}

zhanyong.wan's avatar
zhanyong.wan committed
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
// Tests SkipPrefix().

TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
  const char* const str = "hello";

  const char* p = str;
  EXPECT_TRUE(SkipPrefix("", &p));
  EXPECT_EQ(str, p);

  p = str;
  EXPECT_TRUE(SkipPrefix("hell", &p));
  EXPECT_EQ(str + 4, p);
}

TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
  const char* const str = "world";

  const char* p = str;
  EXPECT_FALSE(SkipPrefix("W", &p));
  EXPECT_EQ(str, p);

  p = str;
  EXPECT_FALSE(SkipPrefix("world!", &p));
  EXPECT_EQ(str, p);
}
7520
7521
7522
7523
7524

// Tests ad_hoc_test_result().

class AdHocTestResultTest : public testing::Test {
 protected:
misterg's avatar
misterg committed
7525
7526
  static void SetUpTestSuite() {
    FAIL() << "A failure happened inside SetUpTestSuite().";
7527
7528
7529
  }
};

misterg's avatar
misterg committed
7530
TEST_F(AdHocTestResultTest, AdHocTestResultForTestSuiteShowsFailure) {
7531
  const testing::TestResult& test_result = testing::UnitTest::GetInstance()
misterg's avatar
misterg committed
7532
                                               ->current_test_suite()
7533
7534
7535
7536
7537
7538
7539
7540
7541
                                               ->ad_hoc_test_result();
  EXPECT_TRUE(test_result.Failed());
}

TEST_F(AdHocTestResultTest, AdHocTestResultTestForUnitTestDoesNotShowFailure) {
  const testing::TestResult& test_result =
      testing::UnitTest::GetInstance()->ad_hoc_test_result();
  EXPECT_FALSE(test_result.Failed());
}
Abseil Team's avatar
Abseil Team committed
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554

class DynamicUnitTestFixture : public testing::Test {};

class DynamicTest : public DynamicUnitTestFixture {
  void TestBody() override { EXPECT_TRUE(true); }
};

auto* dynamic_test = testing::RegisterTest(
    "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__,
    __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });

TEST(RegisterTest, WasRegistered) {
  auto* unittest = testing::UnitTest::GetInstance();
misterg's avatar
misterg committed
7555
7556
  for (int i = 0; i < unittest->total_test_suite_count(); ++i) {
    auto* tests = unittest->GetTestSuite(i);
Abseil Team's avatar
Abseil Team committed
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
    if (tests->name() != std::string("DynamicUnitTestFixture")) continue;
    for (int j = 0; j < tests->total_test_count(); ++j) {
      if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue;
      // Found it.
      EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE");
      EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE");
      return;
    }
  }

  FAIL() << "Didn't find the test!";
}