Update bundled GoogleTest to current HEAD
[alexxy/gromacs.git] / src / external / googletest / googletest / test / gtest_unittest.cc
1 // Copyright 2005, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 //
31 // Tests for Google Test itself.  This verifies that the basic constructs of
32 // Google Test work.
33
34 #include "gtest/gtest.h"
35
36 // Verifies that the command line flag variables can be accessed in
37 // code once "gtest.h" has been #included.
38 // Do not move it after other gtest #includes.
39 TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
40   bool dummy =
41       GTEST_FLAG_GET(also_run_disabled_tests) ||
42       GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) ||
43       GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) ||
44       GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) ||
45       GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) ||
46       GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) ||
47       GTEST_FLAG_GET(repeat) > 0 ||
48       GTEST_FLAG_GET(recreate_environments_when_repeating) ||
49       GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) ||
50       GTEST_FLAG_GET(stack_trace_depth) > 0 ||
51       GTEST_FLAG_GET(stream_result_to) != "unknown" ||
52       GTEST_FLAG_GET(throw_on_failure);
53   EXPECT_TRUE(dummy || !dummy);  // Suppresses warning that dummy is unused.
54 }
55
56 #include <limits.h>  // For INT_MAX.
57 #include <stdlib.h>
58 #include <string.h>
59 #include <time.h>
60
61 #include <cstdint>
62 #include <map>
63 #include <ostream>
64 #include <string>
65 #include <type_traits>
66 #include <unordered_set>
67 #include <vector>
68
69 #include "gtest/gtest-spi.h"
70 #include "src/gtest-internal-inl.h"
71
72 namespace testing {
73 namespace internal {
74
75 #if GTEST_CAN_STREAM_RESULTS_
76
77 class StreamingListenerTest : public Test {
78  public:
79   class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
80    public:
81     // Sends a string to the socket.
82     void Send(const std::string& message) override { output_ += message; }
83
84     std::string output_;
85   };
86
87   StreamingListenerTest()
88       : fake_sock_writer_(new FakeSocketWriter),
89         streamer_(fake_sock_writer_),
90         test_info_obj_("FooTest", "Bar", nullptr, nullptr,
91                        CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {}
92
93  protected:
94   std::string* output() { return &(fake_sock_writer_->output_); }
95
96   FakeSocketWriter* const fake_sock_writer_;
97   StreamingListener streamer_;
98   UnitTest unit_test_;
99   TestInfo test_info_obj_;  // The name test_info_ was taken by testing::Test.
100 };
101
102 TEST_F(StreamingListenerTest, OnTestProgramEnd) {
103   *output() = "";
104   streamer_.OnTestProgramEnd(unit_test_);
105   EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
106 }
107
108 TEST_F(StreamingListenerTest, OnTestIterationEnd) {
109   *output() = "";
110   streamer_.OnTestIterationEnd(unit_test_, 42);
111   EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
112 }
113
114 TEST_F(StreamingListenerTest, OnTestCaseStart) {
115   *output() = "";
116   streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", nullptr, nullptr));
117   EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
118 }
119
120 TEST_F(StreamingListenerTest, OnTestCaseEnd) {
121   *output() = "";
122   streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", nullptr, nullptr));
123   EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
124 }
125
126 TEST_F(StreamingListenerTest, OnTestStart) {
127   *output() = "";
128   streamer_.OnTestStart(test_info_obj_);
129   EXPECT_EQ("event=TestStart&name=Bar\n", *output());
130 }
131
132 TEST_F(StreamingListenerTest, OnTestEnd) {
133   *output() = "";
134   streamer_.OnTestEnd(test_info_obj_);
135   EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
136 }
137
138 TEST_F(StreamingListenerTest, OnTestPartResult) {
139   *output() = "";
140   streamer_.OnTestPartResult(TestPartResult(
141       TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
142
143   // Meta characters in the failure message should be properly escaped.
144   EXPECT_EQ(
145       "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
146       *output());
147 }
148
149 #endif  // GTEST_CAN_STREAM_RESULTS_
150
151 // Provides access to otherwise private parts of the TestEventListeners class
152 // that are needed to test it.
153 class TestEventListenersAccessor {
154  public:
155   static TestEventListener* GetRepeater(TestEventListeners* listeners) {
156     return listeners->repeater();
157   }
158
159   static void SetDefaultResultPrinter(TestEventListeners* listeners,
160                                       TestEventListener* listener) {
161     listeners->SetDefaultResultPrinter(listener);
162   }
163   static void SetDefaultXmlGenerator(TestEventListeners* listeners,
164                                      TestEventListener* listener) {
165     listeners->SetDefaultXmlGenerator(listener);
166   }
167
168   static bool EventForwardingEnabled(const TestEventListeners& listeners) {
169     return listeners.EventForwardingEnabled();
170   }
171
172   static void SuppressEventForwarding(TestEventListeners* listeners) {
173     listeners->SuppressEventForwarding();
174   }
175 };
176
177 class UnitTestRecordPropertyTestHelper : public Test {
178  protected:
179   UnitTestRecordPropertyTestHelper() {}
180
181   // Forwards to UnitTest::RecordProperty() to bypass access controls.
182   void UnitTestRecordProperty(const char* key, const std::string& value) {
183     unit_test_.RecordProperty(key, value);
184   }
185
186   UnitTest unit_test_;
187 };
188
189 }  // namespace internal
190 }  // namespace testing
191
192 using testing::AssertionFailure;
193 using testing::AssertionResult;
194 using testing::AssertionSuccess;
195 using testing::DoubleLE;
196 using testing::EmptyTestEventListener;
197 using testing::Environment;
198 using testing::FloatLE;
199 using testing::IsNotSubstring;
200 using testing::IsSubstring;
201 using testing::kMaxStackTraceDepth;
202 using testing::Message;
203 using testing::ScopedFakeTestPartResultReporter;
204 using testing::StaticAssertTypeEq;
205 using testing::Test;
206 using testing::TestEventListeners;
207 using testing::TestInfo;
208 using testing::TestPartResult;
209 using testing::TestPartResultArray;
210 using testing::TestProperty;
211 using testing::TestResult;
212 using testing::TestSuite;
213 using testing::TimeInMillis;
214 using testing::UnitTest;
215 using testing::internal::AlwaysFalse;
216 using testing::internal::AlwaysTrue;
217 using testing::internal::AppendUserMessage;
218 using testing::internal::ArrayAwareFind;
219 using testing::internal::ArrayEq;
220 using testing::internal::CodePointToUtf8;
221 using testing::internal::CopyArray;
222 using testing::internal::CountIf;
223 using testing::internal::EqFailure;
224 using testing::internal::FloatingPoint;
225 using testing::internal::ForEach;
226 using testing::internal::FormatEpochTimeInMillisAsIso8601;
227 using testing::internal::FormatTimeInMillisAsSeconds;
228 using testing::internal::GetCurrentOsStackTraceExceptTop;
229 using testing::internal::GetElementOr;
230 using testing::internal::GetNextRandomSeed;
231 using testing::internal::GetRandomSeedFromFlag;
232 using testing::internal::GetTestTypeId;
233 using testing::internal::GetTimeInMillis;
234 using testing::internal::GetTypeId;
235 using testing::internal::GetUnitTestImpl;
236 using testing::internal::GTestFlagSaver;
237 using testing::internal::HasDebugStringAndShortDebugString;
238 using testing::internal::Int32FromEnvOrDie;
239 using testing::internal::IsContainer;
240 using testing::internal::IsContainerTest;
241 using testing::internal::IsNotContainer;
242 using testing::internal::kMaxRandomSeed;
243 using testing::internal::kTestTypeIdInGoogleTest;
244 using testing::internal::NativeArray;
245 using testing::internal::OsStackTraceGetter;
246 using testing::internal::OsStackTraceGetterInterface;
247 using testing::internal::ParseFlag;
248 using testing::internal::RelationToSourceCopy;
249 using testing::internal::RelationToSourceReference;
250 using testing::internal::ShouldRunTestOnShard;
251 using testing::internal::ShouldShard;
252 using testing::internal::ShouldUseColor;
253 using testing::internal::Shuffle;
254 using testing::internal::ShuffleRange;
255 using testing::internal::SkipPrefix;
256 using testing::internal::StreamableToString;
257 using testing::internal::String;
258 using testing::internal::TestEventListenersAccessor;
259 using testing::internal::TestResultAccessor;
260 using testing::internal::UnitTestImpl;
261 using testing::internal::WideStringToUtf8;
262 using testing::internal::edit_distance::CalculateOptimalEdits;
263 using testing::internal::edit_distance::CreateUnifiedDiff;
264 using testing::internal::edit_distance::EditType;
265
266 #if GTEST_HAS_STREAM_REDIRECTION
267 using testing::internal::CaptureStdout;
268 using testing::internal::GetCapturedStdout;
269 #endif
270
271 #if GTEST_IS_THREADSAFE
272 using testing::internal::ThreadWithParam;
273 #endif
274
275 class TestingVector : public std::vector<int> {
276 };
277
278 ::std::ostream& operator<<(::std::ostream& os,
279                            const TestingVector& vector) {
280   os << "{ ";
281   for (size_t i = 0; i < vector.size(); i++) {
282     os << vector[i] << " ";
283   }
284   os << "}";
285   return os;
286 }
287
288 // This line tests that we can define tests in an unnamed namespace.
289 namespace {
290
291 TEST(GetRandomSeedFromFlagTest, HandlesZero) {
292   const int seed = GetRandomSeedFromFlag(0);
293   EXPECT_LE(1, seed);
294   EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
295 }
296
297 TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
298   EXPECT_EQ(1, GetRandomSeedFromFlag(1));
299   EXPECT_EQ(2, GetRandomSeedFromFlag(2));
300   EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
301   EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
302             GetRandomSeedFromFlag(kMaxRandomSeed));
303 }
304
305 TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
306   const int seed1 = GetRandomSeedFromFlag(-1);
307   EXPECT_LE(1, seed1);
308   EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
309
310   const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
311   EXPECT_LE(1, seed2);
312   EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
313 }
314
315 TEST(GetNextRandomSeedTest, WorksForValidInput) {
316   EXPECT_EQ(2, GetNextRandomSeed(1));
317   EXPECT_EQ(3, GetNextRandomSeed(2));
318   EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
319             GetNextRandomSeed(kMaxRandomSeed - 1));
320   EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
321
322   // We deliberately don't test GetNextRandomSeed() with invalid
323   // inputs, as that requires death tests, which are expensive.  This
324   // is fine as GetNextRandomSeed() is internal and has a
325   // straightforward definition.
326 }
327
328 static void ClearCurrentTestPartResults() {
329   TestResultAccessor::ClearTestPartResults(
330       GetUnitTestImpl()->current_test_result());
331 }
332
333 // Tests GetTypeId.
334
335 TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
336   EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
337   EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
338 }
339
340 class SubClassOfTest : public Test {};
341 class AnotherSubClassOfTest : public Test {};
342
343 TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
344   EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
345   EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
346   EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
347   EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
348   EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
349   EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
350 }
351
352 // Verifies that GetTestTypeId() returns the same value, no matter it
353 // is called from inside Google Test or outside of it.
354 TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
355   EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
356 }
357
358 // Tests CanonicalizeForStdLibVersioning.
359
360 using ::testing::internal::CanonicalizeForStdLibVersioning;
361
362 TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) {
363   EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind"));
364   EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_"));
365   EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo"));
366   EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x"));
367   EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x"));
368   EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x"));
369 }
370
371 TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
372   EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind"));
373   EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_"));
374
375   EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind"));
376   EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_"));
377
378   EXPECT_EQ("std::bind",
379             CanonicalizeForStdLibVersioning("std::__google::bind"));
380   EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_"));
381 }
382
383 // Tests FormatTimeInMillisAsSeconds().
384
385 TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
386   EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
387 }
388
389 TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
390   EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
391   EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
392   EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
393   EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
394   EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
395 }
396
397 TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
398   EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
399   EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
400   EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
401   EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
402   EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
403 }
404
405 // Tests FormatEpochTimeInMillisAsIso8601().  The correctness of conversion
406 // for particular dates below was verified in Python using
407 // datetime.datetime.fromutctimestamp(<timetamp>/1000).
408
409 // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
410 // have to set up a particular timezone to obtain predictable results.
411 class FormatEpochTimeInMillisAsIso8601Test : public Test {
412  public:
413   // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
414   // 32 bits, even when 64-bit integer types are available.  We have to
415   // force the constants to have a 64-bit type here.
416   static const TimeInMillis kMillisPerSec = 1000;
417
418  private:
419   void SetUp() override {
420     saved_tz_ = nullptr;
421
422     GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
423     if (getenv("TZ"))
424       saved_tz_ = strdup(getenv("TZ"));
425     GTEST_DISABLE_MSC_DEPRECATED_POP_()
426
427     // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use.  We
428     // cannot use the local time zone because the function's output depends
429     // on the time zone.
430     SetTimeZone("UTC+00");
431   }
432
433   void TearDown() override {
434     SetTimeZone(saved_tz_);
435     free(const_cast<char*>(saved_tz_));
436     saved_tz_ = nullptr;
437   }
438
439   static void SetTimeZone(const char* time_zone) {
440     // tzset() distinguishes between the TZ variable being present and empty
441     // and not being present, so we have to consider the case of time_zone
442     // being NULL.
443 #if _MSC_VER || GTEST_OS_WINDOWS_MINGW
444     // ...Unless it's MSVC, whose standard library's _putenv doesn't
445     // distinguish between an empty and a missing variable.
446     const std::string env_var =
447         std::string("TZ=") + (time_zone ? time_zone : "");
448     _putenv(env_var.c_str());
449     GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
450     tzset();
451     GTEST_DISABLE_MSC_WARNINGS_POP_()
452 #else
453     if (time_zone) {
454       setenv(("TZ"), time_zone, 1);
455     } else {
456       unsetenv("TZ");
457     }
458     tzset();
459 #endif
460   }
461
462   const char* saved_tz_;
463 };
464
465 const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
466
467 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
468   EXPECT_EQ("2011-10-31T18:52:42.000",
469             FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
470 }
471
472 TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
473   EXPECT_EQ(
474       "2011-10-31T18:52:42.234",
475       FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
476 }
477
478 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
479   EXPECT_EQ("2011-09-03T05:07:02.000",
480             FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
481 }
482
483 TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
484   EXPECT_EQ("2011-09-28T17:08:22.000",
485             FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
486 }
487
488 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
489   EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
490 }
491
492 # ifdef __BORLANDC__
493 // Silences warnings: "Condition is always true", "Unreachable code"
494 #  pragma option push -w-ccc -w-rch
495 # endif
496
497 // Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal
498 // when the RHS is a pointer type.
499 TEST(NullLiteralTest, LHSAllowsNullLiterals) {
500   EXPECT_EQ(0, static_cast<void*>(nullptr));     // NOLINT
501   ASSERT_EQ(0, static_cast<void*>(nullptr));     // NOLINT
502   EXPECT_EQ(NULL, static_cast<void*>(nullptr));  // NOLINT
503   ASSERT_EQ(NULL, static_cast<void*>(nullptr));  // NOLINT
504   EXPECT_EQ(nullptr, static_cast<void*>(nullptr));
505   ASSERT_EQ(nullptr, static_cast<void*>(nullptr));
506
507   const int* const p = nullptr;
508   EXPECT_EQ(0, p);     // NOLINT
509   ASSERT_EQ(0, p);     // NOLINT
510   EXPECT_EQ(NULL, p);  // NOLINT
511   ASSERT_EQ(NULL, p);  // NOLINT
512   EXPECT_EQ(nullptr, p);
513   ASSERT_EQ(nullptr, p);
514 }
515
516 struct ConvertToAll {
517   template <typename T>
518   operator T() const {  // NOLINT
519     return T();
520   }
521 };
522
523 struct ConvertToPointer {
524   template <class T>
525   operator T*() const {  // NOLINT
526     return nullptr;
527   }
528 };
529
530 struct ConvertToAllButNoPointers {
531   template <typename T,
532             typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0>
533   operator T() const {  // NOLINT
534     return T();
535   }
536 };
537
538 struct MyType {};
539 inline bool operator==(MyType const&, MyType const&) { return true; }
540
541 TEST(NullLiteralTest, ImplicitConversion) {
542   EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr));
543 #if !defined(__GNUC__) || defined(__clang__)
544   // Disabled due to GCC bug gcc.gnu.org/PR89580
545   EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr));
546 #endif
547   EXPECT_EQ(ConvertToAll{}, MyType{});
548   EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{});
549 }
550
551 #ifdef __clang__
552 #pragma clang diagnostic push
553 #if __has_warning("-Wzero-as-null-pointer-constant")
554 #pragma clang diagnostic error "-Wzero-as-null-pointer-constant"
555 #endif
556 #endif
557
558 TEST(NullLiteralTest, NoConversionNoWarning) {
559   // Test that gtests detection and handling of null pointer constants
560   // doesn't trigger a warning when '0' isn't actually used as null.
561   EXPECT_EQ(0, 0);
562   ASSERT_EQ(0, 0);
563 }
564
565 #ifdef __clang__
566 #pragma clang diagnostic pop
567 #endif
568
569 # ifdef __BORLANDC__
570 // Restores warnings after previous "#pragma option push" suppressed them.
571 #  pragma option pop
572 # endif
573
574 //
575 // Tests CodePointToUtf8().
576
577 // Tests that the NUL character L'\0' is encoded correctly.
578 TEST(CodePointToUtf8Test, CanEncodeNul) {
579   EXPECT_EQ("", CodePointToUtf8(L'\0'));
580 }
581
582 // Tests that ASCII characters are encoded correctly.
583 TEST(CodePointToUtf8Test, CanEncodeAscii) {
584   EXPECT_EQ("a", CodePointToUtf8(L'a'));
585   EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
586   EXPECT_EQ("&", CodePointToUtf8(L'&'));
587   EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
588 }
589
590 // Tests that Unicode code-points that have 8 to 11 bits are encoded
591 // as 110xxxxx 10xxxxxx.
592 TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
593   // 000 1101 0011 => 110-00011 10-010011
594   EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
595
596   // 101 0111 0110 => 110-10101 10-110110
597   // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
598   // in wide strings and wide chars. In order to accommodate them, we have to
599   // introduce such character constants as integers.
600   EXPECT_EQ("\xD5\xB6",
601             CodePointToUtf8(static_cast<wchar_t>(0x576)));
602 }
603
604 // Tests that Unicode code-points that have 12 to 16 bits are encoded
605 // as 1110xxxx 10xxxxxx 10xxxxxx.
606 TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
607   // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
608   EXPECT_EQ("\xE0\xA3\x93",
609             CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
610
611   // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
612   EXPECT_EQ("\xEC\x9D\x8D",
613             CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
614 }
615
616 #if !GTEST_WIDE_STRING_USES_UTF16_
617 // Tests in this group require a wchar_t to hold > 16 bits, and thus
618 // are skipped on Windows, and Cygwin, where a wchar_t is
619 // 16-bit wide. This code may not compile on those systems.
620
621 // Tests that Unicode code-points that have 17 to 21 bits are encoded
622 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
623 TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
624   // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
625   EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
626
627   // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
628   EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
629
630   // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
631   EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
632 }
633
634 // Tests that encoding an invalid code-point generates the expected result.
635 TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
636   EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
637 }
638
639 #endif  // !GTEST_WIDE_STRING_USES_UTF16_
640
641 // Tests WideStringToUtf8().
642
643 // Tests that the NUL character L'\0' is encoded correctly.
644 TEST(WideStringToUtf8Test, CanEncodeNul) {
645   EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
646   EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
647 }
648
649 // Tests that ASCII strings are encoded correctly.
650 TEST(WideStringToUtf8Test, CanEncodeAscii) {
651   EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
652   EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
653   EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
654   EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
655 }
656
657 // Tests that Unicode code-points that have 8 to 11 bits are encoded
658 // as 110xxxxx 10xxxxxx.
659 TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
660   // 000 1101 0011 => 110-00011 10-010011
661   EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
662   EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
663
664   // 101 0111 0110 => 110-10101 10-110110
665   const wchar_t s[] = { 0x576, '\0' };
666   EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
667   EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
668 }
669
670 // Tests that Unicode code-points that have 12 to 16 bits are encoded
671 // as 1110xxxx 10xxxxxx 10xxxxxx.
672 TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
673   // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
674   const wchar_t s1[] = { 0x8D3, '\0' };
675   EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
676   EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
677
678   // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
679   const wchar_t s2[] = { 0xC74D, '\0' };
680   EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
681   EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
682 }
683
684 // Tests that the conversion stops when the function encounters \0 character.
685 TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
686   EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
687 }
688
689 // Tests that the conversion stops when the function reaches the limit
690 // specified by the 'length' parameter.
691 TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
692   EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
693 }
694
695 #if !GTEST_WIDE_STRING_USES_UTF16_
696 // Tests that Unicode code-points that have 17 to 21 bits are encoded
697 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
698 // on the systems using UTF-16 encoding.
699 TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
700   // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
701   EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
702   EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
703
704   // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
705   EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
706   EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
707 }
708
709 // Tests that encoding an invalid code-point generates the expected result.
710 TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
711   EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
712                WideStringToUtf8(L"\xABCDFF", -1).c_str());
713 }
714 #else  // !GTEST_WIDE_STRING_USES_UTF16_
715 // Tests that surrogate pairs are encoded correctly on the systems using
716 // UTF-16 encoding in the wide strings.
717 TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
718   const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
719   EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
720 }
721
722 // Tests that encoding an invalid UTF-16 surrogate pair
723 // generates the expected result.
724 TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
725   // Leading surrogate is at the end of the string.
726   const wchar_t s1[] = { 0xD800, '\0' };
727   EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
728   // Leading surrogate is not followed by the trailing surrogate.
729   const wchar_t s2[] = { 0xD800, 'M', '\0' };
730   EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
731   // Trailing surrogate appearas without a leading surrogate.
732   const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
733   EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
734 }
735 #endif  // !GTEST_WIDE_STRING_USES_UTF16_
736
737 // Tests that codepoint concatenation works correctly.
738 #if !GTEST_WIDE_STRING_USES_UTF16_
739 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
740   const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
741   EXPECT_STREQ(
742       "\xF4\x88\x98\xB4"
743           "\xEC\x9D\x8D"
744           "\n"
745           "\xD5\xB6"
746           "\xE0\xA3\x93"
747           "\xF4\x88\x98\xB4",
748       WideStringToUtf8(s, -1).c_str());
749 }
750 #else
751 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
752   const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
753   EXPECT_STREQ(
754       "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
755       WideStringToUtf8(s, -1).c_str());
756 }
757 #endif  // !GTEST_WIDE_STRING_USES_UTF16_
758
759 // Tests the Random class.
760
761 TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
762   testing::internal::Random random(42);
763   EXPECT_DEATH_IF_SUPPORTED(
764       random.Generate(0),
765       "Cannot generate a number in the range \\[0, 0\\)");
766   EXPECT_DEATH_IF_SUPPORTED(
767       random.Generate(testing::internal::Random::kMaxRange + 1),
768       "Generation of a number in \\[0, 2147483649\\) was requested, "
769       "but this can only generate numbers in \\[0, 2147483648\\)");
770 }
771
772 TEST(RandomTest, GeneratesNumbersWithinRange) {
773   constexpr uint32_t kRange = 10000;
774   testing::internal::Random random(12345);
775   for (int i = 0; i < 10; i++) {
776     EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
777   }
778
779   testing::internal::Random random2(testing::internal::Random::kMaxRange);
780   for (int i = 0; i < 10; i++) {
781     EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
782   }
783 }
784
785 TEST(RandomTest, RepeatsWhenReseeded) {
786   constexpr int kSeed = 123;
787   constexpr int kArraySize = 10;
788   constexpr uint32_t kRange = 10000;
789   uint32_t values[kArraySize];
790
791   testing::internal::Random random(kSeed);
792   for (int i = 0; i < kArraySize; i++) {
793     values[i] = random.Generate(kRange);
794   }
795
796   random.Reseed(kSeed);
797   for (int i = 0; i < kArraySize; i++) {
798     EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
799   }
800 }
801
802 // Tests STL container utilities.
803
804 // Tests CountIf().
805
806 static bool IsPositive(int n) { return n > 0; }
807
808 TEST(ContainerUtilityTest, CountIf) {
809   std::vector<int> v;
810   EXPECT_EQ(0, CountIf(v, IsPositive));  // Works for an empty container.
811
812   v.push_back(-1);
813   v.push_back(0);
814   EXPECT_EQ(0, CountIf(v, IsPositive));  // Works when no value satisfies.
815
816   v.push_back(2);
817   v.push_back(-10);
818   v.push_back(10);
819   EXPECT_EQ(2, CountIf(v, IsPositive));
820 }
821
822 // Tests ForEach().
823
824 static int g_sum = 0;
825 static void Accumulate(int n) { g_sum += n; }
826
827 TEST(ContainerUtilityTest, ForEach) {
828   std::vector<int> v;
829   g_sum = 0;
830   ForEach(v, Accumulate);
831   EXPECT_EQ(0, g_sum);  // Works for an empty container;
832
833   g_sum = 0;
834   v.push_back(1);
835   ForEach(v, Accumulate);
836   EXPECT_EQ(1, g_sum);  // Works for a container with one element.
837
838   g_sum = 0;
839   v.push_back(20);
840   v.push_back(300);
841   ForEach(v, Accumulate);
842   EXPECT_EQ(321, g_sum);
843 }
844
845 // Tests GetElementOr().
846 TEST(ContainerUtilityTest, GetElementOr) {
847   std::vector<char> a;
848   EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
849
850   a.push_back('a');
851   a.push_back('b');
852   EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
853   EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
854   EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
855   EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
856 }
857
858 TEST(ContainerUtilityDeathTest, ShuffleRange) {
859   std::vector<int> a;
860   a.push_back(0);
861   a.push_back(1);
862   a.push_back(2);
863   testing::internal::Random random(1);
864
865   EXPECT_DEATH_IF_SUPPORTED(
866       ShuffleRange(&random, -1, 1, &a),
867       "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
868   EXPECT_DEATH_IF_SUPPORTED(
869       ShuffleRange(&random, 4, 4, &a),
870       "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
871   EXPECT_DEATH_IF_SUPPORTED(
872       ShuffleRange(&random, 3, 2, &a),
873       "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
874   EXPECT_DEATH_IF_SUPPORTED(
875       ShuffleRange(&random, 3, 4, &a),
876       "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
877 }
878
879 class VectorShuffleTest : public Test {
880  protected:
881   static const size_t kVectorSize = 20;
882
883   VectorShuffleTest() : random_(1) {
884     for (int i = 0; i < static_cast<int>(kVectorSize); i++) {
885       vector_.push_back(i);
886     }
887   }
888
889   static bool VectorIsCorrupt(const TestingVector& vector) {
890     if (kVectorSize != vector.size()) {
891       return true;
892     }
893
894     bool found_in_vector[kVectorSize] = { false };
895     for (size_t i = 0; i < vector.size(); i++) {
896       const int e = vector[i];
897       if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {
898         return true;
899       }
900       found_in_vector[e] = true;
901     }
902
903     // Vector size is correct, elements' range is correct, no
904     // duplicate elements.  Therefore no corruption has occurred.
905     return false;
906   }
907
908   static bool VectorIsNotCorrupt(const TestingVector& vector) {
909     return !VectorIsCorrupt(vector);
910   }
911
912   static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
913     for (int i = begin; i < end; i++) {
914       if (i != vector[static_cast<size_t>(i)]) {
915         return true;
916       }
917     }
918     return false;
919   }
920
921   static bool RangeIsUnshuffled(
922       const TestingVector& vector, int begin, int end) {
923     return !RangeIsShuffled(vector, begin, end);
924   }
925
926   static bool VectorIsShuffled(const TestingVector& vector) {
927     return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
928   }
929
930   static bool VectorIsUnshuffled(const TestingVector& vector) {
931     return !VectorIsShuffled(vector);
932   }
933
934   testing::internal::Random random_;
935   TestingVector vector_;
936 };  // class VectorShuffleTest
937
938 const size_t VectorShuffleTest::kVectorSize;
939
940 TEST_F(VectorShuffleTest, HandlesEmptyRange) {
941   // Tests an empty range at the beginning...
942   ShuffleRange(&random_, 0, 0, &vector_);
943   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
944   ASSERT_PRED1(VectorIsUnshuffled, vector_);
945
946   // ...in the middle...
947   ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
948   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
949   ASSERT_PRED1(VectorIsUnshuffled, vector_);
950
951   // ...at the end...
952   ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
953   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
954   ASSERT_PRED1(VectorIsUnshuffled, vector_);
955
956   // ...and past the end.
957   ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
958   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
959   ASSERT_PRED1(VectorIsUnshuffled, vector_);
960 }
961
962 TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
963   // Tests a size one range at the beginning...
964   ShuffleRange(&random_, 0, 1, &vector_);
965   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
966   ASSERT_PRED1(VectorIsUnshuffled, vector_);
967
968   // ...in the middle...
969   ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
970   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
971   ASSERT_PRED1(VectorIsUnshuffled, vector_);
972
973   // ...and at the end.
974   ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
975   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
976   ASSERT_PRED1(VectorIsUnshuffled, vector_);
977 }
978
979 // Because we use our own random number generator and a fixed seed,
980 // we can guarantee that the following "random" tests will succeed.
981
982 TEST_F(VectorShuffleTest, ShufflesEntireVector) {
983   Shuffle(&random_, &vector_);
984   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
985   EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
986
987   // Tests the first and last elements in particular to ensure that
988   // there are no off-by-one problems in our shuffle algorithm.
989   EXPECT_NE(0, vector_[0]);
990   EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);
991 }
992
993 TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
994   const int kRangeSize = kVectorSize/2;
995
996   ShuffleRange(&random_, 0, kRangeSize, &vector_);
997
998   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
999   EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
1000   EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize,
1001                static_cast<int>(kVectorSize));
1002 }
1003
1004 TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
1005   const int kRangeSize = kVectorSize / 2;
1006   ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
1007
1008   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1009   EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1010   EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize,
1011                static_cast<int>(kVectorSize));
1012 }
1013
1014 TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
1015   const int kRangeSize = static_cast<int>(kVectorSize) / 3;
1016   ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
1017
1018   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1019   EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1020   EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
1021   EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,
1022                static_cast<int>(kVectorSize));
1023 }
1024
1025 TEST_F(VectorShuffleTest, ShufflesRepeatably) {
1026   TestingVector vector2;
1027   for (size_t i = 0; i < kVectorSize; i++) {
1028     vector2.push_back(static_cast<int>(i));
1029   }
1030
1031   random_.Reseed(1234);
1032   Shuffle(&random_, &vector_);
1033   random_.Reseed(1234);
1034   Shuffle(&random_, &vector2);
1035
1036   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1037   ASSERT_PRED1(VectorIsNotCorrupt, vector2);
1038
1039   for (size_t i = 0; i < kVectorSize; i++) {
1040     EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
1041   }
1042 }
1043
1044 // Tests the size of the AssertHelper class.
1045
1046 TEST(AssertHelperTest, AssertHelperIsSmall) {
1047   // To avoid breaking clients that use lots of assertions in one
1048   // function, we cannot grow the size of AssertHelper.
1049   EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
1050 }
1051
1052 // Tests String::EndsWithCaseInsensitive().
1053 TEST(StringTest, EndsWithCaseInsensitive) {
1054   EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
1055   EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
1056   EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
1057   EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
1058
1059   EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
1060   EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
1061   EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
1062 }
1063
1064 // C++Builder's preprocessor is buggy; it fails to expand macros that
1065 // appear in macro parameters after wide char literals.  Provide an alias
1066 // for NULL as a workaround.
1067 static const wchar_t* const kNull = nullptr;
1068
1069 // Tests String::CaseInsensitiveWideCStringEquals
1070 TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1071   EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr));
1072   EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1073   EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1074   EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1075   EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
1076   EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1077   EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1078   EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1079 }
1080
1081 #if GTEST_OS_WINDOWS
1082
1083 // Tests String::ShowWideCString().
1084 TEST(StringTest, ShowWideCString) {
1085   EXPECT_STREQ("(null)",
1086                String::ShowWideCString(NULL).c_str());
1087   EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1088   EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1089 }
1090
1091 # if GTEST_OS_WINDOWS_MOBILE
1092 TEST(StringTest, AnsiAndUtf16Null) {
1093   EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1094   EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1095 }
1096
1097 TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1098   const char* ansi = String::Utf16ToAnsi(L"str");
1099   EXPECT_STREQ("str", ansi);
1100   delete [] ansi;
1101   const WCHAR* utf16 = String::AnsiToUtf16("str");
1102   EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
1103   delete [] utf16;
1104 }
1105
1106 TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1107   const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1108   EXPECT_STREQ(".:\\ \"*?", ansi);
1109   delete [] ansi;
1110   const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
1111   EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
1112   delete [] utf16;
1113 }
1114 # endif  // GTEST_OS_WINDOWS_MOBILE
1115
1116 #endif  // GTEST_OS_WINDOWS
1117
1118 // Tests TestProperty construction.
1119 TEST(TestPropertyTest, StringValue) {
1120   TestProperty property("key", "1");
1121   EXPECT_STREQ("key", property.key());
1122   EXPECT_STREQ("1", property.value());
1123 }
1124
1125 // Tests TestProperty replacing a value.
1126 TEST(TestPropertyTest, ReplaceStringValue) {
1127   TestProperty property("key", "1");
1128   EXPECT_STREQ("1", property.value());
1129   property.SetValue("2");
1130   EXPECT_STREQ("2", property.value());
1131 }
1132
1133 // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1134 // functions (i.e. their definitions cannot be inlined at the call
1135 // sites), or C++Builder won't compile the code.
1136 static void AddFatalFailure() {
1137   FAIL() << "Expected fatal failure.";
1138 }
1139
1140 static void AddNonfatalFailure() {
1141   ADD_FAILURE() << "Expected non-fatal failure.";
1142 }
1143
1144 class ScopedFakeTestPartResultReporterTest : public Test {
1145  public:  // Must be public and not protected due to a bug in g++ 3.4.2.
1146   enum FailureMode {
1147     FATAL_FAILURE,
1148     NONFATAL_FAILURE
1149   };
1150   static void AddFailure(FailureMode failure) {
1151     if (failure == FATAL_FAILURE) {
1152       AddFatalFailure();
1153     } else {
1154       AddNonfatalFailure();
1155     }
1156   }
1157 };
1158
1159 // Tests that ScopedFakeTestPartResultReporter intercepts test
1160 // failures.
1161 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
1162   TestPartResultArray results;
1163   {
1164     ScopedFakeTestPartResultReporter reporter(
1165         ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1166         &results);
1167     AddFailure(NONFATAL_FAILURE);
1168     AddFailure(FATAL_FAILURE);
1169   }
1170
1171   EXPECT_EQ(2, results.size());
1172   EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1173   EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1174 }
1175
1176 TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1177   TestPartResultArray results;
1178   {
1179     // Tests, that the deprecated constructor still works.
1180     ScopedFakeTestPartResultReporter reporter(&results);
1181     AddFailure(NONFATAL_FAILURE);
1182   }
1183   EXPECT_EQ(1, results.size());
1184 }
1185
1186 #if GTEST_IS_THREADSAFE
1187
1188 class ScopedFakeTestPartResultReporterWithThreadsTest
1189   : public ScopedFakeTestPartResultReporterTest {
1190  protected:
1191   static void AddFailureInOtherThread(FailureMode failure) {
1192     ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
1193     thread.Join();
1194   }
1195 };
1196
1197 TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1198        InterceptsTestFailuresInAllThreads) {
1199   TestPartResultArray results;
1200   {
1201     ScopedFakeTestPartResultReporter reporter(
1202         ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1203     AddFailure(NONFATAL_FAILURE);
1204     AddFailure(FATAL_FAILURE);
1205     AddFailureInOtherThread(NONFATAL_FAILURE);
1206     AddFailureInOtherThread(FATAL_FAILURE);
1207   }
1208
1209   EXPECT_EQ(4, results.size());
1210   EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1211   EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1212   EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1213   EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1214 }
1215
1216 #endif  // GTEST_IS_THREADSAFE
1217
1218 // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}.  Makes sure that they
1219 // work even if the failure is generated in a called function rather than
1220 // the current context.
1221
1222 typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
1223
1224 TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1225   EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
1226 }
1227
1228 TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1229   EXPECT_FATAL_FAILURE(AddFatalFailure(),
1230                        ::std::string("Expected fatal failure."));
1231 }
1232
1233 TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1234   // We have another test below to verify that the macro catches fatal
1235   // failures generated on another thread.
1236   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
1237                                       "Expected fatal failure.");
1238 }
1239
1240 #ifdef __BORLANDC__
1241 // Silences warnings: "Condition is always true"
1242 # pragma option push -w-ccc
1243 #endif
1244
1245 // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1246 // function even when the statement in it contains ASSERT_*.
1247
1248 int NonVoidFunction() {
1249   EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1250   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1251   return 0;
1252 }
1253
1254 TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1255   NonVoidFunction();
1256 }
1257
1258 // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1259 // current function even though 'statement' generates a fatal failure.
1260
1261 void DoesNotAbortHelper(bool* aborted) {
1262   EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1263   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1264
1265   *aborted = false;
1266 }
1267
1268 #ifdef __BORLANDC__
1269 // Restores warnings after previous "#pragma option push" suppressed them.
1270 # pragma option pop
1271 #endif
1272
1273 TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1274   bool aborted = true;
1275   DoesNotAbortHelper(&aborted);
1276   EXPECT_FALSE(aborted);
1277 }
1278
1279 // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1280 // statement that contains a macro which expands to code containing an
1281 // unprotected comma.
1282
1283 static int global_var = 0;
1284 #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1285
1286 TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1287 #ifndef __BORLANDC__
1288   // ICE's in C++Builder.
1289   EXPECT_FATAL_FAILURE({
1290     GTEST_USE_UNPROTECTED_COMMA_;
1291     AddFatalFailure();
1292   }, "");
1293 #endif
1294
1295   EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1296     GTEST_USE_UNPROTECTED_COMMA_;
1297     AddFatalFailure();
1298   }, "");
1299 }
1300
1301 // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1302
1303 typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1304
1305 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1306   EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1307                           "Expected non-fatal failure.");
1308 }
1309
1310 TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1311   EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1312                           ::std::string("Expected non-fatal failure."));
1313 }
1314
1315 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1316   // We have another test below to verify that the macro catches
1317   // non-fatal failures generated on another thread.
1318   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
1319                                          "Expected non-fatal failure.");
1320 }
1321
1322 // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1323 // statement that contains a macro which expands to code containing an
1324 // unprotected comma.
1325 TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1326   EXPECT_NONFATAL_FAILURE({
1327     GTEST_USE_UNPROTECTED_COMMA_;
1328     AddNonfatalFailure();
1329   }, "");
1330
1331   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1332     GTEST_USE_UNPROTECTED_COMMA_;
1333     AddNonfatalFailure();
1334   }, "");
1335 }
1336
1337 #if GTEST_IS_THREADSAFE
1338
1339 typedef ScopedFakeTestPartResultReporterWithThreadsTest
1340     ExpectFailureWithThreadsTest;
1341
1342 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1343   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1344                                       "Expected fatal failure.");
1345 }
1346
1347 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1348   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1349       AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1350 }
1351
1352 #endif  // GTEST_IS_THREADSAFE
1353
1354 // Tests the TestProperty class.
1355
1356 TEST(TestPropertyTest, ConstructorWorks) {
1357   const TestProperty property("key", "value");
1358   EXPECT_STREQ("key", property.key());
1359   EXPECT_STREQ("value", property.value());
1360 }
1361
1362 TEST(TestPropertyTest, SetValue) {
1363   TestProperty property("key", "value_1");
1364   EXPECT_STREQ("key", property.key());
1365   property.SetValue("value_2");
1366   EXPECT_STREQ("key", property.key());
1367   EXPECT_STREQ("value_2", property.value());
1368 }
1369
1370 // Tests the TestResult class
1371
1372 // The test fixture for testing TestResult.
1373 class TestResultTest : public Test {
1374  protected:
1375   typedef std::vector<TestPartResult> TPRVector;
1376
1377   // We make use of 2 TestPartResult objects,
1378   TestPartResult * pr1, * pr2;
1379
1380   // ... and 3 TestResult objects.
1381   TestResult * r0, * r1, * r2;
1382
1383   void SetUp() override {
1384     // pr1 is for success.
1385     pr1 = new TestPartResult(TestPartResult::kSuccess,
1386                              "foo/bar.cc",
1387                              10,
1388                              "Success!");
1389
1390     // pr2 is for fatal failure.
1391     pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1392                              "foo/bar.cc",
1393                              -1,  // This line number means "unknown"
1394                              "Failure!");
1395
1396     // Creates the TestResult objects.
1397     r0 = new TestResult();
1398     r1 = new TestResult();
1399     r2 = new TestResult();
1400
1401     // In order to test TestResult, we need to modify its internal
1402     // state, in particular the TestPartResult vector it holds.
1403     // test_part_results() returns a const reference to this vector.
1404     // We cast it to a non-const object s.t. it can be modified
1405     TPRVector* results1 = const_cast<TPRVector*>(
1406         &TestResultAccessor::test_part_results(*r1));
1407     TPRVector* results2 = const_cast<TPRVector*>(
1408         &TestResultAccessor::test_part_results(*r2));
1409
1410     // r0 is an empty TestResult.
1411
1412     // r1 contains a single SUCCESS TestPartResult.
1413     results1->push_back(*pr1);
1414
1415     // r2 contains a SUCCESS, and a FAILURE.
1416     results2->push_back(*pr1);
1417     results2->push_back(*pr2);
1418   }
1419
1420   void TearDown() override {
1421     delete pr1;
1422     delete pr2;
1423
1424     delete r0;
1425     delete r1;
1426     delete r2;
1427   }
1428
1429   // Helper that compares two TestPartResults.
1430   static void CompareTestPartResult(const TestPartResult& expected,
1431                                     const TestPartResult& actual) {
1432     EXPECT_EQ(expected.type(), actual.type());
1433     EXPECT_STREQ(expected.file_name(), actual.file_name());
1434     EXPECT_EQ(expected.line_number(), actual.line_number());
1435     EXPECT_STREQ(expected.summary(), actual.summary());
1436     EXPECT_STREQ(expected.message(), actual.message());
1437     EXPECT_EQ(expected.passed(), actual.passed());
1438     EXPECT_EQ(expected.failed(), actual.failed());
1439     EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1440     EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
1441   }
1442 };
1443
1444 // Tests TestResult::total_part_count().
1445 TEST_F(TestResultTest, total_part_count) {
1446   ASSERT_EQ(0, r0->total_part_count());
1447   ASSERT_EQ(1, r1->total_part_count());
1448   ASSERT_EQ(2, r2->total_part_count());
1449 }
1450
1451 // Tests TestResult::Passed().
1452 TEST_F(TestResultTest, Passed) {
1453   ASSERT_TRUE(r0->Passed());
1454   ASSERT_TRUE(r1->Passed());
1455   ASSERT_FALSE(r2->Passed());
1456 }
1457
1458 // Tests TestResult::Failed().
1459 TEST_F(TestResultTest, Failed) {
1460   ASSERT_FALSE(r0->Failed());
1461   ASSERT_FALSE(r1->Failed());
1462   ASSERT_TRUE(r2->Failed());
1463 }
1464
1465 // Tests TestResult::GetTestPartResult().
1466
1467 typedef TestResultTest TestResultDeathTest;
1468
1469 TEST_F(TestResultDeathTest, GetTestPartResult) {
1470   CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1471   CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1472   EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1473   EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
1474 }
1475
1476 // Tests TestResult has no properties when none are added.
1477 TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1478   TestResult test_result;
1479   ASSERT_EQ(0, test_result.test_property_count());
1480 }
1481
1482 // Tests TestResult has the expected property when added.
1483 TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1484   TestResult test_result;
1485   TestProperty property("key_1", "1");
1486   TestResultAccessor::RecordProperty(&test_result, "testcase", property);
1487   ASSERT_EQ(1, test_result.test_property_count());
1488   const TestProperty& actual_property = test_result.GetTestProperty(0);
1489   EXPECT_STREQ("key_1", actual_property.key());
1490   EXPECT_STREQ("1", actual_property.value());
1491 }
1492
1493 // Tests TestResult has multiple properties when added.
1494 TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1495   TestResult test_result;
1496   TestProperty property_1("key_1", "1");
1497   TestProperty property_2("key_2", "2");
1498   TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1499   TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1500   ASSERT_EQ(2, test_result.test_property_count());
1501   const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1502   EXPECT_STREQ("key_1", actual_property_1.key());
1503   EXPECT_STREQ("1", actual_property_1.value());
1504
1505   const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1506   EXPECT_STREQ("key_2", actual_property_2.key());
1507   EXPECT_STREQ("2", actual_property_2.value());
1508 }
1509
1510 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
1511 TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1512   TestResult test_result;
1513   TestProperty property_1_1("key_1", "1");
1514   TestProperty property_2_1("key_2", "2");
1515   TestProperty property_1_2("key_1", "12");
1516   TestProperty property_2_2("key_2", "22");
1517   TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
1518   TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
1519   TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
1520   TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
1521
1522   ASSERT_EQ(2, test_result.test_property_count());
1523   const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1524   EXPECT_STREQ("key_1", actual_property_1.key());
1525   EXPECT_STREQ("12", actual_property_1.value());
1526
1527   const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1528   EXPECT_STREQ("key_2", actual_property_2.key());
1529   EXPECT_STREQ("22", actual_property_2.value());
1530 }
1531
1532 // Tests TestResult::GetTestProperty().
1533 TEST(TestResultPropertyTest, GetTestProperty) {
1534   TestResult test_result;
1535   TestProperty property_1("key_1", "1");
1536   TestProperty property_2("key_2", "2");
1537   TestProperty property_3("key_3", "3");
1538   TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1539   TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1540   TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
1541
1542   const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1543   const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1544   const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
1545
1546   EXPECT_STREQ("key_1", fetched_property_1.key());
1547   EXPECT_STREQ("1", fetched_property_1.value());
1548
1549   EXPECT_STREQ("key_2", fetched_property_2.key());
1550   EXPECT_STREQ("2", fetched_property_2.value());
1551
1552   EXPECT_STREQ("key_3", fetched_property_3.key());
1553   EXPECT_STREQ("3", fetched_property_3.value());
1554
1555   EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1556   EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
1557 }
1558
1559 // Tests the Test class.
1560 //
1561 // It's difficult to test every public method of this class (we are
1562 // already stretching the limit of Google Test by using it to test itself!).
1563 // Fortunately, we don't have to do that, as we are already testing
1564 // the functionalities of the Test class extensively by using Google Test
1565 // alone.
1566 //
1567 // Therefore, this section only contains one test.
1568
1569 // Tests that GTestFlagSaver works on Windows and Mac.
1570
1571 class GTestFlagSaverTest : public Test {
1572  protected:
1573   // Saves the Google Test flags such that we can restore them later, and
1574   // then sets them to their default values.  This will be called
1575   // before the first test in this test case is run.
1576   static void SetUpTestSuite() {
1577     saver_ = new GTestFlagSaver;
1578
1579     GTEST_FLAG_SET(also_run_disabled_tests, false);
1580     GTEST_FLAG_SET(break_on_failure, false);
1581     GTEST_FLAG_SET(catch_exceptions, false);
1582     GTEST_FLAG_SET(death_test_use_fork, false);
1583     GTEST_FLAG_SET(color, "auto");
1584     GTEST_FLAG_SET(fail_fast, false);
1585     GTEST_FLAG_SET(filter, "");
1586     GTEST_FLAG_SET(list_tests, false);
1587     GTEST_FLAG_SET(output, "");
1588     GTEST_FLAG_SET(brief, false);
1589     GTEST_FLAG_SET(print_time, true);
1590     GTEST_FLAG_SET(random_seed, 0);
1591     GTEST_FLAG_SET(repeat, 1);
1592     GTEST_FLAG_SET(recreate_environments_when_repeating, true);
1593     GTEST_FLAG_SET(shuffle, false);
1594     GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
1595     GTEST_FLAG_SET(stream_result_to, "");
1596     GTEST_FLAG_SET(throw_on_failure, false);
1597   }
1598
1599   // Restores the Google Test flags that the tests have modified.  This will
1600   // be called after the last test in this test case is run.
1601   static void TearDownTestSuite() {
1602     delete saver_;
1603     saver_ = nullptr;
1604   }
1605
1606   // Verifies that the Google Test flags have their default values, and then
1607   // modifies each of them.
1608   void VerifyAndModifyFlags() {
1609     EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests));
1610     EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure));
1611     EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions));
1612     EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str());
1613     EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork));
1614     EXPECT_FALSE(GTEST_FLAG_GET(fail_fast));
1615     EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str());
1616     EXPECT_FALSE(GTEST_FLAG_GET(list_tests));
1617     EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str());
1618     EXPECT_FALSE(GTEST_FLAG_GET(brief));
1619     EXPECT_TRUE(GTEST_FLAG_GET(print_time));
1620     EXPECT_EQ(0, GTEST_FLAG_GET(random_seed));
1621     EXPECT_EQ(1, GTEST_FLAG_GET(repeat));
1622     EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating));
1623     EXPECT_FALSE(GTEST_FLAG_GET(shuffle));
1624     EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth));
1625     EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str());
1626     EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure));
1627
1628     GTEST_FLAG_SET(also_run_disabled_tests, true);
1629     GTEST_FLAG_SET(break_on_failure, true);
1630     GTEST_FLAG_SET(catch_exceptions, true);
1631     GTEST_FLAG_SET(color, "no");
1632     GTEST_FLAG_SET(death_test_use_fork, true);
1633     GTEST_FLAG_SET(fail_fast, true);
1634     GTEST_FLAG_SET(filter, "abc");
1635     GTEST_FLAG_SET(list_tests, true);
1636     GTEST_FLAG_SET(output, "xml:foo.xml");
1637     GTEST_FLAG_SET(brief, true);
1638     GTEST_FLAG_SET(print_time, false);
1639     GTEST_FLAG_SET(random_seed, 1);
1640     GTEST_FLAG_SET(repeat, 100);
1641     GTEST_FLAG_SET(recreate_environments_when_repeating, false);
1642     GTEST_FLAG_SET(shuffle, true);
1643     GTEST_FLAG_SET(stack_trace_depth, 1);
1644     GTEST_FLAG_SET(stream_result_to, "localhost:1234");
1645     GTEST_FLAG_SET(throw_on_failure, true);
1646   }
1647
1648  private:
1649   // For saving Google Test flags during this test case.
1650   static GTestFlagSaver* saver_;
1651 };
1652
1653 GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;
1654
1655 // Google Test doesn't guarantee the order of tests.  The following two
1656 // tests are designed to work regardless of their order.
1657
1658 // Modifies the Google Test flags in the test body.
1659 TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1660   VerifyAndModifyFlags();
1661 }
1662
1663 // Verifies that the Google Test flags in the body of the previous test were
1664 // restored to their original values.
1665 TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1666   VerifyAndModifyFlags();
1667 }
1668
1669 // Sets an environment variable with the given name to the given
1670 // value.  If the value argument is "", unsets the environment
1671 // variable.  The caller must ensure that both arguments are not NULL.
1672 static void SetEnv(const char* name, const char* value) {
1673 #if GTEST_OS_WINDOWS_MOBILE
1674   // Environment variables are not supported on Windows CE.
1675   return;
1676 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1677   // C++Builder's putenv only stores a pointer to its parameter; we have to
1678   // ensure that the string remains valid as long as it might be needed.
1679   // We use an std::map to do so.
1680   static std::map<std::string, std::string*> added_env;
1681
1682   // Because putenv stores a pointer to the string buffer, we can't delete the
1683   // previous string (if present) until after it's replaced.
1684   std::string *prev_env = NULL;
1685   if (added_env.find(name) != added_env.end()) {
1686     prev_env = added_env[name];
1687   }
1688   added_env[name] = new std::string(
1689       (Message() << name << "=" << value).GetString());
1690
1691   // The standard signature of putenv accepts a 'char*' argument. Other
1692   // implementations, like C++Builder's, accept a 'const char*'.
1693   // We cast away the 'const' since that would work for both variants.
1694   putenv(const_cast<char*>(added_env[name]->c_str()));
1695   delete prev_env;
1696 #elif GTEST_OS_WINDOWS  // If we are on Windows proper.
1697   _putenv((Message() << name << "=" << value).GetString().c_str());
1698 #else
1699   if (*value == '\0') {
1700     unsetenv(name);
1701   } else {
1702     setenv(name, value, 1);
1703   }
1704 #endif  // GTEST_OS_WINDOWS_MOBILE
1705 }
1706
1707 #if !GTEST_OS_WINDOWS_MOBILE
1708 // Environment variables are not supported on Windows CE.
1709
1710 using testing::internal::Int32FromGTestEnv;
1711
1712 // Tests Int32FromGTestEnv().
1713
1714 // Tests that Int32FromGTestEnv() returns the default value when the
1715 // environment variable is not set.
1716 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1717   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1718   EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1719 }
1720
1721 # if !defined(GTEST_GET_INT32_FROM_ENV_)
1722
1723 // Tests that Int32FromGTestEnv() returns the default value when the
1724 // environment variable overflows as an Int32.
1725 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1726   printf("(expecting 2 warnings)\n");
1727
1728   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1729   EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1730
1731   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1732   EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1733 }
1734
1735 // Tests that Int32FromGTestEnv() returns the default value when the
1736 // environment variable does not represent a valid decimal integer.
1737 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1738   printf("(expecting 2 warnings)\n");
1739
1740   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1741   EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1742
1743   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1744   EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1745 }
1746
1747 # endif  // !defined(GTEST_GET_INT32_FROM_ENV_)
1748
1749 // Tests that Int32FromGTestEnv() parses and returns the value of the
1750 // environment variable when it represents a valid decimal integer in
1751 // the range of an Int32.
1752 TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1753   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1754   EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1755
1756   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1757   EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1758 }
1759 #endif  // !GTEST_OS_WINDOWS_MOBILE
1760
1761 // Tests ParseFlag().
1762
1763 // Tests that ParseInt32Flag() returns false and doesn't change the
1764 // output value when the flag has wrong format
1765 TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1766   int32_t value = 123;
1767   EXPECT_FALSE(ParseFlag("--a=100", "b", &value));
1768   EXPECT_EQ(123, value);
1769
1770   EXPECT_FALSE(ParseFlag("a=100", "a", &value));
1771   EXPECT_EQ(123, value);
1772 }
1773
1774 // Tests that ParseFlag() returns false and doesn't change the
1775 // output value when the flag overflows as an Int32.
1776 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1777   printf("(expecting 2 warnings)\n");
1778
1779   int32_t value = 123;
1780   EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value));
1781   EXPECT_EQ(123, value);
1782
1783   EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value));
1784   EXPECT_EQ(123, value);
1785 }
1786
1787 // Tests that ParseInt32Flag() returns false and doesn't change the
1788 // output value when the flag does not represent a valid decimal
1789 // integer.
1790 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1791   printf("(expecting 2 warnings)\n");
1792
1793   int32_t value = 123;
1794   EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value));
1795   EXPECT_EQ(123, value);
1796
1797   EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value));
1798   EXPECT_EQ(123, value);
1799 }
1800
1801 // Tests that ParseInt32Flag() parses the value of the flag and
1802 // returns true when the flag represents a valid decimal integer in
1803 // the range of an Int32.
1804 TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1805   int32_t value = 123;
1806   EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1807   EXPECT_EQ(456, value);
1808
1809   EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value));
1810   EXPECT_EQ(-789, value);
1811 }
1812
1813 // Tests that Int32FromEnvOrDie() parses the value of the var or
1814 // returns the correct default.
1815 // Environment variables are not supported on Windows CE.
1816 #if !GTEST_OS_WINDOWS_MOBILE
1817 TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1818   EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1819   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1820   EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1821   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1822   EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1823 }
1824 #endif  // !GTEST_OS_WINDOWS_MOBILE
1825
1826 // Tests that Int32FromEnvOrDie() aborts with an error message
1827 // if the variable is not an int32_t.
1828 TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1829   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1830   EXPECT_DEATH_IF_SUPPORTED(
1831       Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1832       ".*");
1833 }
1834
1835 // Tests that Int32FromEnvOrDie() aborts with an error message
1836 // if the variable cannot be represented by an int32_t.
1837 TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1838   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1839   EXPECT_DEATH_IF_SUPPORTED(
1840       Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1841       ".*");
1842 }
1843
1844 // Tests that ShouldRunTestOnShard() selects all tests
1845 // where there is 1 shard.
1846 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1847   EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1848   EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1849   EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1850   EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1851   EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1852 }
1853
1854 class ShouldShardTest : public testing::Test {
1855  protected:
1856   void SetUp() override {
1857     index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1858     total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1859   }
1860
1861   void TearDown() override {
1862     SetEnv(index_var_, "");
1863     SetEnv(total_var_, "");
1864   }
1865
1866   const char* index_var_;
1867   const char* total_var_;
1868 };
1869
1870 // Tests that sharding is disabled if neither of the environment variables
1871 // are set.
1872 TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1873   SetEnv(index_var_, "");
1874   SetEnv(total_var_, "");
1875
1876   EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1877   EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1878 }
1879
1880 // Tests that sharding is not enabled if total_shards  == 1.
1881 TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1882   SetEnv(index_var_, "0");
1883   SetEnv(total_var_, "1");
1884   EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1885   EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1886 }
1887
1888 // Tests that sharding is enabled if total_shards > 1 and
1889 // we are not in a death test subprocess.
1890 // Environment variables are not supported on Windows CE.
1891 #if !GTEST_OS_WINDOWS_MOBILE
1892 TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1893   SetEnv(index_var_, "4");
1894   SetEnv(total_var_, "22");
1895   EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1896   EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1897
1898   SetEnv(index_var_, "8");
1899   SetEnv(total_var_, "9");
1900   EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1901   EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1902
1903   SetEnv(index_var_, "0");
1904   SetEnv(total_var_, "9");
1905   EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1906   EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1907 }
1908 #endif  // !GTEST_OS_WINDOWS_MOBILE
1909
1910 // Tests that we exit in error if the sharding values are not valid.
1911
1912 typedef ShouldShardTest ShouldShardDeathTest;
1913
1914 TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
1915   SetEnv(index_var_, "4");
1916   SetEnv(total_var_, "4");
1917   EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1918
1919   SetEnv(index_var_, "4");
1920   SetEnv(total_var_, "-2");
1921   EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1922
1923   SetEnv(index_var_, "5");
1924   SetEnv(total_var_, "");
1925   EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1926
1927   SetEnv(index_var_, "");
1928   SetEnv(total_var_, "5");
1929   EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1930 }
1931
1932 // Tests that ShouldRunTestOnShard is a partition when 5
1933 // shards are used.
1934 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1935   // Choose an arbitrary number of tests and shards.
1936   const int num_tests = 17;
1937   const int num_shards = 5;
1938
1939   // Check partitioning: each test should be on exactly 1 shard.
1940   for (int test_id = 0; test_id < num_tests; test_id++) {
1941     int prev_selected_shard_index = -1;
1942     for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1943       if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1944         if (prev_selected_shard_index < 0) {
1945           prev_selected_shard_index = shard_index;
1946         } else {
1947           ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1948             << shard_index << " are both selected to run test " << test_id;
1949         }
1950       }
1951     }
1952   }
1953
1954   // Check balance: This is not required by the sharding protocol, but is a
1955   // desirable property for performance.
1956   for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1957     int num_tests_on_shard = 0;
1958     for (int test_id = 0; test_id < num_tests; test_id++) {
1959       num_tests_on_shard +=
1960         ShouldRunTestOnShard(num_shards, shard_index, test_id);
1961     }
1962     EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1963   }
1964 }
1965
1966 // For the same reason we are not explicitly testing everything in the
1967 // Test class, there are no separate tests for the following classes
1968 // (except for some trivial cases):
1969 //
1970 //   TestSuite, UnitTest, UnitTestResultPrinter.
1971 //
1972 // Similarly, there are no separate tests for the following macros:
1973 //
1974 //   TEST, TEST_F, RUN_ALL_TESTS
1975
1976 TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1977   ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr);
1978   EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1979 }
1980
1981 TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
1982   EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
1983   EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
1984 }
1985
1986 // When a property using a reserved key is supplied to this function, it
1987 // tests that a non-fatal failure is added, a fatal failure is not added,
1988 // and that the property is not recorded.
1989 void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1990     const TestResult& test_result, const char* key) {
1991   EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
1992   ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
1993                                                   << "' recorded unexpectedly.";
1994 }
1995
1996 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
1997     const char* key) {
1998   const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
1999   ASSERT_TRUE(test_info != nullptr);
2000   ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
2001                                                         key);
2002 }
2003
2004 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2005     const char* key) {
2006   const testing::TestSuite* test_suite =
2007       UnitTest::GetInstance()->current_test_suite();
2008   ASSERT_TRUE(test_suite != nullptr);
2009   ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2010       test_suite->ad_hoc_test_result(), key);
2011 }
2012
2013 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2014     const char* key) {
2015   ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2016       UnitTest::GetInstance()->ad_hoc_test_result(), key);
2017 }
2018
2019 // Tests that property recording functions in UnitTest outside of tests
2020 // functions correcly.  Creating a separate instance of UnitTest ensures it
2021 // is in a state similar to the UnitTest's singleton's between tests.
2022 class UnitTestRecordPropertyTest :
2023     public testing::internal::UnitTestRecordPropertyTestHelper {
2024  public:
2025   static void SetUpTestSuite() {
2026     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2027         "disabled");
2028     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2029         "errors");
2030     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2031         "failures");
2032     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2033         "name");
2034     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2035         "tests");
2036     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2037         "time");
2038
2039     Test::RecordProperty("test_case_key_1", "1");
2040
2041     const testing::TestSuite* test_suite =
2042         UnitTest::GetInstance()->current_test_suite();
2043
2044     ASSERT_TRUE(test_suite != nullptr);
2045
2046     ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count());
2047     EXPECT_STREQ("test_case_key_1",
2048                  test_suite->ad_hoc_test_result().GetTestProperty(0).key());
2049     EXPECT_STREQ("1",
2050                  test_suite->ad_hoc_test_result().GetTestProperty(0).value());
2051   }
2052 };
2053
2054 // Tests TestResult has the expected property when added.
2055 TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
2056   UnitTestRecordProperty("key_1", "1");
2057
2058   ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
2059
2060   EXPECT_STREQ("key_1",
2061                unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2062   EXPECT_STREQ("1",
2063                unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2064 }
2065
2066 // Tests TestResult has multiple properties when added.
2067 TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
2068   UnitTestRecordProperty("key_1", "1");
2069   UnitTestRecordProperty("key_2", "2");
2070
2071   ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2072
2073   EXPECT_STREQ("key_1",
2074                unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2075   EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2076
2077   EXPECT_STREQ("key_2",
2078                unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2079   EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2080 }
2081
2082 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
2083 TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
2084   UnitTestRecordProperty("key_1", "1");
2085   UnitTestRecordProperty("key_2", "2");
2086   UnitTestRecordProperty("key_1", "12");
2087   UnitTestRecordProperty("key_2", "22");
2088
2089   ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2090
2091   EXPECT_STREQ("key_1",
2092                unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2093   EXPECT_STREQ("12",
2094                unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2095
2096   EXPECT_STREQ("key_2",
2097                unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2098   EXPECT_STREQ("22",
2099                unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2100 }
2101
2102 TEST_F(UnitTestRecordPropertyTest,
2103        AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
2104   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2105       "name");
2106   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2107       "value_param");
2108   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2109       "type_param");
2110   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2111       "status");
2112   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2113       "time");
2114   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2115       "classname");
2116 }
2117
2118 TEST_F(UnitTestRecordPropertyTest,
2119        AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
2120   EXPECT_NONFATAL_FAILURE(
2121       Test::RecordProperty("name", "1"),
2122       "'classname', 'name', 'status', 'time', 'type_param', 'value_param',"
2123       " 'file', and 'line' are reserved");
2124 }
2125
2126 class UnitTestRecordPropertyTestEnvironment : public Environment {
2127  public:
2128   void TearDown() override {
2129     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2130         "tests");
2131     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2132         "failures");
2133     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2134         "disabled");
2135     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2136         "errors");
2137     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2138         "name");
2139     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2140         "timestamp");
2141     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2142         "time");
2143     ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2144         "random_seed");
2145   }
2146 };
2147
2148 // This will test property recording outside of any test or test case.
2149 static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ =
2150     AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
2151
2152 // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2153 // of various arities.  They do not attempt to be exhaustive.  Rather,
2154 // view them as smoke tests that can be easily reviewed and verified.
2155 // A more complete set of tests for predicate assertions can be found
2156 // in gtest_pred_impl_unittest.cc.
2157
2158 // First, some predicates and predicate-formatters needed by the tests.
2159
2160 // Returns true if and only if the argument is an even number.
2161 bool IsEven(int n) {
2162   return (n % 2) == 0;
2163 }
2164
2165 // A functor that returns true if and only if the argument is an even number.
2166 struct IsEvenFunctor {
2167   bool operator()(int n) { return IsEven(n); }
2168 };
2169
2170 // A predicate-formatter function that asserts the argument is an even
2171 // number.
2172 AssertionResult AssertIsEven(const char* expr, int n) {
2173   if (IsEven(n)) {
2174     return AssertionSuccess();
2175   }
2176
2177   Message msg;
2178   msg << expr << " evaluates to " << n << ", which is not even.";
2179   return AssertionFailure(msg);
2180 }
2181
2182 // A predicate function that returns AssertionResult for use in
2183 // EXPECT/ASSERT_TRUE/FALSE.
2184 AssertionResult ResultIsEven(int n) {
2185   if (IsEven(n))
2186     return AssertionSuccess() << n << " is even";
2187   else
2188     return AssertionFailure() << n << " is odd";
2189 }
2190
2191 // A predicate function that returns AssertionResult but gives no
2192 // explanation why it succeeds. Needed for testing that
2193 // EXPECT/ASSERT_FALSE handles such functions correctly.
2194 AssertionResult ResultIsEvenNoExplanation(int n) {
2195   if (IsEven(n))
2196     return AssertionSuccess();
2197   else
2198     return AssertionFailure() << n << " is odd";
2199 }
2200
2201 // A predicate-formatter functor that asserts the argument is an even
2202 // number.
2203 struct AssertIsEvenFunctor {
2204   AssertionResult operator()(const char* expr, int n) {
2205     return AssertIsEven(expr, n);
2206   }
2207 };
2208
2209 // Returns true if and only if the sum of the arguments is an even number.
2210 bool SumIsEven2(int n1, int n2) {
2211   return IsEven(n1 + n2);
2212 }
2213
2214 // A functor that returns true if and only if the sum of the arguments is an
2215 // even number.
2216 struct SumIsEven3Functor {
2217   bool operator()(int n1, int n2, int n3) {
2218     return IsEven(n1 + n2 + n3);
2219   }
2220 };
2221
2222 // A predicate-formatter function that asserts the sum of the
2223 // arguments is an even number.
2224 AssertionResult AssertSumIsEven4(
2225     const char* e1, const char* e2, const char* e3, const char* e4,
2226     int n1, int n2, int n3, int n4) {
2227   const int sum = n1 + n2 + n3 + n4;
2228   if (IsEven(sum)) {
2229     return AssertionSuccess();
2230   }
2231
2232   Message msg;
2233   msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2234       << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2235       << ") evaluates to " << sum << ", which is not even.";
2236   return AssertionFailure(msg);
2237 }
2238
2239 // A predicate-formatter functor that asserts the sum of the arguments
2240 // is an even number.
2241 struct AssertSumIsEven5Functor {
2242   AssertionResult operator()(
2243       const char* e1, const char* e2, const char* e3, const char* e4,
2244       const char* e5, int n1, int n2, int n3, int n4, int n5) {
2245     const int sum = n1 + n2 + n3 + n4 + n5;
2246     if (IsEven(sum)) {
2247       return AssertionSuccess();
2248     }
2249
2250     Message msg;
2251     msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2252         << " ("
2253         << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2254         << ") evaluates to " << sum << ", which is not even.";
2255     return AssertionFailure(msg);
2256   }
2257 };
2258
2259
2260 // Tests unary predicate assertions.
2261
2262 // Tests unary predicate assertions that don't use a custom formatter.
2263 TEST(Pred1Test, WithoutFormat) {
2264   // Success cases.
2265   EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2266   ASSERT_PRED1(IsEven, 4);
2267
2268   // Failure cases.
2269   EXPECT_NONFATAL_FAILURE({  // NOLINT
2270     EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2271   }, "This failure is expected.");
2272   EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2273                        "evaluates to false");
2274 }
2275
2276 // Tests unary predicate assertions that use a custom formatter.
2277 TEST(Pred1Test, WithFormat) {
2278   // Success cases.
2279   EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2280   ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2281     << "This failure is UNEXPECTED!";
2282
2283   // Failure cases.
2284   const int n = 5;
2285   EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2286                           "n evaluates to 5, which is not even.");
2287   EXPECT_FATAL_FAILURE({  // NOLINT
2288     ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2289   }, "This failure is expected.");
2290 }
2291
2292 // Tests that unary predicate assertions evaluates their arguments
2293 // exactly once.
2294 TEST(Pred1Test, SingleEvaluationOnFailure) {
2295   // A success case.
2296   static int n = 0;
2297   EXPECT_PRED1(IsEven, n++);
2298   EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2299
2300   // A failure case.
2301   EXPECT_FATAL_FAILURE({  // NOLINT
2302     ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2303         << "This failure is expected.";
2304   }, "This failure is expected.");
2305   EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2306 }
2307
2308
2309 // Tests predicate assertions whose arity is >= 2.
2310
2311 // Tests predicate assertions that don't use a custom formatter.
2312 TEST(PredTest, WithoutFormat) {
2313   // Success cases.
2314   ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2315   EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2316
2317   // Failure cases.
2318   const int n1 = 1;
2319   const int n2 = 2;
2320   EXPECT_NONFATAL_FAILURE({  // NOLINT
2321     EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2322   }, "This failure is expected.");
2323   EXPECT_FATAL_FAILURE({  // NOLINT
2324     ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2325   }, "evaluates to false");
2326 }
2327
2328 // Tests predicate assertions that use a custom formatter.
2329 TEST(PredTest, WithFormat) {
2330   // Success cases.
2331   ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2332     "This failure is UNEXPECTED!";
2333   EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2334
2335   // Failure cases.
2336   const int n1 = 1;
2337   const int n2 = 2;
2338   const int n3 = 4;
2339   const int n4 = 6;
2340   EXPECT_NONFATAL_FAILURE({  // NOLINT
2341     EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2342   }, "evaluates to 13, which is not even.");
2343   EXPECT_FATAL_FAILURE({  // NOLINT
2344     ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2345         << "This failure is expected.";
2346   }, "This failure is expected.");
2347 }
2348
2349 // Tests that predicate assertions evaluates their arguments
2350 // exactly once.
2351 TEST(PredTest, SingleEvaluationOnFailure) {
2352   // A success case.
2353   int n1 = 0;
2354   int n2 = 0;
2355   EXPECT_PRED2(SumIsEven2, n1++, n2++);
2356   EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2357   EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2358
2359   // Another success case.
2360   n1 = n2 = 0;
2361   int n3 = 0;
2362   int n4 = 0;
2363   int n5 = 0;
2364   ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2365                       n1++, n2++, n3++, n4++, n5++)
2366                         << "This failure is UNEXPECTED!";
2367   EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2368   EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2369   EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2370   EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2371   EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2372
2373   // A failure case.
2374   n1 = n2 = n3 = 0;
2375   EXPECT_NONFATAL_FAILURE({  // NOLINT
2376     EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2377         << "This failure is expected.";
2378   }, "This failure is expected.");
2379   EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2380   EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2381   EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2382
2383   // Another failure case.
2384   n1 = n2 = n3 = n4 = 0;
2385   EXPECT_NONFATAL_FAILURE({  // NOLINT
2386     EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2387   }, "evaluates to 1, which is not even.");
2388   EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2389   EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2390   EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2391   EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2392 }
2393
2394 // Test predicate assertions for sets
2395 TEST(PredTest, ExpectPredEvalFailure) {
2396   std::set<int> set_a = {2, 1, 3, 4, 5};
2397   std::set<int> set_b = {0, 4, 8};
2398   const auto compare_sets = [] (std::set<int>, std::set<int>) { return false; };
2399   EXPECT_NONFATAL_FAILURE(
2400       EXPECT_PRED2(compare_sets, set_a, set_b),
2401       "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates "
2402       "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }");
2403 }
2404
2405 // Some helper functions for testing using overloaded/template
2406 // functions with ASSERT_PREDn and EXPECT_PREDn.
2407
2408 bool IsPositive(double x) {
2409   return x > 0;
2410 }
2411
2412 template <typename T>
2413 bool IsNegative(T x) {
2414   return x < 0;
2415 }
2416
2417 template <typename T1, typename T2>
2418 bool GreaterThan(T1 x1, T2 x2) {
2419   return x1 > x2;
2420 }
2421
2422 // Tests that overloaded functions can be used in *_PRED* as long as
2423 // their types are explicitly specified.
2424 TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2425   // C++Builder requires C-style casts rather than static_cast.
2426   EXPECT_PRED1((bool (*)(int))(IsPositive), 5);  // NOLINT
2427   ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0);  // NOLINT
2428 }
2429
2430 // Tests that template functions can be used in *_PRED* as long as
2431 // their types are explicitly specified.
2432 TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2433   EXPECT_PRED1(IsNegative<int>, -5);
2434   // Makes sure that we can handle templates with more than one
2435   // parameter.
2436   ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2437 }
2438
2439
2440 // Some helper functions for testing using overloaded/template
2441 // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2442
2443 AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2444   return n > 0 ? AssertionSuccess() :
2445       AssertionFailure(Message() << "Failure");
2446 }
2447
2448 AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2449   return x > 0 ? AssertionSuccess() :
2450       AssertionFailure(Message() << "Failure");
2451 }
2452
2453 template <typename T>
2454 AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2455   return x < 0 ? AssertionSuccess() :
2456       AssertionFailure(Message() << "Failure");
2457 }
2458
2459 template <typename T1, typename T2>
2460 AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2461                              const T1& x1, const T2& x2) {
2462   return x1 == x2 ? AssertionSuccess() :
2463       AssertionFailure(Message() << "Failure");
2464 }
2465
2466 // Tests that overloaded functions can be used in *_PRED_FORMAT*
2467 // without explicitly specifying their types.
2468 TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2469   EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2470   ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2471 }
2472
2473 // Tests that template functions can be used in *_PRED_FORMAT* without
2474 // explicitly specifying their types.
2475 TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2476   EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2477   ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2478 }
2479
2480
2481 // Tests string assertions.
2482
2483 // Tests ASSERT_STREQ with non-NULL arguments.
2484 TEST(StringAssertionTest, ASSERT_STREQ) {
2485   const char * const p1 = "good";
2486   ASSERT_STREQ(p1, p1);
2487
2488   // Let p2 have the same content as p1, but be at a different address.
2489   const char p2[] = "good";
2490   ASSERT_STREQ(p1, p2);
2491
2492   EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2493                        "  \"bad\"\n  \"good\"");
2494 }
2495
2496 // Tests ASSERT_STREQ with NULL arguments.
2497 TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2498   ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr);
2499   EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null");
2500 }
2501
2502 // Tests ASSERT_STREQ with NULL arguments.
2503 TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2504   EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null");
2505 }
2506
2507 // Tests ASSERT_STRNE.
2508 TEST(StringAssertionTest, ASSERT_STRNE) {
2509   ASSERT_STRNE("hi", "Hi");
2510   ASSERT_STRNE("Hi", nullptr);
2511   ASSERT_STRNE(nullptr, "Hi");
2512   ASSERT_STRNE("", nullptr);
2513   ASSERT_STRNE(nullptr, "");
2514   ASSERT_STRNE("", "Hi");
2515   ASSERT_STRNE("Hi", "");
2516   EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2517                        "\"Hi\" vs \"Hi\"");
2518 }
2519
2520 // Tests ASSERT_STRCASEEQ.
2521 TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2522   ASSERT_STRCASEEQ("hi", "Hi");
2523   ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);
2524
2525   ASSERT_STRCASEEQ("", "");
2526   EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2527                        "Ignoring case");
2528 }
2529
2530 // Tests ASSERT_STRCASENE.
2531 TEST(StringAssertionTest, ASSERT_STRCASENE) {
2532   ASSERT_STRCASENE("hi1", "Hi2");
2533   ASSERT_STRCASENE("Hi", nullptr);
2534   ASSERT_STRCASENE(nullptr, "Hi");
2535   ASSERT_STRCASENE("", nullptr);
2536   ASSERT_STRCASENE(nullptr, "");
2537   ASSERT_STRCASENE("", "Hi");
2538   ASSERT_STRCASENE("Hi", "");
2539   EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2540                        "(ignoring case)");
2541 }
2542
2543 // Tests *_STREQ on wide strings.
2544 TEST(StringAssertionTest, STREQ_Wide) {
2545   // NULL strings.
2546   ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr);
2547
2548   // Empty strings.
2549   ASSERT_STREQ(L"", L"");
2550
2551   // Non-null vs NULL.
2552   EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null");
2553
2554   // Equal strings.
2555   EXPECT_STREQ(L"Hi", L"Hi");
2556
2557   // Unequal strings.
2558   EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2559                           "Abc");
2560
2561   // Strings containing wide characters.
2562   EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2563                           "abc");
2564
2565   // The streaming variation.
2566   EXPECT_NONFATAL_FAILURE({  // NOLINT
2567     EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
2568   }, "Expected failure");
2569 }
2570
2571 // Tests *_STRNE on wide strings.
2572 TEST(StringAssertionTest, STRNE_Wide) {
2573   // NULL strings.
2574   EXPECT_NONFATAL_FAILURE(
2575       {  // NOLINT
2576         EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr);
2577       },
2578       "");
2579
2580   // Empty strings.
2581   EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2582                           "L\"\"");
2583
2584   // Non-null vs NULL.
2585   ASSERT_STRNE(L"non-null", nullptr);
2586
2587   // Equal strings.
2588   EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2589                           "L\"Hi\"");
2590
2591   // Unequal strings.
2592   EXPECT_STRNE(L"abc", L"Abc");
2593
2594   // Strings containing wide characters.
2595   EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2596                           "abc");
2597
2598   // The streaming variation.
2599   ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
2600 }
2601
2602 // Tests for ::testing::IsSubstring().
2603
2604 // Tests that IsSubstring() returns the correct result when the input
2605 // argument type is const char*.
2606 TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2607   EXPECT_FALSE(IsSubstring("", "", nullptr, "a"));
2608   EXPECT_FALSE(IsSubstring("", "", "b", nullptr));
2609   EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2610
2611   EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr));
2612   EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2613 }
2614
2615 // Tests that IsSubstring() returns the correct result when the input
2616 // argument type is const wchar_t*.
2617 TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2618   EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2619   EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
2620   EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2621
2622   EXPECT_TRUE(
2623       IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr));
2624   EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2625 }
2626
2627 // Tests that IsSubstring() generates the correct message when the input
2628 // argument type is const char*.
2629 TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2630   EXPECT_STREQ("Value of: needle_expr\n"
2631                "  Actual: \"needle\"\n"
2632                "Expected: a substring of haystack_expr\n"
2633                "Which is: \"haystack\"",
2634                IsSubstring("needle_expr", "haystack_expr",
2635                            "needle", "haystack").failure_message());
2636 }
2637
2638 // Tests that IsSubstring returns the correct result when the input
2639 // argument type is ::std::string.
2640 TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2641   EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2642   EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2643 }
2644
2645 #if GTEST_HAS_STD_WSTRING
2646 // Tests that IsSubstring returns the correct result when the input
2647 // argument type is ::std::wstring.
2648 TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2649   EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2650   EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2651 }
2652
2653 // Tests that IsSubstring() generates the correct message when the input
2654 // argument type is ::std::wstring.
2655 TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2656   EXPECT_STREQ("Value of: needle_expr\n"
2657                "  Actual: L\"needle\"\n"
2658                "Expected: a substring of haystack_expr\n"
2659                "Which is: L\"haystack\"",
2660                IsSubstring(
2661                    "needle_expr", "haystack_expr",
2662                    ::std::wstring(L"needle"), L"haystack").failure_message());
2663 }
2664
2665 #endif  // GTEST_HAS_STD_WSTRING
2666
2667 // Tests for ::testing::IsNotSubstring().
2668
2669 // Tests that IsNotSubstring() returns the correct result when the input
2670 // argument type is const char*.
2671 TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2672   EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2673   EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2674 }
2675
2676 // Tests that IsNotSubstring() returns the correct result when the input
2677 // argument type is const wchar_t*.
2678 TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2679   EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2680   EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2681 }
2682
2683 // Tests that IsNotSubstring() generates the correct message when the input
2684 // argument type is const wchar_t*.
2685 TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2686   EXPECT_STREQ("Value of: needle_expr\n"
2687                "  Actual: L\"needle\"\n"
2688                "Expected: not a substring of haystack_expr\n"
2689                "Which is: L\"two needles\"",
2690                IsNotSubstring(
2691                    "needle_expr", "haystack_expr",
2692                    L"needle", L"two needles").failure_message());
2693 }
2694
2695 // Tests that IsNotSubstring returns the correct result when the input
2696 // argument type is ::std::string.
2697 TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2698   EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2699   EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2700 }
2701
2702 // Tests that IsNotSubstring() generates the correct message when the input
2703 // argument type is ::std::string.
2704 TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2705   EXPECT_STREQ("Value of: needle_expr\n"
2706                "  Actual: \"needle\"\n"
2707                "Expected: not a substring of haystack_expr\n"
2708                "Which is: \"two needles\"",
2709                IsNotSubstring(
2710                    "needle_expr", "haystack_expr",
2711                    ::std::string("needle"), "two needles").failure_message());
2712 }
2713
2714 #if GTEST_HAS_STD_WSTRING
2715
2716 // Tests that IsNotSubstring returns the correct result when the input
2717 // argument type is ::std::wstring.
2718 TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2719   EXPECT_FALSE(
2720       IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2721   EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2722 }
2723
2724 #endif  // GTEST_HAS_STD_WSTRING
2725
2726 // Tests floating-point assertions.
2727
2728 template <typename RawType>
2729 class FloatingPointTest : public Test {
2730  protected:
2731   // Pre-calculated numbers to be used by the tests.
2732   struct TestValues {
2733     RawType close_to_positive_zero;
2734     RawType close_to_negative_zero;
2735     RawType further_from_negative_zero;
2736
2737     RawType close_to_one;
2738     RawType further_from_one;
2739
2740     RawType infinity;
2741     RawType close_to_infinity;
2742     RawType further_from_infinity;
2743
2744     RawType nan1;
2745     RawType nan2;
2746   };
2747
2748   typedef typename testing::internal::FloatingPoint<RawType> Floating;
2749   typedef typename Floating::Bits Bits;
2750
2751   void SetUp() override {
2752     const uint32_t max_ulps = Floating::kMaxUlps;
2753
2754     // The bits that represent 0.0.
2755     const Bits zero_bits = Floating(0).bits();
2756
2757     // Makes some numbers close to 0.0.
2758     values_.close_to_positive_zero = Floating::ReinterpretBits(
2759         zero_bits + max_ulps/2);
2760     values_.close_to_negative_zero = -Floating::ReinterpretBits(
2761         zero_bits + max_ulps - max_ulps/2);
2762     values_.further_from_negative_zero = -Floating::ReinterpretBits(
2763         zero_bits + max_ulps + 1 - max_ulps/2);
2764
2765     // The bits that represent 1.0.
2766     const Bits one_bits = Floating(1).bits();
2767
2768     // Makes some numbers close to 1.0.
2769     values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2770     values_.further_from_one = Floating::ReinterpretBits(
2771         one_bits + max_ulps + 1);
2772
2773     // +infinity.
2774     values_.infinity = Floating::Infinity();
2775
2776     // The bits that represent +infinity.
2777     const Bits infinity_bits = Floating(values_.infinity).bits();
2778
2779     // Makes some numbers close to infinity.
2780     values_.close_to_infinity = Floating::ReinterpretBits(
2781         infinity_bits - max_ulps);
2782     values_.further_from_infinity = Floating::ReinterpretBits(
2783         infinity_bits - max_ulps - 1);
2784
2785     // Makes some NAN's.  Sets the most significant bit of the fraction so that
2786     // our NaN's are quiet; trying to process a signaling NaN would raise an
2787     // exception if our environment enables floating point exceptions.
2788     values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2789         | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2790     values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2791         | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
2792   }
2793
2794   void TestSize() {
2795     EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2796   }
2797
2798   static TestValues values_;
2799 };
2800
2801 template <typename RawType>
2802 typename FloatingPointTest<RawType>::TestValues
2803     FloatingPointTest<RawType>::values_;
2804
2805 // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2806 typedef FloatingPointTest<float> FloatTest;
2807
2808 // Tests that the size of Float::Bits matches the size of float.
2809 TEST_F(FloatTest, Size) {
2810   TestSize();
2811 }
2812
2813 // Tests comparing with +0 and -0.
2814 TEST_F(FloatTest, Zeros) {
2815   EXPECT_FLOAT_EQ(0.0, -0.0);
2816   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2817                           "1.0");
2818   EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2819                        "1.5");
2820 }
2821
2822 // Tests comparing numbers close to 0.
2823 //
2824 // This ensures that *_FLOAT_EQ handles the sign correctly and no
2825 // overflow occurs when comparing numbers whose absolute value is very
2826 // small.
2827 TEST_F(FloatTest, AlmostZeros) {
2828   // In C++Builder, names within local classes (such as used by
2829   // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2830   // scoping class.  Use a static local alias as a workaround.
2831   // We use the assignment syntax since some compilers, like Sun Studio,
2832   // don't allow initializing references using construction syntax
2833   // (parentheses).
2834   static const FloatTest::TestValues& v = this->values_;
2835
2836   EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2837   EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2838   EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2839
2840   EXPECT_FATAL_FAILURE({  // NOLINT
2841     ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2842                     v.further_from_negative_zero);
2843   }, "v.further_from_negative_zero");
2844 }
2845
2846 // Tests comparing numbers close to each other.
2847 TEST_F(FloatTest, SmallDiff) {
2848   EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2849   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2850                           "values_.further_from_one");
2851 }
2852
2853 // Tests comparing numbers far apart.
2854 TEST_F(FloatTest, LargeDiff) {
2855   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2856                           "3.0");
2857 }
2858
2859 // Tests comparing with infinity.
2860 //
2861 // This ensures that no overflow occurs when comparing numbers whose
2862 // absolute value is very large.
2863 TEST_F(FloatTest, Infinity) {
2864   EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2865   EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
2866   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2867                           "-values_.infinity");
2868
2869   // This is interesting as the representations of infinity and nan1
2870   // are only 1 DLP apart.
2871   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2872                           "values_.nan1");
2873 }
2874
2875 // Tests that comparing with NAN always returns false.
2876 TEST_F(FloatTest, NaN) {
2877   // In C++Builder, names within local classes (such as used by
2878   // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2879   // scoping class.  Use a static local alias as a workaround.
2880   // We use the assignment syntax since some compilers, like Sun Studio,
2881   // don't allow initializing references using construction syntax
2882   // (parentheses).
2883   static const FloatTest::TestValues& v = this->values_;
2884
2885   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2886                           "v.nan1");
2887   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2888                           "v.nan2");
2889   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2890                           "v.nan1");
2891
2892   EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2893                        "v.infinity");
2894 }
2895
2896 // Tests that *_FLOAT_EQ are reflexive.
2897 TEST_F(FloatTest, Reflexive) {
2898   EXPECT_FLOAT_EQ(0.0, 0.0);
2899   EXPECT_FLOAT_EQ(1.0, 1.0);
2900   ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
2901 }
2902
2903 // Tests that *_FLOAT_EQ are commutative.
2904 TEST_F(FloatTest, Commutative) {
2905   // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2906   EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2907
2908   // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2909   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2910                           "1.0");
2911 }
2912
2913 // Tests EXPECT_NEAR.
2914 TEST_F(FloatTest, EXPECT_NEAR) {
2915   EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2916   EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2917   EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f),  // NOLINT
2918                           "The difference between 1.0f and 1.5f is 0.5, "
2919                           "which exceeds 0.25f");
2920 }
2921
2922 // Tests ASSERT_NEAR.
2923 TEST_F(FloatTest, ASSERT_NEAR) {
2924   ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2925   ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2926   EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f),  // NOLINT
2927                        "The difference between 1.0f and 1.5f is 0.5, "
2928                        "which exceeds 0.25f");
2929 }
2930
2931 // Tests the cases where FloatLE() should succeed.
2932 TEST_F(FloatTest, FloatLESucceeds) {
2933   EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f);  // When val1 < val2,
2934   ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f);  // val1 == val2,
2935
2936   // or when val1 is greater than, but almost equals to, val2.
2937   EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2938 }
2939
2940 // Tests the cases where FloatLE() should fail.
2941 TEST_F(FloatTest, FloatLEFails) {
2942   // When val1 is greater than val2 by a large margin,
2943   EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2944                           "(2.0f) <= (1.0f)");
2945
2946   // or by a small yet non-negligible margin,
2947   EXPECT_NONFATAL_FAILURE({  // NOLINT
2948     EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2949   }, "(values_.further_from_one) <= (1.0f)");
2950
2951   EXPECT_NONFATAL_FAILURE({  // NOLINT
2952     EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2953   }, "(values_.nan1) <= (values_.infinity)");
2954   EXPECT_NONFATAL_FAILURE({  // NOLINT
2955     EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2956   }, "(-values_.infinity) <= (values_.nan1)");
2957   EXPECT_FATAL_FAILURE({  // NOLINT
2958     ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2959   }, "(values_.nan1) <= (values_.nan1)");
2960 }
2961
2962 // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2963 typedef FloatingPointTest<double> DoubleTest;
2964
2965 // Tests that the size of Double::Bits matches the size of double.
2966 TEST_F(DoubleTest, Size) {
2967   TestSize();
2968 }
2969
2970 // Tests comparing with +0 and -0.
2971 TEST_F(DoubleTest, Zeros) {
2972   EXPECT_DOUBLE_EQ(0.0, -0.0);
2973   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2974                           "1.0");
2975   EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2976                        "1.0");
2977 }
2978
2979 // Tests comparing numbers close to 0.
2980 //
2981 // This ensures that *_DOUBLE_EQ handles the sign correctly and no
2982 // overflow occurs when comparing numbers whose absolute value is very
2983 // small.
2984 TEST_F(DoubleTest, AlmostZeros) {
2985   // In C++Builder, names within local classes (such as used by
2986   // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2987   // scoping class.  Use a static local alias as a workaround.
2988   // We use the assignment syntax since some compilers, like Sun Studio,
2989   // don't allow initializing references using construction syntax
2990   // (parentheses).
2991   static const DoubleTest::TestValues& v = this->values_;
2992
2993   EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2994   EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2995   EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2996
2997   EXPECT_FATAL_FAILURE({  // NOLINT
2998     ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2999                      v.further_from_negative_zero);
3000   }, "v.further_from_negative_zero");
3001 }
3002
3003 // Tests comparing numbers close to each other.
3004 TEST_F(DoubleTest, SmallDiff) {
3005   EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
3006   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
3007                           "values_.further_from_one");
3008 }
3009
3010 // Tests comparing numbers far apart.
3011 TEST_F(DoubleTest, LargeDiff) {
3012   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
3013                           "3.0");
3014 }
3015
3016 // Tests comparing with infinity.
3017 //
3018 // This ensures that no overflow occurs when comparing numbers whose
3019 // absolute value is very large.
3020 TEST_F(DoubleTest, Infinity) {
3021   EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
3022   EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
3023   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
3024                           "-values_.infinity");
3025
3026   // This is interesting as the representations of infinity_ and nan1_
3027   // are only 1 DLP apart.
3028   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
3029                           "values_.nan1");
3030 }
3031
3032 // Tests that comparing with NAN always returns false.
3033 TEST_F(DoubleTest, NaN) {
3034   static const DoubleTest::TestValues& v = this->values_;
3035
3036   // Nokia's STLport crashes if we try to output infinity or NaN.
3037   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
3038                           "v.nan1");
3039   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
3040   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3041   EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
3042                        "v.infinity");
3043 }
3044
3045 // Tests that *_DOUBLE_EQ are reflexive.
3046 TEST_F(DoubleTest, Reflexive) {
3047   EXPECT_DOUBLE_EQ(0.0, 0.0);
3048   EXPECT_DOUBLE_EQ(1.0, 1.0);
3049   ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
3050 }
3051
3052 // Tests that *_DOUBLE_EQ are commutative.
3053 TEST_F(DoubleTest, Commutative) {
3054   // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3055   EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
3056
3057   // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3058   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3059                           "1.0");
3060 }
3061
3062 // Tests EXPECT_NEAR.
3063 TEST_F(DoubleTest, EXPECT_NEAR) {
3064   EXPECT_NEAR(-1.0, -1.1, 0.2);
3065   EXPECT_NEAR(2.0, 3.0, 1.0);
3066   EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25),  // NOLINT
3067                           "The difference between 1.0 and 1.5 is 0.5, "
3068                           "which exceeds 0.25");
3069   // At this magnitude adjacent doubles are 512.0 apart, so this triggers a
3070   // slightly different failure reporting path.
3071   EXPECT_NONFATAL_FAILURE(
3072       EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),
3073       "The abs_error parameter 1.0 evaluates to 1 which is smaller than the "
3074       "minimum distance between doubles for numbers of this magnitude which is "
3075       "512");
3076 }
3077
3078 // Tests ASSERT_NEAR.
3079 TEST_F(DoubleTest, ASSERT_NEAR) {
3080   ASSERT_NEAR(-1.0, -1.1, 0.2);
3081   ASSERT_NEAR(2.0, 3.0, 1.0);
3082   EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25),  // NOLINT
3083                        "The difference between 1.0 and 1.5 is 0.5, "
3084                        "which exceeds 0.25");
3085 }
3086
3087 // Tests the cases where DoubleLE() should succeed.
3088 TEST_F(DoubleTest, DoubleLESucceeds) {
3089   EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0);  // When val1 < val2,
3090   ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0);  // val1 == val2,
3091
3092   // or when val1 is greater than, but almost equals to, val2.
3093   EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3094 }
3095
3096 // Tests the cases where DoubleLE() should fail.
3097 TEST_F(DoubleTest, DoubleLEFails) {
3098   // When val1 is greater than val2 by a large margin,
3099   EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
3100                           "(2.0) <= (1.0)");
3101
3102   // or by a small yet non-negligible margin,
3103   EXPECT_NONFATAL_FAILURE({  // NOLINT
3104     EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3105   }, "(values_.further_from_one) <= (1.0)");
3106
3107   EXPECT_NONFATAL_FAILURE({  // NOLINT
3108     EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3109   }, "(values_.nan1) <= (values_.infinity)");
3110   EXPECT_NONFATAL_FAILURE({  // NOLINT
3111     EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3112   }, " (-values_.infinity) <= (values_.nan1)");
3113   EXPECT_FATAL_FAILURE({  // NOLINT
3114     ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3115   }, "(values_.nan1) <= (values_.nan1)");
3116 }
3117
3118
3119 // Verifies that a test or test case whose name starts with DISABLED_ is
3120 // not run.
3121
3122 // A test whose name starts with DISABLED_.
3123 // Should not run.
3124 TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3125   FAIL() << "Unexpected failure: Disabled test should not be run.";
3126 }
3127
3128 // A test whose name does not start with DISABLED_.
3129 // Should run.
3130 TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3131   EXPECT_EQ(1, 1);
3132 }
3133
3134 // A test case whose name starts with DISABLED_.
3135 // Should not run.
3136 TEST(DISABLED_TestSuite, TestShouldNotRun) {
3137   FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3138 }
3139
3140 // A test case and test whose names start with DISABLED_.
3141 // Should not run.
3142 TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {
3143   FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3144 }
3145
3146 // Check that when all tests in a test case are disabled, SetUpTestSuite() and
3147 // TearDownTestSuite() are not called.
3148 class DisabledTestsTest : public Test {
3149  protected:
3150   static void SetUpTestSuite() {
3151     FAIL() << "Unexpected failure: All tests disabled in test case. "
3152               "SetUpTestSuite() should not be called.";
3153   }
3154
3155   static void TearDownTestSuite() {
3156     FAIL() << "Unexpected failure: All tests disabled in test case. "
3157               "TearDownTestSuite() should not be called.";
3158   }
3159 };
3160
3161 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3162   FAIL() << "Unexpected failure: Disabled test should not be run.";
3163 }
3164
3165 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3166   FAIL() << "Unexpected failure: Disabled test should not be run.";
3167 }
3168
3169 // Tests that disabled typed tests aren't run.
3170
3171 template <typename T>
3172 class TypedTest : public Test {
3173 };
3174
3175 typedef testing::Types<int, double> NumericTypes;
3176 TYPED_TEST_SUITE(TypedTest, NumericTypes);
3177
3178 TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3179   FAIL() << "Unexpected failure: Disabled typed test should not run.";
3180 }
3181
3182 template <typename T>
3183 class DISABLED_TypedTest : public Test {
3184 };
3185
3186 TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
3187
3188 TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3189   FAIL() << "Unexpected failure: Disabled typed test should not run.";
3190 }
3191
3192 // Tests that disabled type-parameterized tests aren't run.
3193
3194 template <typename T>
3195 class TypedTestP : public Test {
3196 };
3197
3198 TYPED_TEST_SUITE_P(TypedTestP);
3199
3200 TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3201   FAIL() << "Unexpected failure: "
3202          << "Disabled type-parameterized test should not run.";
3203 }
3204
3205 REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
3206
3207 INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);
3208
3209 template <typename T>
3210 class DISABLED_TypedTestP : public Test {
3211 };
3212
3213 TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
3214
3215 TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3216   FAIL() << "Unexpected failure: "
3217          << "Disabled type-parameterized test should not run.";
3218 }
3219
3220 REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
3221
3222 INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
3223
3224 // Tests that assertion macros evaluate their arguments exactly once.
3225
3226 class SingleEvaluationTest : public Test {
3227  public:  // Must be public and not protected due to a bug in g++ 3.4.2.
3228   // This helper function is needed by the FailedASSERT_STREQ test
3229   // below.  It's public to work around C++Builder's bug with scoping local
3230   // classes.
3231   static void CompareAndIncrementCharPtrs() {
3232     ASSERT_STREQ(p1_++, p2_++);
3233   }
3234
3235   // This helper function is needed by the FailedASSERT_NE test below.  It's
3236   // public to work around C++Builder's bug with scoping local classes.
3237   static void CompareAndIncrementInts() {
3238     ASSERT_NE(a_++, b_++);
3239   }
3240
3241  protected:
3242   SingleEvaluationTest() {
3243     p1_ = s1_;
3244     p2_ = s2_;
3245     a_ = 0;
3246     b_ = 0;
3247   }
3248
3249   static const char* const s1_;
3250   static const char* const s2_;
3251   static const char* p1_;
3252   static const char* p2_;
3253
3254   static int a_;
3255   static int b_;
3256 };
3257
3258 const char* const SingleEvaluationTest::s1_ = "01234";
3259 const char* const SingleEvaluationTest::s2_ = "abcde";
3260 const char* SingleEvaluationTest::p1_;
3261 const char* SingleEvaluationTest::p2_;
3262 int SingleEvaluationTest::a_;
3263 int SingleEvaluationTest::b_;
3264
3265 // Tests that when ASSERT_STREQ fails, it evaluates its arguments
3266 // exactly once.
3267 TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3268   EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3269                        "p2_++");
3270   EXPECT_EQ(s1_ + 1, p1_);
3271   EXPECT_EQ(s2_ + 1, p2_);
3272 }
3273
3274 // Tests that string assertion arguments are evaluated exactly once.
3275 TEST_F(SingleEvaluationTest, ASSERT_STR) {
3276   // successful EXPECT_STRNE
3277   EXPECT_STRNE(p1_++, p2_++);
3278   EXPECT_EQ(s1_ + 1, p1_);
3279   EXPECT_EQ(s2_ + 1, p2_);
3280
3281   // failed EXPECT_STRCASEEQ
3282   EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3283                           "Ignoring case");
3284   EXPECT_EQ(s1_ + 2, p1_);
3285   EXPECT_EQ(s2_ + 2, p2_);
3286 }
3287
3288 // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3289 // once.
3290 TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3291   EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3292                        "(a_++) != (b_++)");
3293   EXPECT_EQ(1, a_);
3294   EXPECT_EQ(1, b_);
3295 }
3296
3297 // Tests that assertion arguments are evaluated exactly once.
3298 TEST_F(SingleEvaluationTest, OtherCases) {
3299   // successful EXPECT_TRUE
3300   EXPECT_TRUE(0 == a_++);  // NOLINT
3301   EXPECT_EQ(1, a_);
3302
3303   // failed EXPECT_TRUE
3304   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3305   EXPECT_EQ(2, a_);
3306
3307   // successful EXPECT_GT
3308   EXPECT_GT(a_++, b_++);
3309   EXPECT_EQ(3, a_);
3310   EXPECT_EQ(1, b_);
3311
3312   // failed EXPECT_LT
3313   EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3314   EXPECT_EQ(4, a_);
3315   EXPECT_EQ(2, b_);
3316
3317   // successful ASSERT_TRUE
3318   ASSERT_TRUE(0 < a_++);  // NOLINT
3319   EXPECT_EQ(5, a_);
3320
3321   // successful ASSERT_GT
3322   ASSERT_GT(a_++, b_++);
3323   EXPECT_EQ(6, a_);
3324   EXPECT_EQ(3, b_);
3325 }
3326
3327 #if GTEST_HAS_EXCEPTIONS
3328
3329 #if GTEST_HAS_RTTI
3330
3331 #ifdef _MSC_VER
3332 #define ERROR_DESC "class std::runtime_error"
3333 #else
3334 #define ERROR_DESC "std::runtime_error"
3335 #endif
3336
3337 #else  // GTEST_HAS_RTTI
3338
3339 #define ERROR_DESC "an std::exception-derived error"
3340
3341 #endif  // GTEST_HAS_RTTI
3342
3343 void ThrowAnInteger() {
3344   throw 1;
3345 }
3346 void ThrowRuntimeError(const char* what) {
3347   throw std::runtime_error(what);
3348 }
3349
3350 // Tests that assertion arguments are evaluated exactly once.
3351 TEST_F(SingleEvaluationTest, ExceptionTests) {
3352   // successful EXPECT_THROW
3353   EXPECT_THROW({  // NOLINT
3354     a_++;
3355     ThrowAnInteger();
3356   }, int);
3357   EXPECT_EQ(1, a_);
3358
3359   // failed EXPECT_THROW, throws different
3360   EXPECT_NONFATAL_FAILURE(EXPECT_THROW({  // NOLINT
3361     a_++;
3362     ThrowAnInteger();
3363   }, bool), "throws a different type");
3364   EXPECT_EQ(2, a_);
3365
3366   // failed EXPECT_THROW, throws runtime error
3367   EXPECT_NONFATAL_FAILURE(EXPECT_THROW({  // NOLINT
3368     a_++;
3369     ThrowRuntimeError("A description");
3370   }, bool), "throws " ERROR_DESC " with description \"A description\"");
3371   EXPECT_EQ(3, a_);
3372
3373   // failed EXPECT_THROW, throws nothing
3374   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3375   EXPECT_EQ(4, a_);
3376
3377   // successful EXPECT_NO_THROW
3378   EXPECT_NO_THROW(a_++);
3379   EXPECT_EQ(5, a_);
3380
3381   // failed EXPECT_NO_THROW
3382   EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({  // NOLINT
3383     a_++;
3384     ThrowAnInteger();
3385   }), "it throws");
3386   EXPECT_EQ(6, a_);
3387
3388   // successful EXPECT_ANY_THROW
3389   EXPECT_ANY_THROW({  // NOLINT
3390     a_++;
3391     ThrowAnInteger();
3392   });
3393   EXPECT_EQ(7, a_);
3394
3395   // failed EXPECT_ANY_THROW
3396   EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3397   EXPECT_EQ(8, a_);
3398 }
3399
3400 #endif  // GTEST_HAS_EXCEPTIONS
3401
3402 // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3403 class NoFatalFailureTest : public Test {
3404  protected:
3405   void Succeeds() {}
3406   void FailsNonFatal() {
3407     ADD_FAILURE() << "some non-fatal failure";
3408   }
3409   void Fails() {
3410     FAIL() << "some fatal failure";
3411   }
3412
3413   void DoAssertNoFatalFailureOnFails() {
3414     ASSERT_NO_FATAL_FAILURE(Fails());
3415     ADD_FAILURE() << "should not reach here.";
3416   }
3417
3418   void DoExpectNoFatalFailureOnFails() {
3419     EXPECT_NO_FATAL_FAILURE(Fails());
3420     ADD_FAILURE() << "other failure";
3421   }
3422 };
3423
3424 TEST_F(NoFatalFailureTest, NoFailure) {
3425   EXPECT_NO_FATAL_FAILURE(Succeeds());
3426   ASSERT_NO_FATAL_FAILURE(Succeeds());
3427 }
3428
3429 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3430   EXPECT_NONFATAL_FAILURE(
3431       EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3432       "some non-fatal failure");
3433   EXPECT_NONFATAL_FAILURE(
3434       ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3435       "some non-fatal failure");
3436 }
3437
3438 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3439   TestPartResultArray gtest_failures;
3440   {
3441     ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3442     DoAssertNoFatalFailureOnFails();
3443   }
3444   ASSERT_EQ(2, gtest_failures.size());
3445   EXPECT_EQ(TestPartResult::kFatalFailure,
3446             gtest_failures.GetTestPartResult(0).type());
3447   EXPECT_EQ(TestPartResult::kFatalFailure,
3448             gtest_failures.GetTestPartResult(1).type());
3449   EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3450                       gtest_failures.GetTestPartResult(0).message());
3451   EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3452                       gtest_failures.GetTestPartResult(1).message());
3453 }
3454
3455 TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3456   TestPartResultArray gtest_failures;
3457   {
3458     ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3459     DoExpectNoFatalFailureOnFails();
3460   }
3461   ASSERT_EQ(3, gtest_failures.size());
3462   EXPECT_EQ(TestPartResult::kFatalFailure,
3463             gtest_failures.GetTestPartResult(0).type());
3464   EXPECT_EQ(TestPartResult::kNonFatalFailure,
3465             gtest_failures.GetTestPartResult(1).type());
3466   EXPECT_EQ(TestPartResult::kNonFatalFailure,
3467             gtest_failures.GetTestPartResult(2).type());
3468   EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3469                       gtest_failures.GetTestPartResult(0).message());
3470   EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3471                       gtest_failures.GetTestPartResult(1).message());
3472   EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3473                       gtest_failures.GetTestPartResult(2).message());
3474 }
3475
3476 TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3477   TestPartResultArray gtest_failures;
3478   {
3479     ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3480     EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3481   }
3482   ASSERT_EQ(2, gtest_failures.size());
3483   EXPECT_EQ(TestPartResult::kNonFatalFailure,
3484             gtest_failures.GetTestPartResult(0).type());
3485   EXPECT_EQ(TestPartResult::kNonFatalFailure,
3486             gtest_failures.GetTestPartResult(1).type());
3487   EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3488                       gtest_failures.GetTestPartResult(0).message());
3489   EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3490                       gtest_failures.GetTestPartResult(1).message());
3491 }
3492
3493 // Tests non-string assertions.
3494
3495 std::string EditsToString(const std::vector<EditType>& edits) {
3496   std::string out;
3497   for (size_t i = 0; i < edits.size(); ++i) {
3498     static const char kEdits[] = " +-/";
3499     out.append(1, kEdits[edits[i]]);
3500   }
3501   return out;
3502 }
3503
3504 std::vector<size_t> CharsToIndices(const std::string& str) {
3505   std::vector<size_t> out;
3506   for (size_t i = 0; i < str.size(); ++i) {
3507     out.push_back(static_cast<size_t>(str[i]));
3508   }
3509   return out;
3510 }
3511
3512 std::vector<std::string> CharsToLines(const std::string& str) {
3513   std::vector<std::string> out;
3514   for (size_t i = 0; i < str.size(); ++i) {
3515     out.push_back(str.substr(i, 1));
3516   }
3517   return out;
3518 }
3519
3520 TEST(EditDistance, TestSuites) {
3521   struct Case {
3522     int line;
3523     const char* left;
3524     const char* right;
3525     const char* expected_edits;
3526     const char* expected_diff;
3527   };
3528   static const Case kCases[] = {
3529       // No change.
3530       {__LINE__, "A", "A", " ", ""},
3531       {__LINE__, "ABCDE", "ABCDE", "     ", ""},
3532       // Simple adds.
3533       {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
3534       {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
3535       // Simple removes.
3536       {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
3537       {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
3538       // Simple replaces.
3539       {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
3540       {__LINE__, "ABCD", "abcd", "////",
3541        "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
3542       // Path finding.
3543       {__LINE__, "ABCDEFGH", "ABXEGH1", "  -/ -  +",
3544        "@@ -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"},
3545       {__LINE__, "AAAABCCCC", "ABABCDCDC", "- /   + / ",
3546        "@@ -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"},
3547       {__LINE__, "ABCDE", "BCDCD", "-   +/",
3548        "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
3549       {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++     --   ++",
3550        "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
3551        "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
3552       {}};
3553   for (const Case* c = kCases; c->left; ++c) {
3554     EXPECT_TRUE(c->expected_edits ==
3555                 EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3556                                                     CharsToIndices(c->right))))
3557         << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
3558         << EditsToString(CalculateOptimalEdits(
3559                CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
3560     EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
3561                                                       CharsToLines(c->right)))
3562         << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
3563         << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
3564         << ">";
3565   }
3566 }
3567
3568 // Tests EqFailure(), used for implementing *EQ* assertions.
3569 TEST(AssertionTest, EqFailure) {
3570   const std::string foo_val("5"), bar_val("6");
3571   const std::string msg1(
3572       EqFailure("foo", "bar", foo_val, bar_val, false)
3573       .failure_message());
3574   EXPECT_STREQ(
3575       "Expected equality of these values:\n"
3576       "  foo\n"
3577       "    Which is: 5\n"
3578       "  bar\n"
3579       "    Which is: 6",
3580       msg1.c_str());
3581
3582   const std::string msg2(
3583       EqFailure("foo", "6", foo_val, bar_val, false)
3584       .failure_message());
3585   EXPECT_STREQ(
3586       "Expected equality of these values:\n"
3587       "  foo\n"
3588       "    Which is: 5\n"
3589       "  6",
3590       msg2.c_str());
3591
3592   const std::string msg3(
3593       EqFailure("5", "bar", foo_val, bar_val, false)
3594       .failure_message());
3595   EXPECT_STREQ(
3596       "Expected equality of these values:\n"
3597       "  5\n"
3598       "  bar\n"
3599       "    Which is: 6",
3600       msg3.c_str());
3601
3602   const std::string msg4(
3603       EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3604   EXPECT_STREQ(
3605       "Expected equality of these values:\n"
3606       "  5\n"
3607       "  6",
3608       msg4.c_str());
3609
3610   const std::string msg5(
3611       EqFailure("foo", "bar",
3612                 std::string("\"x\""), std::string("\"y\""),
3613                 true).failure_message());
3614   EXPECT_STREQ(
3615       "Expected equality of these values:\n"
3616       "  foo\n"
3617       "    Which is: \"x\"\n"
3618       "  bar\n"
3619       "    Which is: \"y\"\n"
3620       "Ignoring case",
3621       msg5.c_str());
3622 }
3623
3624 TEST(AssertionTest, EqFailureWithDiff) {
3625   const std::string left(
3626       "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
3627   const std::string right(
3628       "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
3629   const std::string msg1(
3630       EqFailure("left", "right", left, right, false).failure_message());
3631   EXPECT_STREQ(
3632       "Expected equality of these values:\n"
3633       "  left\n"
3634       "    Which is: "
3635       "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3636       "  right\n"
3637       "    Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3638       "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
3639       "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
3640       msg1.c_str());
3641 }
3642
3643 // Tests AppendUserMessage(), used for implementing the *EQ* macros.
3644 TEST(AssertionTest, AppendUserMessage) {
3645   const std::string foo("foo");
3646
3647   Message msg;
3648   EXPECT_STREQ("foo",
3649                AppendUserMessage(foo, msg).c_str());
3650
3651   msg << "bar";
3652   EXPECT_STREQ("foo\nbar",
3653                AppendUserMessage(foo, msg).c_str());
3654 }
3655
3656 #ifdef __BORLANDC__
3657 // Silences warnings: "Condition is always true", "Unreachable code"
3658 # pragma option push -w-ccc -w-rch
3659 #endif
3660
3661 // Tests ASSERT_TRUE.
3662 TEST(AssertionTest, ASSERT_TRUE) {
3663   ASSERT_TRUE(2 > 1);  // NOLINT
3664   EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3665                        "2 < 1");
3666 }
3667
3668 // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3669 TEST(AssertionTest, AssertTrueWithAssertionResult) {
3670   ASSERT_TRUE(ResultIsEven(2));
3671 #ifndef __BORLANDC__
3672   // ICE's in C++Builder.
3673   EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3674                        "Value of: ResultIsEven(3)\n"
3675                        "  Actual: false (3 is odd)\n"
3676                        "Expected: true");
3677 #endif
3678   ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3679   EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3680                        "Value of: ResultIsEvenNoExplanation(3)\n"
3681                        "  Actual: false (3 is odd)\n"
3682                        "Expected: true");
3683 }
3684
3685 // Tests ASSERT_FALSE.
3686 TEST(AssertionTest, ASSERT_FALSE) {
3687   ASSERT_FALSE(2 < 1);  // NOLINT
3688   EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3689                        "Value of: 2 > 1\n"
3690                        "  Actual: true\n"
3691                        "Expected: false");
3692 }
3693
3694 // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3695 TEST(AssertionTest, AssertFalseWithAssertionResult) {
3696   ASSERT_FALSE(ResultIsEven(3));
3697 #ifndef __BORLANDC__
3698   // ICE's in C++Builder.
3699   EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3700                        "Value of: ResultIsEven(2)\n"
3701                        "  Actual: true (2 is even)\n"
3702                        "Expected: false");
3703 #endif
3704   ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3705   EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3706                        "Value of: ResultIsEvenNoExplanation(2)\n"
3707                        "  Actual: true\n"
3708                        "Expected: false");
3709 }
3710
3711 #ifdef __BORLANDC__
3712 // Restores warnings after previous "#pragma option push" suppressed them
3713 # pragma option pop
3714 #endif
3715
3716 // Tests using ASSERT_EQ on double values.  The purpose is to make
3717 // sure that the specialization we did for integer and anonymous enums
3718 // isn't used for double arguments.
3719 TEST(ExpectTest, ASSERT_EQ_Double) {
3720   // A success.
3721   ASSERT_EQ(5.6, 5.6);
3722
3723   // A failure.
3724   EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3725                        "5.1");
3726 }
3727
3728 // Tests ASSERT_EQ.
3729 TEST(AssertionTest, ASSERT_EQ) {
3730   ASSERT_EQ(5, 2 + 3);
3731   EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3732                        "Expected equality of these values:\n"
3733                        "  5\n"
3734                        "  2*3\n"
3735                        "    Which is: 6");
3736 }
3737
3738 // Tests ASSERT_EQ(NULL, pointer).
3739 TEST(AssertionTest, ASSERT_EQ_NULL) {
3740   // A success.
3741   const char* p = nullptr;
3742   ASSERT_EQ(nullptr, p);
3743
3744   // A failure.
3745   static int n = 0;
3746   EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), "  &n\n    Which is:");
3747 }
3748
3749 // Tests ASSERT_EQ(0, non_pointer).  Since the literal 0 can be
3750 // treated as a null pointer by the compiler, we need to make sure
3751 // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3752 // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3753 TEST(ExpectTest, ASSERT_EQ_0) {
3754   int n = 0;
3755
3756   // A success.
3757   ASSERT_EQ(0, n);
3758
3759   // A failure.
3760   EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3761                        "  0\n  5.6");
3762 }
3763
3764 // Tests ASSERT_NE.
3765 TEST(AssertionTest, ASSERT_NE) {
3766   ASSERT_NE(6, 7);
3767   EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3768                        "Expected: ('a') != ('a'), "
3769                        "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3770 }
3771
3772 // Tests ASSERT_LE.
3773 TEST(AssertionTest, ASSERT_LE) {
3774   ASSERT_LE(2, 3);
3775   ASSERT_LE(2, 2);
3776   EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3777                        "Expected: (2) <= (0), actual: 2 vs 0");
3778 }
3779
3780 // Tests ASSERT_LT.
3781 TEST(AssertionTest, ASSERT_LT) {
3782   ASSERT_LT(2, 3);
3783   EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3784                        "Expected: (2) < (2), actual: 2 vs 2");
3785 }
3786
3787 // Tests ASSERT_GE.
3788 TEST(AssertionTest, ASSERT_GE) {
3789   ASSERT_GE(2, 1);
3790   ASSERT_GE(2, 2);
3791   EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3792                        "Expected: (2) >= (3), actual: 2 vs 3");
3793 }
3794
3795 // Tests ASSERT_GT.
3796 TEST(AssertionTest, ASSERT_GT) {
3797   ASSERT_GT(2, 1);
3798   EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3799                        "Expected: (2) > (2), actual: 2 vs 2");
3800 }
3801
3802 #if GTEST_HAS_EXCEPTIONS
3803
3804 void ThrowNothing() {}
3805
3806 // Tests ASSERT_THROW.
3807 TEST(AssertionTest, ASSERT_THROW) {
3808   ASSERT_THROW(ThrowAnInteger(), int);
3809
3810 # ifndef __BORLANDC__
3811
3812   // ICE's in C++Builder 2007 and 2009.
3813   EXPECT_FATAL_FAILURE(
3814       ASSERT_THROW(ThrowAnInteger(), bool),
3815       "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3816       "  Actual: it throws a different type.");
3817   EXPECT_FATAL_FAILURE(
3818       ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
3819       "Expected: ThrowRuntimeError(\"A description\") "
3820       "throws an exception of type std::logic_error.\n  "
3821       "Actual: it throws " ERROR_DESC " "
3822       "with description \"A description\".");
3823 # endif
3824
3825   EXPECT_FATAL_FAILURE(
3826       ASSERT_THROW(ThrowNothing(), bool),
3827       "Expected: ThrowNothing() throws an exception of type bool.\n"
3828       "  Actual: it throws nothing.");
3829 }
3830
3831 // Tests ASSERT_NO_THROW.
3832 TEST(AssertionTest, ASSERT_NO_THROW) {
3833   ASSERT_NO_THROW(ThrowNothing());
3834   EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3835                        "Expected: ThrowAnInteger() doesn't throw an exception."
3836                        "\n  Actual: it throws.");
3837   EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
3838                        "Expected: ThrowRuntimeError(\"A description\") "
3839                        "doesn't throw an exception.\n  "
3840                        "Actual: it throws " ERROR_DESC " "
3841                        "with description \"A description\".");
3842 }
3843
3844 // Tests ASSERT_ANY_THROW.
3845 TEST(AssertionTest, ASSERT_ANY_THROW) {
3846   ASSERT_ANY_THROW(ThrowAnInteger());
3847   EXPECT_FATAL_FAILURE(
3848       ASSERT_ANY_THROW(ThrowNothing()),
3849       "Expected: ThrowNothing() throws an exception.\n"
3850       "  Actual: it doesn't.");
3851 }
3852
3853 #endif  // GTEST_HAS_EXCEPTIONS
3854
3855 // Makes sure we deal with the precedence of <<.  This test should
3856 // compile.
3857 TEST(AssertionTest, AssertPrecedence) {
3858   ASSERT_EQ(1 < 2, true);
3859   bool false_value = false;
3860   ASSERT_EQ(true && false_value, false);
3861 }
3862
3863 // A subroutine used by the following test.
3864 void TestEq1(int x) {
3865   ASSERT_EQ(1, x);
3866 }
3867
3868 // Tests calling a test subroutine that's not part of a fixture.
3869 TEST(AssertionTest, NonFixtureSubroutine) {
3870   EXPECT_FATAL_FAILURE(TestEq1(2),
3871                        "  x\n    Which is: 2");
3872 }
3873
3874 // An uncopyable class.
3875 class Uncopyable {
3876  public:
3877   explicit Uncopyable(int a_value) : value_(a_value) {}
3878
3879   int value() const { return value_; }
3880   bool operator==(const Uncopyable& rhs) const {
3881     return value() == rhs.value();
3882   }
3883  private:
3884   // This constructor deliberately has no implementation, as we don't
3885   // want this class to be copyable.
3886   Uncopyable(const Uncopyable&);  // NOLINT
3887
3888   int value_;
3889 };
3890
3891 ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3892   return os << value.value();
3893 }
3894
3895
3896 bool IsPositiveUncopyable(const Uncopyable& x) {
3897   return x.value() > 0;
3898 }
3899
3900 // A subroutine used by the following test.
3901 void TestAssertNonPositive() {
3902   Uncopyable y(-1);
3903   ASSERT_PRED1(IsPositiveUncopyable, y);
3904 }
3905 // A subroutine used by the following test.
3906 void TestAssertEqualsUncopyable() {
3907   Uncopyable x(5);
3908   Uncopyable y(-1);
3909   ASSERT_EQ(x, y);
3910 }
3911
3912 // Tests that uncopyable objects can be used in assertions.
3913 TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3914   Uncopyable x(5);
3915   ASSERT_PRED1(IsPositiveUncopyable, x);
3916   ASSERT_EQ(x, x);
3917   EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3918     "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3919   EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3920                        "Expected equality of these values:\n"
3921                        "  x\n    Which is: 5\n  y\n    Which is: -1");
3922 }
3923
3924 // Tests that uncopyable objects can be used in expects.
3925 TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3926   Uncopyable x(5);
3927   EXPECT_PRED1(IsPositiveUncopyable, x);
3928   Uncopyable y(-1);
3929   EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3930     "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3931   EXPECT_EQ(x, x);
3932   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3933                           "Expected equality of these values:\n"
3934                           "  x\n    Which is: 5\n  y\n    Which is: -1");
3935 }
3936
3937 enum NamedEnum {
3938   kE1 = 0,
3939   kE2 = 1
3940 };
3941
3942 TEST(AssertionTest, NamedEnum) {
3943   EXPECT_EQ(kE1, kE1);
3944   EXPECT_LT(kE1, kE2);
3945   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3946   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
3947 }
3948
3949 // Sun Studio and HP aCC2reject this code.
3950 #if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3951
3952 // Tests using assertions with anonymous enums.
3953 enum {
3954   kCaseA = -1,
3955
3956 # if GTEST_OS_LINUX
3957
3958   // We want to test the case where the size of the anonymous enum is
3959   // larger than sizeof(int), to make sure our implementation of the
3960   // assertions doesn't truncate the enums.  However, MSVC
3961   // (incorrectly) doesn't allow an enum value to exceed the range of
3962   // an int, so this has to be conditionally compiled.
3963   //
3964   // On Linux, kCaseB and kCaseA have the same value when truncated to
3965   // int size.  We want to test whether this will confuse the
3966   // assertions.
3967   kCaseB = testing::internal::kMaxBiggestInt,
3968
3969 # else
3970
3971   kCaseB = INT_MAX,
3972
3973 # endif  // GTEST_OS_LINUX
3974
3975   kCaseC = 42
3976 };
3977
3978 TEST(AssertionTest, AnonymousEnum) {
3979 # if GTEST_OS_LINUX
3980
3981   EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
3982
3983 # endif  // GTEST_OS_LINUX
3984
3985   EXPECT_EQ(kCaseA, kCaseA);
3986   EXPECT_NE(kCaseA, kCaseB);
3987   EXPECT_LT(kCaseA, kCaseB);
3988   EXPECT_LE(kCaseA, kCaseB);
3989   EXPECT_GT(kCaseB, kCaseA);
3990   EXPECT_GE(kCaseA, kCaseA);
3991   EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
3992                           "(kCaseA) >= (kCaseB)");
3993   EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
3994                           "-1 vs 42");
3995
3996   ASSERT_EQ(kCaseA, kCaseA);
3997   ASSERT_NE(kCaseA, kCaseB);
3998   ASSERT_LT(kCaseA, kCaseB);
3999   ASSERT_LE(kCaseA, kCaseB);
4000   ASSERT_GT(kCaseB, kCaseA);
4001   ASSERT_GE(kCaseA, kCaseA);
4002
4003 # ifndef __BORLANDC__
4004
4005   // ICE's in C++Builder.
4006   EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
4007                        "  kCaseB\n    Which is: ");
4008   EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
4009                        "\n    Which is: 42");
4010 # endif
4011
4012   EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
4013                        "\n    Which is: -1");
4014 }
4015
4016 #endif  // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
4017
4018 #if GTEST_OS_WINDOWS
4019
4020 static HRESULT UnexpectedHRESULTFailure() {
4021   return E_UNEXPECTED;
4022 }
4023
4024 static HRESULT OkHRESULTSuccess() {
4025   return S_OK;
4026 }
4027
4028 static HRESULT FalseHRESULTSuccess() {
4029   return S_FALSE;
4030 }
4031
4032 // HRESULT assertion tests test both zero and non-zero
4033 // success codes as well as failure message for each.
4034 //
4035 // Windows CE doesn't support message texts.
4036 TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
4037   EXPECT_HRESULT_SUCCEEDED(S_OK);
4038   EXPECT_HRESULT_SUCCEEDED(S_FALSE);
4039
4040   EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4041     "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4042     "  Actual: 0x8000FFFF");
4043 }
4044
4045 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
4046   ASSERT_HRESULT_SUCCEEDED(S_OK);
4047   ASSERT_HRESULT_SUCCEEDED(S_FALSE);
4048
4049   EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4050     "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4051     "  Actual: 0x8000FFFF");
4052 }
4053
4054 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
4055   EXPECT_HRESULT_FAILED(E_UNEXPECTED);
4056
4057   EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
4058     "Expected: (OkHRESULTSuccess()) fails.\n"
4059     "  Actual: 0x0");
4060   EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
4061     "Expected: (FalseHRESULTSuccess()) fails.\n"
4062     "  Actual: 0x1");
4063 }
4064
4065 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4066   ASSERT_HRESULT_FAILED(E_UNEXPECTED);
4067
4068 # ifndef __BORLANDC__
4069
4070   // ICE's in C++Builder 2007 and 2009.
4071   EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4072     "Expected: (OkHRESULTSuccess()) fails.\n"
4073     "  Actual: 0x0");
4074 # endif
4075
4076   EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4077     "Expected: (FalseHRESULTSuccess()) fails.\n"
4078     "  Actual: 0x1");
4079 }
4080
4081 // Tests that streaming to the HRESULT macros works.
4082 TEST(HRESULTAssertionTest, Streaming) {
4083   EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4084   ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4085   EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4086   ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4087
4088   EXPECT_NONFATAL_FAILURE(
4089       EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4090       "expected failure");
4091
4092 # ifndef __BORLANDC__
4093
4094   // ICE's in C++Builder 2007 and 2009.
4095   EXPECT_FATAL_FAILURE(
4096       ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4097       "expected failure");
4098 # endif
4099
4100   EXPECT_NONFATAL_FAILURE(
4101       EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4102       "expected failure");
4103
4104   EXPECT_FATAL_FAILURE(
4105       ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4106       "expected failure");
4107 }
4108
4109 #endif  // GTEST_OS_WINDOWS
4110
4111 // The following code intentionally tests a suboptimal syntax.
4112 #ifdef __GNUC__
4113 #pragma GCC diagnostic push
4114 #pragma GCC diagnostic ignored "-Wdangling-else"
4115 #pragma GCC diagnostic ignored "-Wempty-body"
4116 #pragma GCC diagnostic ignored "-Wpragmas"
4117 #endif
4118 // Tests that the assertion macros behave like single statements.
4119 TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4120   if (AlwaysFalse())
4121     ASSERT_TRUE(false) << "This should never be executed; "
4122                           "It's a compilation test only.";
4123
4124   if (AlwaysTrue())
4125     EXPECT_FALSE(false);
4126   else
4127     ;  // NOLINT
4128
4129   if (AlwaysFalse())
4130     ASSERT_LT(1, 3);
4131
4132   if (AlwaysFalse())
4133     ;  // NOLINT
4134   else
4135     EXPECT_GT(3, 2) << "";
4136 }
4137 #ifdef __GNUC__
4138 #pragma GCC diagnostic pop
4139 #endif
4140
4141 #if GTEST_HAS_EXCEPTIONS
4142 // Tests that the compiler will not complain about unreachable code in the
4143 // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4144 TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4145   int n = 0;
4146
4147   EXPECT_THROW(throw 1, int);
4148   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4149   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4150   EXPECT_NO_THROW(n++);
4151   EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4152   EXPECT_ANY_THROW(throw 1);
4153   EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4154 }
4155
4156 TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
4157   EXPECT_THROW(throw std::exception(), std::exception);
4158 }
4159
4160 // The following code intentionally tests a suboptimal syntax.
4161 #ifdef __GNUC__
4162 #pragma GCC diagnostic push
4163 #pragma GCC diagnostic ignored "-Wdangling-else"
4164 #pragma GCC diagnostic ignored "-Wempty-body"
4165 #pragma GCC diagnostic ignored "-Wpragmas"
4166 #endif
4167 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4168   if (AlwaysFalse())
4169     EXPECT_THROW(ThrowNothing(), bool);
4170
4171   if (AlwaysTrue())
4172     EXPECT_THROW(ThrowAnInteger(), int);
4173   else
4174     ;  // NOLINT
4175
4176   if (AlwaysFalse())
4177     EXPECT_NO_THROW(ThrowAnInteger());
4178
4179   if (AlwaysTrue())
4180     EXPECT_NO_THROW(ThrowNothing());
4181   else
4182     ;  // NOLINT
4183
4184   if (AlwaysFalse())
4185     EXPECT_ANY_THROW(ThrowNothing());
4186
4187   if (AlwaysTrue())
4188     EXPECT_ANY_THROW(ThrowAnInteger());
4189   else
4190     ;  // NOLINT
4191 }
4192 #ifdef __GNUC__
4193 #pragma GCC diagnostic pop
4194 #endif
4195
4196 #endif  // GTEST_HAS_EXCEPTIONS
4197
4198 // The following code intentionally tests a suboptimal syntax.
4199 #ifdef __GNUC__
4200 #pragma GCC diagnostic push
4201 #pragma GCC diagnostic ignored "-Wdangling-else"
4202 #pragma GCC diagnostic ignored "-Wempty-body"
4203 #pragma GCC diagnostic ignored "-Wpragmas"
4204 #endif
4205 TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4206   if (AlwaysFalse())
4207     EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4208                                     << "It's a compilation test only.";
4209   else
4210     ;  // NOLINT
4211
4212   if (AlwaysFalse())
4213     ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4214   else
4215     ;  // NOLINT
4216
4217   if (AlwaysTrue())
4218     EXPECT_NO_FATAL_FAILURE(SUCCEED());
4219   else
4220     ;  // NOLINT
4221
4222   if (AlwaysFalse())
4223     ;  // NOLINT
4224   else
4225     ASSERT_NO_FATAL_FAILURE(SUCCEED());
4226 }
4227 #ifdef __GNUC__
4228 #pragma GCC diagnostic pop
4229 #endif
4230
4231 // Tests that the assertion macros work well with switch statements.
4232 TEST(AssertionSyntaxTest, WorksWithSwitch) {
4233   switch (0) {
4234     case 1:
4235       break;
4236     default:
4237       ASSERT_TRUE(true);
4238   }
4239
4240   switch (0)
4241     case 0:
4242       EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4243
4244   // Binary assertions are implemented using a different code path
4245   // than the Boolean assertions.  Hence we test them separately.
4246   switch (0) {
4247     case 1:
4248     default:
4249       ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4250   }
4251
4252   switch (0)
4253     case 0:
4254       EXPECT_NE(1, 2);
4255 }
4256
4257 #if GTEST_HAS_EXCEPTIONS
4258
4259 void ThrowAString() {
4260     throw "std::string";
4261 }
4262
4263 // Test that the exception assertion macros compile and work with const
4264 // type qualifier.
4265 TEST(AssertionSyntaxTest, WorksWithConst) {
4266     ASSERT_THROW(ThrowAString(), const char*);
4267
4268     EXPECT_THROW(ThrowAString(), const char*);
4269 }
4270
4271 #endif  // GTEST_HAS_EXCEPTIONS
4272
4273 }  // namespace
4274
4275 namespace testing {
4276
4277 // Tests that Google Test tracks SUCCEED*.
4278 TEST(SuccessfulAssertionTest, SUCCEED) {
4279   SUCCEED();
4280   SUCCEED() << "OK";
4281   EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4282 }
4283
4284 // Tests that Google Test doesn't track successful EXPECT_*.
4285 TEST(SuccessfulAssertionTest, EXPECT) {
4286   EXPECT_TRUE(true);
4287   EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4288 }
4289
4290 // Tests that Google Test doesn't track successful EXPECT_STR*.
4291 TEST(SuccessfulAssertionTest, EXPECT_STR) {
4292   EXPECT_STREQ("", "");
4293   EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4294 }
4295
4296 // Tests that Google Test doesn't track successful ASSERT_*.
4297 TEST(SuccessfulAssertionTest, ASSERT) {
4298   ASSERT_TRUE(true);
4299   EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4300 }
4301
4302 // Tests that Google Test doesn't track successful ASSERT_STR*.
4303 TEST(SuccessfulAssertionTest, ASSERT_STR) {
4304   ASSERT_STREQ("", "");
4305   EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4306 }
4307
4308 }  // namespace testing
4309
4310 namespace {
4311
4312 // Tests the message streaming variation of assertions.
4313
4314 TEST(AssertionWithMessageTest, EXPECT) {
4315   EXPECT_EQ(1, 1) << "This should succeed.";
4316   EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4317                           "Expected failure #1");
4318   EXPECT_LE(1, 2) << "This should succeed.";
4319   EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4320                           "Expected failure #2.");
4321   EXPECT_GE(1, 0) << "This should succeed.";
4322   EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4323                           "Expected failure #3.");
4324
4325   EXPECT_STREQ("1", "1") << "This should succeed.";
4326   EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4327                           "Expected failure #4.");
4328   EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4329   EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4330                           "Expected failure #5.");
4331
4332   EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4333   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4334                           "Expected failure #6.");
4335   EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4336 }
4337
4338 TEST(AssertionWithMessageTest, ASSERT) {
4339   ASSERT_EQ(1, 1) << "This should succeed.";
4340   ASSERT_NE(1, 2) << "This should succeed.";
4341   ASSERT_LE(1, 2) << "This should succeed.";
4342   ASSERT_LT(1, 2) << "This should succeed.";
4343   ASSERT_GE(1, 0) << "This should succeed.";
4344   EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4345                        "Expected failure.");
4346 }
4347
4348 TEST(AssertionWithMessageTest, ASSERT_STR) {
4349   ASSERT_STREQ("1", "1") << "This should succeed.";
4350   ASSERT_STRNE("1", "2") << "This should succeed.";
4351   ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4352   EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4353                        "Expected failure.");
4354 }
4355
4356 TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4357   ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4358   ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4359   EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.",  // NOLINT
4360                        "Expect failure.");
4361 }
4362
4363 // Tests using ASSERT_FALSE with a streamed message.
4364 TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4365   ASSERT_FALSE(false) << "This shouldn't fail.";
4366   EXPECT_FATAL_FAILURE({  // NOLINT
4367     ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4368                        << " evaluates to " << true;
4369   }, "Expected failure");
4370 }
4371
4372 // Tests using FAIL with a streamed message.
4373 TEST(AssertionWithMessageTest, FAIL) {
4374   EXPECT_FATAL_FAILURE(FAIL() << 0,
4375                        "0");
4376 }
4377
4378 // Tests using SUCCEED with a streamed message.
4379 TEST(AssertionWithMessageTest, SUCCEED) {
4380   SUCCEED() << "Success == " << 1;
4381 }
4382
4383 // Tests using ASSERT_TRUE with a streamed message.
4384 TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4385   ASSERT_TRUE(true) << "This should succeed.";
4386   ASSERT_TRUE(true) << true;
4387   EXPECT_FATAL_FAILURE(
4388       {  // NOLINT
4389         ASSERT_TRUE(false) << static_cast<const char*>(nullptr)
4390                            << static_cast<char*>(nullptr);
4391       },
4392       "(null)(null)");
4393 }
4394
4395 #if GTEST_OS_WINDOWS
4396 // Tests using wide strings in assertion messages.
4397 TEST(AssertionWithMessageTest, WideStringMessage) {
4398   EXPECT_NONFATAL_FAILURE({  // NOLINT
4399     EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4400   }, "This failure is expected.");
4401   EXPECT_FATAL_FAILURE({  // NOLINT
4402     ASSERT_EQ(1, 2) << "This failure is "
4403                     << L"expected too.\x8120";
4404   }, "This failure is expected too.");
4405 }
4406 #endif  // GTEST_OS_WINDOWS
4407
4408 // Tests EXPECT_TRUE.
4409 TEST(ExpectTest, EXPECT_TRUE) {
4410   EXPECT_TRUE(true) << "Intentional success";
4411   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4412                           "Intentional failure #1.");
4413   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4414                           "Intentional failure #2.");
4415   EXPECT_TRUE(2 > 1);  // NOLINT
4416   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4417                           "Value of: 2 < 1\n"
4418                           "  Actual: false\n"
4419                           "Expected: true");
4420   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4421                           "2 > 3");
4422 }
4423
4424 // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4425 TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4426   EXPECT_TRUE(ResultIsEven(2));
4427   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4428                           "Value of: ResultIsEven(3)\n"
4429                           "  Actual: false (3 is odd)\n"
4430                           "Expected: true");
4431   EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4432   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4433                           "Value of: ResultIsEvenNoExplanation(3)\n"
4434                           "  Actual: false (3 is odd)\n"
4435                           "Expected: true");
4436 }
4437
4438 // Tests EXPECT_FALSE with a streamed message.
4439 TEST(ExpectTest, EXPECT_FALSE) {
4440   EXPECT_FALSE(2 < 1);  // NOLINT
4441   EXPECT_FALSE(false) << "Intentional success";
4442   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4443                           "Intentional failure #1.");
4444   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4445                           "Intentional failure #2.");
4446   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4447                           "Value of: 2 > 1\n"
4448                           "  Actual: true\n"
4449                           "Expected: false");
4450   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4451                           "2 < 3");
4452 }
4453
4454 // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4455 TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4456   EXPECT_FALSE(ResultIsEven(3));
4457   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4458                           "Value of: ResultIsEven(2)\n"
4459                           "  Actual: true (2 is even)\n"
4460                           "Expected: false");
4461   EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4462   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4463                           "Value of: ResultIsEvenNoExplanation(2)\n"
4464                           "  Actual: true\n"
4465                           "Expected: false");
4466 }
4467
4468 #ifdef __BORLANDC__
4469 // Restores warnings after previous "#pragma option push" suppressed them
4470 # pragma option pop
4471 #endif
4472
4473 // Tests EXPECT_EQ.
4474 TEST(ExpectTest, EXPECT_EQ) {
4475   EXPECT_EQ(5, 2 + 3);
4476   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4477                           "Expected equality of these values:\n"
4478                           "  5\n"
4479                           "  2*3\n"
4480                           "    Which is: 6");
4481   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4482                           "2 - 3");
4483 }
4484
4485 // Tests using EXPECT_EQ on double values.  The purpose is to make
4486 // sure that the specialization we did for integer and anonymous enums
4487 // isn't used for double arguments.
4488 TEST(ExpectTest, EXPECT_EQ_Double) {
4489   // A success.
4490   EXPECT_EQ(5.6, 5.6);
4491
4492   // A failure.
4493   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4494                           "5.1");
4495 }
4496
4497 // Tests EXPECT_EQ(NULL, pointer).
4498 TEST(ExpectTest, EXPECT_EQ_NULL) {
4499   // A success.
4500   const char* p = nullptr;
4501   EXPECT_EQ(nullptr, p);
4502
4503   // A failure.
4504   int n = 0;
4505   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), "  &n\n    Which is:");
4506 }
4507
4508 // Tests EXPECT_EQ(0, non_pointer).  Since the literal 0 can be
4509 // treated as a null pointer by the compiler, we need to make sure
4510 // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4511 // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4512 TEST(ExpectTest, EXPECT_EQ_0) {
4513   int n = 0;
4514
4515   // A success.
4516   EXPECT_EQ(0, n);
4517
4518   // A failure.
4519   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4520                           "  0\n  5.6");
4521 }
4522
4523 // Tests EXPECT_NE.
4524 TEST(ExpectTest, EXPECT_NE) {
4525   EXPECT_NE(6, 7);
4526
4527   EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4528                           "Expected: ('a') != ('a'), "
4529                           "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4530   EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4531                           "2");
4532   char* const p0 = nullptr;
4533   EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4534                           "p0");
4535   // Only way to get the Nokia compiler to compile the cast
4536   // is to have a separate void* variable first. Putting
4537   // the two casts on the same line doesn't work, neither does
4538   // a direct C-style to char*.
4539   void* pv1 = (void*)0x1234;  // NOLINT
4540   char* const p1 = reinterpret_cast<char*>(pv1);
4541   EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4542                           "p1");
4543 }
4544
4545 // Tests EXPECT_LE.
4546 TEST(ExpectTest, EXPECT_LE) {
4547   EXPECT_LE(2, 3);
4548   EXPECT_LE(2, 2);
4549   EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4550                           "Expected: (2) <= (0), actual: 2 vs 0");
4551   EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4552                           "(1.1) <= (0.9)");
4553 }
4554
4555 // Tests EXPECT_LT.
4556 TEST(ExpectTest, EXPECT_LT) {
4557   EXPECT_LT(2, 3);
4558   EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4559                           "Expected: (2) < (2), actual: 2 vs 2");
4560   EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4561                           "(2) < (1)");
4562 }
4563
4564 // Tests EXPECT_GE.
4565 TEST(ExpectTest, EXPECT_GE) {
4566   EXPECT_GE(2, 1);
4567   EXPECT_GE(2, 2);
4568   EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4569                           "Expected: (2) >= (3), actual: 2 vs 3");
4570   EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4571                           "(0.9) >= (1.1)");
4572 }
4573
4574 // Tests EXPECT_GT.
4575 TEST(ExpectTest, EXPECT_GT) {
4576   EXPECT_GT(2, 1);
4577   EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4578                           "Expected: (2) > (2), actual: 2 vs 2");
4579   EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4580                           "(2) > (3)");
4581 }
4582
4583 #if GTEST_HAS_EXCEPTIONS
4584
4585 // Tests EXPECT_THROW.
4586 TEST(ExpectTest, EXPECT_THROW) {
4587   EXPECT_THROW(ThrowAnInteger(), int);
4588   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4589                           "Expected: ThrowAnInteger() throws an exception of "
4590                           "type bool.\n  Actual: it throws a different type.");
4591   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"),
4592                                        std::logic_error),
4593                           "Expected: ThrowRuntimeError(\"A description\") "
4594                           "throws an exception of type std::logic_error.\n  "
4595                           "Actual: it throws " ERROR_DESC " "
4596                           "with description \"A description\".");
4597   EXPECT_NONFATAL_FAILURE(
4598       EXPECT_THROW(ThrowNothing(), bool),
4599       "Expected: ThrowNothing() throws an exception of type bool.\n"
4600       "  Actual: it throws nothing.");
4601 }
4602
4603 // Tests EXPECT_NO_THROW.
4604 TEST(ExpectTest, EXPECT_NO_THROW) {
4605   EXPECT_NO_THROW(ThrowNothing());
4606   EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4607                           "Expected: ThrowAnInteger() doesn't throw an "
4608                           "exception.\n  Actual: it throws.");
4609   EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
4610                           "Expected: ThrowRuntimeError(\"A description\") "
4611                           "doesn't throw an exception.\n  "
4612                           "Actual: it throws " ERROR_DESC " "
4613                           "with description \"A description\".");
4614 }
4615
4616 // Tests EXPECT_ANY_THROW.
4617 TEST(ExpectTest, EXPECT_ANY_THROW) {
4618   EXPECT_ANY_THROW(ThrowAnInteger());
4619   EXPECT_NONFATAL_FAILURE(
4620       EXPECT_ANY_THROW(ThrowNothing()),
4621       "Expected: ThrowNothing() throws an exception.\n"
4622       "  Actual: it doesn't.");
4623 }
4624
4625 #endif  // GTEST_HAS_EXCEPTIONS
4626
4627 // Make sure we deal with the precedence of <<.
4628 TEST(ExpectTest, ExpectPrecedence) {
4629   EXPECT_EQ(1 < 2, true);
4630   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4631                           "  true && false\n    Which is: false");
4632 }
4633
4634
4635 // Tests the StreamableToString() function.
4636
4637 // Tests using StreamableToString() on a scalar.
4638 TEST(StreamableToStringTest, Scalar) {
4639   EXPECT_STREQ("5", StreamableToString(5).c_str());
4640 }
4641
4642 // Tests using StreamableToString() on a non-char pointer.
4643 TEST(StreamableToStringTest, Pointer) {
4644   int n = 0;
4645   int* p = &n;
4646   EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4647 }
4648
4649 // Tests using StreamableToString() on a NULL non-char pointer.
4650 TEST(StreamableToStringTest, NullPointer) {
4651   int* p = nullptr;
4652   EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4653 }
4654
4655 // Tests using StreamableToString() on a C string.
4656 TEST(StreamableToStringTest, CString) {
4657   EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4658 }
4659
4660 // Tests using StreamableToString() on a NULL C string.
4661 TEST(StreamableToStringTest, NullCString) {
4662   char* p = nullptr;
4663   EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4664 }
4665
4666 // Tests using streamable values as assertion messages.
4667
4668 // Tests using std::string as an assertion message.
4669 TEST(StreamableTest, string) {
4670   static const std::string str(
4671       "This failure message is a std::string, and is expected.");
4672   EXPECT_FATAL_FAILURE(FAIL() << str,
4673                        str.c_str());
4674 }
4675
4676 // Tests that we can output strings containing embedded NULs.
4677 // Limited to Linux because we can only do this with std::string's.
4678 TEST(StreamableTest, stringWithEmbeddedNUL) {
4679   static const char char_array_with_nul[] =
4680       "Here's a NUL\0 and some more string";
4681   static const std::string string_with_nul(char_array_with_nul,
4682                                            sizeof(char_array_with_nul)
4683                                            - 1);  // drops the trailing NUL
4684   EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4685                        "Here's a NUL\\0 and some more string");
4686 }
4687
4688 // Tests that we can output a NUL char.
4689 TEST(StreamableTest, NULChar) {
4690   EXPECT_FATAL_FAILURE({  // NOLINT
4691     FAIL() << "A NUL" << '\0' << " and some more string";
4692   }, "A NUL\\0 and some more string");
4693 }
4694
4695 // Tests using int as an assertion message.
4696 TEST(StreamableTest, int) {
4697   EXPECT_FATAL_FAILURE(FAIL() << 900913,
4698                        "900913");
4699 }
4700
4701 // Tests using NULL char pointer as an assertion message.
4702 //
4703 // In MSVC, streaming a NULL char * causes access violation.  Google Test
4704 // implemented a workaround (substituting "(null)" for NULL).  This
4705 // tests whether the workaround works.
4706 TEST(StreamableTest, NullCharPtr) {
4707   EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)");
4708 }
4709
4710 // Tests that basic IO manipulators (endl, ends, and flush) can be
4711 // streamed to testing::Message.
4712 TEST(StreamableTest, BasicIoManip) {
4713   EXPECT_FATAL_FAILURE({  // NOLINT
4714     FAIL() << "Line 1." << std::endl
4715            << "A NUL char " << std::ends << std::flush << " in line 2.";
4716   }, "Line 1.\nA NUL char \\0 in line 2.");
4717 }
4718
4719 // Tests the macros that haven't been covered so far.
4720
4721 void AddFailureHelper(bool* aborted) {
4722   *aborted = true;
4723   ADD_FAILURE() << "Intentional failure.";
4724   *aborted = false;
4725 }
4726
4727 // Tests ADD_FAILURE.
4728 TEST(MacroTest, ADD_FAILURE) {
4729   bool aborted = true;
4730   EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4731                           "Intentional failure.");
4732   EXPECT_FALSE(aborted);
4733 }
4734
4735 // Tests ADD_FAILURE_AT.
4736 TEST(MacroTest, ADD_FAILURE_AT) {
4737   // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4738   // the failure message contains the user-streamed part.
4739   EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4740
4741   // Verifies that the user-streamed part is optional.
4742   EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4743
4744   // Unfortunately, we cannot verify that the failure message contains
4745   // the right file path and line number the same way, as
4746   // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4747   // line number.  Instead, we do that in googletest-output-test_.cc.
4748 }
4749
4750 // Tests FAIL.
4751 TEST(MacroTest, FAIL) {
4752   EXPECT_FATAL_FAILURE(FAIL(),
4753                        "Failed");
4754   EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4755                        "Intentional failure.");
4756 }
4757
4758 // Tests GTEST_FAIL_AT.
4759 TEST(MacroTest, GTEST_FAIL_AT) {
4760   // Verifies that GTEST_FAIL_AT does generate a fatal failure and
4761   // the failure message contains the user-streamed part.
4762   EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4763
4764   // Verifies that the user-streamed part is optional.
4765   EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed");
4766
4767   // See the ADD_FAIL_AT test above to see how we test that the failure message
4768   // contains the right filename and line number -- the same applies here.
4769 }
4770
4771 // Tests SUCCEED
4772 TEST(MacroTest, SUCCEED) {
4773   SUCCEED();
4774   SUCCEED() << "Explicit success.";
4775 }
4776
4777 // Tests for EXPECT_EQ() and ASSERT_EQ().
4778 //
4779 // These tests fail *intentionally*, s.t. the failure messages can be
4780 // generated and tested.
4781 //
4782 // We have different tests for different argument types.
4783
4784 // Tests using bool values in {EXPECT|ASSERT}_EQ.
4785 TEST(EqAssertionTest, Bool) {
4786   EXPECT_EQ(true,  true);
4787   EXPECT_FATAL_FAILURE({
4788       bool false_value = false;
4789       ASSERT_EQ(false_value, true);
4790     }, "  false_value\n    Which is: false\n  true");
4791 }
4792
4793 // Tests using int values in {EXPECT|ASSERT}_EQ.
4794 TEST(EqAssertionTest, Int) {
4795   ASSERT_EQ(32, 32);
4796   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4797                           "  32\n  33");
4798 }
4799
4800 // Tests using time_t values in {EXPECT|ASSERT}_EQ.
4801 TEST(EqAssertionTest, Time_T) {
4802   EXPECT_EQ(static_cast<time_t>(0),
4803             static_cast<time_t>(0));
4804   EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4805                                  static_cast<time_t>(1234)),
4806                        "1234");
4807 }
4808
4809 // Tests using char values in {EXPECT|ASSERT}_EQ.
4810 TEST(EqAssertionTest, Char) {
4811   ASSERT_EQ('z', 'z');
4812   const char ch = 'b';
4813   EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4814                           "  ch\n    Which is: 'b'");
4815   EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4816                           "  ch\n    Which is: 'b'");
4817 }
4818
4819 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4820 TEST(EqAssertionTest, WideChar) {
4821   EXPECT_EQ(L'b', L'b');
4822
4823   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4824                           "Expected equality of these values:\n"
4825                           "  L'\0'\n"
4826                           "    Which is: L'\0' (0, 0x0)\n"
4827                           "  L'x'\n"
4828                           "    Which is: L'x' (120, 0x78)");
4829
4830   static wchar_t wchar;
4831   wchar = L'b';
4832   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4833                           "wchar");
4834   wchar = 0x8119;
4835   EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
4836                        "  wchar\n    Which is: L'");
4837 }
4838
4839 // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4840 TEST(EqAssertionTest, StdString) {
4841   // Compares a const char* to an std::string that has identical
4842   // content.
4843   ASSERT_EQ("Test", ::std::string("Test"));
4844
4845   // Compares two identical std::strings.
4846   static const ::std::string str1("A * in the middle");
4847   static const ::std::string str2(str1);
4848   EXPECT_EQ(str1, str2);
4849
4850   // Compares a const char* to an std::string that has different
4851   // content
4852   EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4853                           "\"test\"");
4854
4855   // Compares an std::string to a char* that has different content.
4856   char* const p1 = const_cast<char*>("foo");
4857   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4858                           "p1");
4859
4860   // Compares two std::strings that have different contents, one of
4861   // which having a NUL character in the middle.  This should fail.
4862   static ::std::string str3(str1);
4863   str3.at(2) = '\0';
4864   EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4865                        "  str3\n    Which is: \"A \\0 in the middle\"");
4866 }
4867
4868 #if GTEST_HAS_STD_WSTRING
4869
4870 // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4871 TEST(EqAssertionTest, StdWideString) {
4872   // Compares two identical std::wstrings.
4873   const ::std::wstring wstr1(L"A * in the middle");
4874   const ::std::wstring wstr2(wstr1);
4875   ASSERT_EQ(wstr1, wstr2);
4876
4877   // Compares an std::wstring to a const wchar_t* that has identical
4878   // content.
4879   const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4880   EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4881
4882   // Compares an std::wstring to a const wchar_t* that has different
4883   // content.
4884   const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4885   EXPECT_NONFATAL_FAILURE({  // NOLINT
4886     EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4887   }, "kTestX8120");
4888
4889   // Compares two std::wstrings that have different contents, one of
4890   // which having a NUL character in the middle.
4891   ::std::wstring wstr3(wstr1);
4892   wstr3.at(2) = L'\0';
4893   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4894                           "wstr3");
4895
4896   // Compares a wchar_t* to an std::wstring that has different
4897   // content.
4898   EXPECT_FATAL_FAILURE({  // NOLINT
4899     ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4900   }, "");
4901 }
4902
4903 #endif  // GTEST_HAS_STD_WSTRING
4904
4905 // Tests using char pointers in {EXPECT|ASSERT}_EQ.
4906 TEST(EqAssertionTest, CharPointer) {
4907   char* const p0 = nullptr;
4908   // Only way to get the Nokia compiler to compile the cast
4909   // is to have a separate void* variable first. Putting
4910   // the two casts on the same line doesn't work, neither does
4911   // a direct C-style to char*.
4912   void* pv1 = (void*)0x1234;  // NOLINT
4913   void* pv2 = (void*)0xABC0;  // NOLINT
4914   char* const p1 = reinterpret_cast<char*>(pv1);
4915   char* const p2 = reinterpret_cast<char*>(pv2);
4916   ASSERT_EQ(p1, p1);
4917
4918   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4919                           "  p2\n    Which is:");
4920   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4921                           "  p2\n    Which is:");
4922   EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4923                                  reinterpret_cast<char*>(0xABC0)),
4924                        "ABC0");
4925 }
4926
4927 // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4928 TEST(EqAssertionTest, WideCharPointer) {
4929   wchar_t* const p0 = nullptr;
4930   // Only way to get the Nokia compiler to compile the cast
4931   // is to have a separate void* variable first. Putting
4932   // the two casts on the same line doesn't work, neither does
4933   // a direct C-style to char*.
4934   void* pv1 = (void*)0x1234;  // NOLINT
4935   void* pv2 = (void*)0xABC0;  // NOLINT
4936   wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4937   wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4938   EXPECT_EQ(p0, p0);
4939
4940   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4941                           "  p2\n    Which is:");
4942   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4943                           "  p2\n    Which is:");
4944   void* pv3 = (void*)0x1234;  // NOLINT
4945   void* pv4 = (void*)0xABC0;  // NOLINT
4946   const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4947   const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4948   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4949                           "p4");
4950 }
4951
4952 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4953 TEST(EqAssertionTest, OtherPointer) {
4954   ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));
4955   EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),
4956                                  reinterpret_cast<const int*>(0x1234)),
4957                        "0x1234");
4958 }
4959
4960 // A class that supports binary comparison operators but not streaming.
4961 class UnprintableChar {
4962  public:
4963   explicit UnprintableChar(char ch) : char_(ch) {}
4964
4965   bool operator==(const UnprintableChar& rhs) const {
4966     return char_ == rhs.char_;
4967   }
4968   bool operator!=(const UnprintableChar& rhs) const {
4969     return char_ != rhs.char_;
4970   }
4971   bool operator<(const UnprintableChar& rhs) const {
4972     return char_ < rhs.char_;
4973   }
4974   bool operator<=(const UnprintableChar& rhs) const {
4975     return char_ <= rhs.char_;
4976   }
4977   bool operator>(const UnprintableChar& rhs) const {
4978     return char_ > rhs.char_;
4979   }
4980   bool operator>=(const UnprintableChar& rhs) const {
4981     return char_ >= rhs.char_;
4982   }
4983
4984  private:
4985   char char_;
4986 };
4987
4988 // Tests that ASSERT_EQ() and friends don't require the arguments to
4989 // be printable.
4990 TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4991   const UnprintableChar x('x'), y('y');
4992   ASSERT_EQ(x, x);
4993   EXPECT_NE(x, y);
4994   ASSERT_LT(x, y);
4995   EXPECT_LE(x, y);
4996   ASSERT_GT(y, x);
4997   EXPECT_GE(x, x);
4998
4999   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
5000   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
5001   EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
5002   EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
5003   EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
5004
5005   // Code tested by EXPECT_FATAL_FAILURE cannot reference local
5006   // variables, so we have to write UnprintableChar('x') instead of x.
5007 #ifndef __BORLANDC__
5008   // ICE's in C++Builder.
5009   EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
5010                        "1-byte object <78>");
5011   EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
5012                        "1-byte object <78>");
5013 #endif
5014   EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
5015                        "1-byte object <79>");
5016   EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
5017                        "1-byte object <78>");
5018   EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
5019                        "1-byte object <79>");
5020 }
5021
5022 // Tests the FRIEND_TEST macro.
5023
5024 // This class has a private member we want to test.  We will test it
5025 // both in a TEST and in a TEST_F.
5026 class Foo {
5027  public:
5028   Foo() {}
5029
5030  private:
5031   int Bar() const { return 1; }
5032
5033   // Declares the friend tests that can access the private member
5034   // Bar().
5035   FRIEND_TEST(FRIEND_TEST_Test, TEST);
5036   FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
5037 };
5038
5039 // Tests that the FRIEND_TEST declaration allows a TEST to access a
5040 // class's private members.  This should compile.
5041 TEST(FRIEND_TEST_Test, TEST) {
5042   ASSERT_EQ(1, Foo().Bar());
5043 }
5044
5045 // The fixture needed to test using FRIEND_TEST with TEST_F.
5046 class FRIEND_TEST_Test2 : public Test {
5047  protected:
5048   Foo foo;
5049 };
5050
5051 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
5052 // class's private members.  This should compile.
5053 TEST_F(FRIEND_TEST_Test2, TEST_F) {
5054   ASSERT_EQ(1, foo.Bar());
5055 }
5056
5057 // Tests the life cycle of Test objects.
5058
5059 // The test fixture for testing the life cycle of Test objects.
5060 //
5061 // This class counts the number of live test objects that uses this
5062 // fixture.
5063 class TestLifeCycleTest : public Test {
5064  protected:
5065   // Constructor.  Increments the number of test objects that uses
5066   // this fixture.
5067   TestLifeCycleTest() { count_++; }
5068
5069   // Destructor.  Decrements the number of test objects that uses this
5070   // fixture.
5071   ~TestLifeCycleTest() override { count_--; }
5072
5073   // Returns the number of live test objects that uses this fixture.
5074   int count() const { return count_; }
5075
5076  private:
5077   static int count_;
5078 };
5079
5080 int TestLifeCycleTest::count_ = 0;
5081
5082 // Tests the life cycle of test objects.
5083 TEST_F(TestLifeCycleTest, Test1) {
5084   // There should be only one test object in this test case that's
5085   // currently alive.
5086   ASSERT_EQ(1, count());
5087 }
5088
5089 // Tests the life cycle of test objects.
5090 TEST_F(TestLifeCycleTest, Test2) {
5091   // After Test1 is done and Test2 is started, there should still be
5092   // only one live test object, as the object for Test1 should've been
5093   // deleted.
5094   ASSERT_EQ(1, count());
5095 }
5096
5097 }  // namespace
5098
5099 // Tests that the copy constructor works when it is NOT optimized away by
5100 // the compiler.
5101 TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5102   // Checks that the copy constructor doesn't try to dereference NULL pointers
5103   // in the source object.
5104   AssertionResult r1 = AssertionSuccess();
5105   AssertionResult r2 = r1;
5106   // The following line is added to prevent the compiler from optimizing
5107   // away the constructor call.
5108   r1 << "abc";
5109
5110   AssertionResult r3 = r1;
5111   EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
5112   EXPECT_STREQ("abc", r1.message());
5113 }
5114
5115 // Tests that AssertionSuccess and AssertionFailure construct
5116 // AssertionResult objects as expected.
5117 TEST(AssertionResultTest, ConstructionWorks) {
5118   AssertionResult r1 = AssertionSuccess();
5119   EXPECT_TRUE(r1);
5120   EXPECT_STREQ("", r1.message());
5121
5122   AssertionResult r2 = AssertionSuccess() << "abc";
5123   EXPECT_TRUE(r2);
5124   EXPECT_STREQ("abc", r2.message());
5125
5126   AssertionResult r3 = AssertionFailure();
5127   EXPECT_FALSE(r3);
5128   EXPECT_STREQ("", r3.message());
5129
5130   AssertionResult r4 = AssertionFailure() << "def";
5131   EXPECT_FALSE(r4);
5132   EXPECT_STREQ("def", r4.message());
5133
5134   AssertionResult r5 = AssertionFailure(Message() << "ghi");
5135   EXPECT_FALSE(r5);
5136   EXPECT_STREQ("ghi", r5.message());
5137 }
5138
5139 // Tests that the negation flips the predicate result but keeps the message.
5140 TEST(AssertionResultTest, NegationWorks) {
5141   AssertionResult r1 = AssertionSuccess() << "abc";
5142   EXPECT_FALSE(!r1);
5143   EXPECT_STREQ("abc", (!r1).message());
5144
5145   AssertionResult r2 = AssertionFailure() << "def";
5146   EXPECT_TRUE(!r2);
5147   EXPECT_STREQ("def", (!r2).message());
5148 }
5149
5150 TEST(AssertionResultTest, StreamingWorks) {
5151   AssertionResult r = AssertionSuccess();
5152   r << "abc" << 'd' << 0 << true;
5153   EXPECT_STREQ("abcd0true", r.message());
5154 }
5155
5156 TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5157   AssertionResult r = AssertionSuccess();
5158   r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5159   EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5160 }
5161
5162 // The next test uses explicit conversion operators
5163
5164 TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5165   struct ExplicitlyConvertibleToBool {
5166     explicit operator bool() const { return value; }
5167     bool value;
5168   };
5169   ExplicitlyConvertibleToBool v1 = {false};
5170   ExplicitlyConvertibleToBool v2 = {true};
5171   EXPECT_FALSE(v1);
5172   EXPECT_TRUE(v2);
5173 }
5174
5175 struct ConvertibleToAssertionResult {
5176   operator AssertionResult() const { return AssertionResult(true); }
5177 };
5178
5179 TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5180   ConvertibleToAssertionResult obj;
5181   EXPECT_TRUE(obj);
5182 }
5183
5184 // Tests streaming a user type whose definition and operator << are
5185 // both in the global namespace.
5186 class Base {
5187  public:
5188   explicit Base(int an_x) : x_(an_x) {}
5189   int x() const { return x_; }
5190  private:
5191   int x_;
5192 };
5193 std::ostream& operator<<(std::ostream& os,
5194                          const Base& val) {
5195   return os << val.x();
5196 }
5197 std::ostream& operator<<(std::ostream& os,
5198                          const Base* pointer) {
5199   return os << "(" << pointer->x() << ")";
5200 }
5201
5202 TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5203   Message msg;
5204   Base a(1);
5205
5206   msg << a << &a;  // Uses ::operator<<.
5207   EXPECT_STREQ("1(1)", msg.GetString().c_str());
5208 }
5209
5210 // Tests streaming a user type whose definition and operator<< are
5211 // both in an unnamed namespace.
5212 namespace {
5213 class MyTypeInUnnamedNameSpace : public Base {
5214  public:
5215   explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
5216 };
5217 std::ostream& operator<<(std::ostream& os,
5218                          const MyTypeInUnnamedNameSpace& val) {
5219   return os << val.x();
5220 }
5221 std::ostream& operator<<(std::ostream& os,
5222                          const MyTypeInUnnamedNameSpace* pointer) {
5223   return os << "(" << pointer->x() << ")";
5224 }
5225 }  // namespace
5226
5227 TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5228   Message msg;
5229   MyTypeInUnnamedNameSpace a(1);
5230
5231   msg << a << &a;  // Uses <unnamed_namespace>::operator<<.
5232   EXPECT_STREQ("1(1)", msg.GetString().c_str());
5233 }
5234
5235 // Tests streaming a user type whose definition and operator<< are
5236 // both in a user namespace.
5237 namespace namespace1 {
5238 class MyTypeInNameSpace1 : public Base {
5239  public:
5240   explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
5241 };
5242 std::ostream& operator<<(std::ostream& os,
5243                          const MyTypeInNameSpace1& val) {
5244   return os << val.x();
5245 }
5246 std::ostream& operator<<(std::ostream& os,
5247                          const MyTypeInNameSpace1* pointer) {
5248   return os << "(" << pointer->x() << ")";
5249 }
5250 }  // namespace namespace1
5251
5252 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5253   Message msg;
5254   namespace1::MyTypeInNameSpace1 a(1);
5255
5256   msg << a << &a;  // Uses namespace1::operator<<.
5257   EXPECT_STREQ("1(1)", msg.GetString().c_str());
5258 }
5259
5260 // Tests streaming a user type whose definition is in a user namespace
5261 // but whose operator<< is in the global namespace.
5262 namespace namespace2 {
5263 class MyTypeInNameSpace2 : public ::Base {
5264  public:
5265   explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
5266 };
5267 }  // namespace namespace2
5268 std::ostream& operator<<(std::ostream& os,
5269                          const namespace2::MyTypeInNameSpace2& val) {
5270   return os << val.x();
5271 }
5272 std::ostream& operator<<(std::ostream& os,
5273                          const namespace2::MyTypeInNameSpace2* pointer) {
5274   return os << "(" << pointer->x() << ")";
5275 }
5276
5277 TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5278   Message msg;
5279   namespace2::MyTypeInNameSpace2 a(1);
5280
5281   msg << a << &a;  // Uses ::operator<<.
5282   EXPECT_STREQ("1(1)", msg.GetString().c_str());
5283 }
5284
5285 // Tests streaming NULL pointers to testing::Message.
5286 TEST(MessageTest, NullPointers) {
5287   Message msg;
5288   char* const p1 = nullptr;
5289   unsigned char* const p2 = nullptr;
5290   int* p3 = nullptr;
5291   double* p4 = nullptr;
5292   bool* p5 = nullptr;
5293   Message* p6 = nullptr;
5294
5295   msg << p1 << p2 << p3 << p4 << p5 << p6;
5296   ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5297                msg.GetString().c_str());
5298 }
5299
5300 // Tests streaming wide strings to testing::Message.
5301 TEST(MessageTest, WideStrings) {
5302   // Streams a NULL of type const wchar_t*.
5303   const wchar_t* const_wstr = nullptr;
5304   EXPECT_STREQ("(null)",
5305                (Message() << const_wstr).GetString().c_str());
5306
5307   // Streams a NULL of type wchar_t*.
5308   wchar_t* wstr = nullptr;
5309   EXPECT_STREQ("(null)",
5310                (Message() << wstr).GetString().c_str());
5311
5312   // Streams a non-NULL of type const wchar_t*.
5313   const_wstr = L"abc\x8119";
5314   EXPECT_STREQ("abc\xe8\x84\x99",
5315                (Message() << const_wstr).GetString().c_str());
5316
5317   // Streams a non-NULL of type wchar_t*.
5318   wstr = const_cast<wchar_t*>(const_wstr);
5319   EXPECT_STREQ("abc\xe8\x84\x99",
5320                (Message() << wstr).GetString().c_str());
5321 }
5322
5323
5324 // This line tests that we can define tests in the testing namespace.
5325 namespace testing {
5326
5327 // Tests the TestInfo class.
5328
5329 class TestInfoTest : public Test {
5330  protected:
5331   static const TestInfo* GetTestInfo(const char* test_name) {
5332     const TestSuite* const test_suite =
5333         GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr);
5334
5335     for (int i = 0; i < test_suite->total_test_count(); ++i) {
5336       const TestInfo* const test_info = test_suite->GetTestInfo(i);
5337       if (strcmp(test_name, test_info->name()) == 0)
5338         return test_info;
5339     }
5340     return nullptr;
5341   }
5342
5343   static const TestResult* GetTestResult(
5344       const TestInfo* test_info) {
5345     return test_info->result();
5346   }
5347 };
5348
5349 // Tests TestInfo::test_case_name() and TestInfo::name().
5350 TEST_F(TestInfoTest, Names) {
5351   const TestInfo* const test_info = GetTestInfo("Names");
5352
5353   ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
5354   ASSERT_STREQ("Names", test_info->name());
5355 }
5356
5357 // Tests TestInfo::result().
5358 TEST_F(TestInfoTest, result) {
5359   const TestInfo* const test_info = GetTestInfo("result");
5360
5361   // Initially, there is no TestPartResult for this test.
5362   ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5363
5364   // After the previous assertion, there is still none.
5365   ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5366 }
5367
5368 #define VERIFY_CODE_LOCATION \
5369   const int expected_line = __LINE__ - 1; \
5370   const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
5371   ASSERT_TRUE(test_info); \
5372   EXPECT_STREQ(__FILE__, test_info->file()); \
5373   EXPECT_EQ(expected_line, test_info->line())
5374
5375 TEST(CodeLocationForTEST, Verify) {
5376   VERIFY_CODE_LOCATION;
5377 }
5378
5379 class CodeLocationForTESTF : public Test {
5380 };
5381
5382 TEST_F(CodeLocationForTESTF, Verify) {
5383   VERIFY_CODE_LOCATION;
5384 }
5385
5386 class CodeLocationForTESTP : public TestWithParam<int> {
5387 };
5388
5389 TEST_P(CodeLocationForTESTP, Verify) {
5390   VERIFY_CODE_LOCATION;
5391 }
5392
5393 INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
5394
5395 template <typename T>
5396 class CodeLocationForTYPEDTEST : public Test {
5397 };
5398
5399 TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);
5400
5401 TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
5402   VERIFY_CODE_LOCATION;
5403 }
5404
5405 template <typename T>
5406 class CodeLocationForTYPEDTESTP : public Test {
5407 };
5408
5409 TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
5410
5411 TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
5412   VERIFY_CODE_LOCATION;
5413 }
5414
5415 REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
5416
5417 INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
5418
5419 #undef VERIFY_CODE_LOCATION
5420
5421 // Tests setting up and tearing down a test case.
5422 // Legacy API is deprecated but still available
5423 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5424 class SetUpTestCaseTest : public Test {
5425  protected:
5426   // This will be called once before the first test in this test case
5427   // is run.
5428   static void SetUpTestCase() {
5429     printf("Setting up the test case . . .\n");
5430
5431     // Initializes some shared resource.  In this simple example, we
5432     // just create a C string.  More complex stuff can be done if
5433     // desired.
5434     shared_resource_ = "123";
5435
5436     // Increments the number of test cases that have been set up.
5437     counter_++;
5438
5439     // SetUpTestCase() should be called only once.
5440     EXPECT_EQ(1, counter_);
5441   }
5442
5443   // This will be called once after the last test in this test case is
5444   // run.
5445   static void TearDownTestCase() {
5446     printf("Tearing down the test case . . .\n");
5447
5448     // Decrements the number of test cases that have been set up.
5449     counter_--;
5450
5451     // TearDownTestCase() should be called only once.
5452     EXPECT_EQ(0, counter_);
5453
5454     // Cleans up the shared resource.
5455     shared_resource_ = nullptr;
5456   }
5457
5458   // This will be called before each test in this test case.
5459   void SetUp() override {
5460     // SetUpTestCase() should be called only once, so counter_ should
5461     // always be 1.
5462     EXPECT_EQ(1, counter_);
5463   }
5464
5465   // Number of test cases that have been set up.
5466   static int counter_;
5467
5468   // Some resource to be shared by all tests in this test case.
5469   static const char* shared_resource_;
5470 };
5471
5472 int SetUpTestCaseTest::counter_ = 0;
5473 const char* SetUpTestCaseTest::shared_resource_ = nullptr;
5474
5475 // A test that uses the shared resource.
5476 TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
5477
5478 // Another test that uses the shared resource.
5479 TEST_F(SetUpTestCaseTest, Test2) {
5480   EXPECT_STREQ("123", shared_resource_);
5481 }
5482 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5483
5484 // Tests SetupTestSuite/TearDown TestSuite
5485 class SetUpTestSuiteTest : public Test {
5486  protected:
5487   // This will be called once before the first test in this test case
5488   // is run.
5489   static void SetUpTestSuite() {
5490     printf("Setting up the test suite . . .\n");
5491
5492     // Initializes some shared resource.  In this simple example, we
5493     // just create a C string.  More complex stuff can be done if
5494     // desired.
5495     shared_resource_ = "123";
5496
5497     // Increments the number of test cases that have been set up.
5498     counter_++;
5499
5500     // SetUpTestSuite() should be called only once.
5501     EXPECT_EQ(1, counter_);
5502   }
5503
5504   // This will be called once after the last test in this test case is
5505   // run.
5506   static void TearDownTestSuite() {
5507     printf("Tearing down the test suite . . .\n");
5508
5509     // Decrements the number of test suites that have been set up.
5510     counter_--;
5511
5512     // TearDownTestSuite() should be called only once.
5513     EXPECT_EQ(0, counter_);
5514
5515     // Cleans up the shared resource.
5516     shared_resource_ = nullptr;
5517   }
5518
5519   // This will be called before each test in this test case.
5520   void SetUp() override {
5521     // SetUpTestSuite() should be called only once, so counter_ should
5522     // always be 1.
5523     EXPECT_EQ(1, counter_);
5524   }
5525
5526   // Number of test suites that have been set up.
5527   static int counter_;
5528
5529   // Some resource to be shared by all tests in this test case.
5530   static const char* shared_resource_;
5531 };
5532
5533 int SetUpTestSuiteTest::counter_ = 0;
5534 const char* SetUpTestSuiteTest::shared_resource_ = nullptr;
5535
5536 // A test that uses the shared resource.
5537 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) {
5538   EXPECT_STRNE(nullptr, shared_resource_);
5539 }
5540
5541 // Another test that uses the shared resource.
5542 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
5543   EXPECT_STREQ("123", shared_resource_);
5544 }
5545
5546 // The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.
5547
5548 // The Flags struct stores a copy of all Google Test flags.
5549 struct Flags {
5550   // Constructs a Flags struct where each flag has its default value.
5551   Flags()
5552       : also_run_disabled_tests(false),
5553         break_on_failure(false),
5554         catch_exceptions(false),
5555         death_test_use_fork(false),
5556         fail_fast(false),
5557         filter(""),
5558         list_tests(false),
5559         output(""),
5560         brief(false),
5561         print_time(true),
5562         random_seed(0),
5563         repeat(1),
5564         recreate_environments_when_repeating(true),
5565         shuffle(false),
5566         stack_trace_depth(kMaxStackTraceDepth),
5567         stream_result_to(""),
5568         throw_on_failure(false) {}
5569
5570   // Factory methods.
5571
5572   // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5573   // the given value.
5574   static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5575     Flags flags;
5576     flags.also_run_disabled_tests = also_run_disabled_tests;
5577     return flags;
5578   }
5579
5580   // Creates a Flags struct where the gtest_break_on_failure flag has
5581   // the given value.
5582   static Flags BreakOnFailure(bool break_on_failure) {
5583     Flags flags;
5584     flags.break_on_failure = break_on_failure;
5585     return flags;
5586   }
5587
5588   // Creates a Flags struct where the gtest_catch_exceptions flag has
5589   // the given value.
5590   static Flags CatchExceptions(bool catch_exceptions) {
5591     Flags flags;
5592     flags.catch_exceptions = catch_exceptions;
5593     return flags;
5594   }
5595
5596   // Creates a Flags struct where the gtest_death_test_use_fork flag has
5597   // the given value.
5598   static Flags DeathTestUseFork(bool death_test_use_fork) {
5599     Flags flags;
5600     flags.death_test_use_fork = death_test_use_fork;
5601     return flags;
5602   }
5603
5604   // Creates a Flags struct where the gtest_fail_fast flag has
5605   // the given value.
5606   static Flags FailFast(bool fail_fast) {
5607     Flags flags;
5608     flags.fail_fast = fail_fast;
5609     return flags;
5610   }
5611
5612   // Creates a Flags struct where the gtest_filter flag has the given
5613   // value.
5614   static Flags Filter(const char* filter) {
5615     Flags flags;
5616     flags.filter = filter;
5617     return flags;
5618   }
5619
5620   // Creates a Flags struct where the gtest_list_tests flag has the
5621   // given value.
5622   static Flags ListTests(bool list_tests) {
5623     Flags flags;
5624     flags.list_tests = list_tests;
5625     return flags;
5626   }
5627
5628   // Creates a Flags struct where the gtest_output flag has the given
5629   // value.
5630   static Flags Output(const char* output) {
5631     Flags flags;
5632     flags.output = output;
5633     return flags;
5634   }
5635
5636   // Creates a Flags struct where the gtest_brief flag has the given
5637   // value.
5638   static Flags Brief(bool brief) {
5639     Flags flags;
5640     flags.brief = brief;
5641     return flags;
5642   }
5643
5644   // Creates a Flags struct where the gtest_print_time flag has the given
5645   // value.
5646   static Flags PrintTime(bool print_time) {
5647     Flags flags;
5648     flags.print_time = print_time;
5649     return flags;
5650   }
5651
5652   // Creates a Flags struct where the gtest_random_seed flag has the given
5653   // value.
5654   static Flags RandomSeed(int32_t random_seed) {
5655     Flags flags;
5656     flags.random_seed = random_seed;
5657     return flags;
5658   }
5659
5660   // Creates a Flags struct where the gtest_repeat flag has the given
5661   // value.
5662   static Flags Repeat(int32_t repeat) {
5663     Flags flags;
5664     flags.repeat = repeat;
5665     return flags;
5666   }
5667
5668   // Creates a Flags struct where the gtest_recreate_environments_when_repeating
5669   // flag has the given value.
5670   static Flags RecreateEnvironmentsWhenRepeating(
5671       bool recreate_environments_when_repeating) {
5672     Flags flags;
5673     flags.recreate_environments_when_repeating =
5674         recreate_environments_when_repeating;
5675     return flags;
5676   }
5677
5678   // Creates a Flags struct where the gtest_shuffle flag has the given
5679   // value.
5680   static Flags Shuffle(bool shuffle) {
5681     Flags flags;
5682     flags.shuffle = shuffle;
5683     return flags;
5684   }
5685
5686   // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5687   // the given value.
5688   static Flags StackTraceDepth(int32_t stack_trace_depth) {
5689     Flags flags;
5690     flags.stack_trace_depth = stack_trace_depth;
5691     return flags;
5692   }
5693
5694   // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5695   // the given value.
5696   static Flags StreamResultTo(const char* stream_result_to) {
5697     Flags flags;
5698     flags.stream_result_to = stream_result_to;
5699     return flags;
5700   }
5701
5702   // Creates a Flags struct where the gtest_throw_on_failure flag has
5703   // the given value.
5704   static Flags ThrowOnFailure(bool throw_on_failure) {
5705     Flags flags;
5706     flags.throw_on_failure = throw_on_failure;
5707     return flags;
5708   }
5709
5710   // These fields store the flag values.
5711   bool also_run_disabled_tests;
5712   bool break_on_failure;
5713   bool catch_exceptions;
5714   bool death_test_use_fork;
5715   bool fail_fast;
5716   const char* filter;
5717   bool list_tests;
5718   const char* output;
5719   bool brief;
5720   bool print_time;
5721   int32_t random_seed;
5722   int32_t repeat;
5723   bool recreate_environments_when_repeating;
5724   bool shuffle;
5725   int32_t stack_trace_depth;
5726   const char* stream_result_to;
5727   bool throw_on_failure;
5728 };
5729
5730 // Fixture for testing ParseGoogleTestFlagsOnly().
5731 class ParseFlagsTest : public Test {
5732  protected:
5733   // Clears the flags before each test.
5734   void SetUp() override {
5735     GTEST_FLAG_SET(also_run_disabled_tests, false);
5736     GTEST_FLAG_SET(break_on_failure, false);
5737     GTEST_FLAG_SET(catch_exceptions, false);
5738     GTEST_FLAG_SET(death_test_use_fork, false);
5739     GTEST_FLAG_SET(fail_fast, false);
5740     GTEST_FLAG_SET(filter, "");
5741     GTEST_FLAG_SET(list_tests, false);
5742     GTEST_FLAG_SET(output, "");
5743     GTEST_FLAG_SET(brief, false);
5744     GTEST_FLAG_SET(print_time, true);
5745     GTEST_FLAG_SET(random_seed, 0);
5746     GTEST_FLAG_SET(repeat, 1);
5747     GTEST_FLAG_SET(recreate_environments_when_repeating, true);
5748     GTEST_FLAG_SET(shuffle, false);
5749     GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
5750     GTEST_FLAG_SET(stream_result_to, "");
5751     GTEST_FLAG_SET(throw_on_failure, false);
5752   }
5753
5754   // Asserts that two narrow or wide string arrays are equal.
5755   template <typename CharType>
5756   static void AssertStringArrayEq(int size1, CharType** array1, int size2,
5757                                   CharType** array2) {
5758     ASSERT_EQ(size1, size2) << " Array sizes different.";
5759
5760     for (int i = 0; i != size1; i++) {
5761       ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5762     }
5763   }
5764
5765   // Verifies that the flag values match the expected values.
5766   static void CheckFlags(const Flags& expected) {
5767     EXPECT_EQ(expected.also_run_disabled_tests,
5768               GTEST_FLAG_GET(also_run_disabled_tests));
5769     EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure));
5770     EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions));
5771     EXPECT_EQ(expected.death_test_use_fork,
5772               GTEST_FLAG_GET(death_test_use_fork));
5773     EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast));
5774     EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str());
5775     EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests));
5776     EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str());
5777     EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief));
5778     EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time));
5779     EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed));
5780     EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat));
5781     EXPECT_EQ(expected.recreate_environments_when_repeating,
5782               GTEST_FLAG_GET(recreate_environments_when_repeating));
5783     EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle));
5784     EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth));
5785     EXPECT_STREQ(expected.stream_result_to,
5786                  GTEST_FLAG_GET(stream_result_to).c_str());
5787     EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure));
5788   }
5789
5790   // Parses a command line (specified by argc1 and argv1), then
5791   // verifies that the flag values are expected and that the
5792   // recognized flags are removed from the command line.
5793   template <typename CharType>
5794   static void TestParsingFlags(int argc1, const CharType** argv1,
5795                                int argc2, const CharType** argv2,
5796                                const Flags& expected, bool should_print_help) {
5797     const bool saved_help_flag = ::testing::internal::g_help_flag;
5798     ::testing::internal::g_help_flag = false;
5799
5800 # if GTEST_HAS_STREAM_REDIRECTION
5801     CaptureStdout();
5802 # endif
5803
5804     // Parses the command line.
5805     internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5806
5807 # if GTEST_HAS_STREAM_REDIRECTION
5808     const std::string captured_stdout = GetCapturedStdout();
5809 # endif
5810
5811     // Verifies the flag values.
5812     CheckFlags(expected);
5813
5814     // Verifies that the recognized flags are removed from the command
5815     // line.
5816     AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5817
5818     // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5819     // help message for the flags it recognizes.
5820     EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5821
5822 # if GTEST_HAS_STREAM_REDIRECTION
5823     const char* const expected_help_fragment =
5824         "This program contains tests written using";
5825     if (should_print_help) {
5826       EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5827     } else {
5828       EXPECT_PRED_FORMAT2(IsNotSubstring,
5829                           expected_help_fragment, captured_stdout);
5830     }
5831 # endif  // GTEST_HAS_STREAM_REDIRECTION
5832
5833     ::testing::internal::g_help_flag = saved_help_flag;
5834   }
5835
5836   // This macro wraps TestParsingFlags s.t. the user doesn't need
5837   // to specify the array sizes.
5838
5839 # define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5840   TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5841                    sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5842                    expected, should_print_help)
5843 };
5844
5845 // Tests parsing an empty command line.
5846 TEST_F(ParseFlagsTest, Empty) {
5847   const char* argv[] = {nullptr};
5848
5849   const char* argv2[] = {nullptr};
5850
5851   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5852 }
5853
5854 // Tests parsing a command line that has no flag.
5855 TEST_F(ParseFlagsTest, NoFlag) {
5856   const char* argv[] = {"foo.exe", nullptr};
5857
5858   const char* argv2[] = {"foo.exe", nullptr};
5859
5860   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5861 }
5862
5863 // Tests parsing --gtest_fail_fast.
5864 TEST_F(ParseFlagsTest, FailFast) {
5865   const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
5866
5867   const char* argv2[] = {"foo.exe", nullptr};
5868
5869   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
5870 }
5871
5872 // Tests parsing a bad --gtest_filter flag.
5873 TEST_F(ParseFlagsTest, FilterBad) {
5874   const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
5875
5876   const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
5877
5878   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
5879 }
5880
5881 // Tests parsing an empty --gtest_filter flag.
5882 TEST_F(ParseFlagsTest, FilterEmpty) {
5883   const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
5884
5885   const char* argv2[] = {"foo.exe", nullptr};
5886
5887   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5888 }
5889
5890 // Tests parsing a non-empty --gtest_filter flag.
5891 TEST_F(ParseFlagsTest, FilterNonEmpty) {
5892   const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr};
5893
5894   const char* argv2[] = {"foo.exe", nullptr};
5895
5896   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5897 }
5898
5899 // Tests parsing --gtest_break_on_failure.
5900 TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {
5901   const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr};
5902
5903   const char* argv2[] = {"foo.exe", nullptr};
5904
5905   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5906 }
5907
5908 // Tests parsing --gtest_break_on_failure=0.
5909 TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {
5910   const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr};
5911
5912   const char* argv2[] = {"foo.exe", nullptr};
5913
5914   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5915 }
5916
5917 // Tests parsing --gtest_break_on_failure=f.
5918 TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {
5919   const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr};
5920
5921   const char* argv2[] = {"foo.exe", nullptr};
5922
5923   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5924 }
5925
5926 // Tests parsing --gtest_break_on_failure=F.
5927 TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {
5928   const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr};
5929
5930   const char* argv2[] = {"foo.exe", nullptr};
5931
5932   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5933 }
5934
5935 // Tests parsing a --gtest_break_on_failure flag that has a "true"
5936 // definition.
5937 TEST_F(ParseFlagsTest, BreakOnFailureTrue) {
5938   const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr};
5939
5940   const char* argv2[] = {"foo.exe", nullptr};
5941
5942   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5943 }
5944
5945 // Tests parsing --gtest_catch_exceptions.
5946 TEST_F(ParseFlagsTest, CatchExceptions) {
5947   const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr};
5948
5949   const char* argv2[] = {"foo.exe", nullptr};
5950
5951   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5952 }
5953
5954 // Tests parsing --gtest_death_test_use_fork.
5955 TEST_F(ParseFlagsTest, DeathTestUseFork) {
5956   const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr};
5957
5958   const char* argv2[] = {"foo.exe", nullptr};
5959
5960   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5961 }
5962
5963 // Tests having the same flag twice with different values.  The
5964 // expected behavior is that the one coming last takes precedence.
5965 TEST_F(ParseFlagsTest, DuplicatedFlags) {
5966   const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b",
5967                         nullptr};
5968
5969   const char* argv2[] = {"foo.exe", nullptr};
5970
5971   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5972 }
5973
5974 // Tests having an unrecognized flag on the command line.
5975 TEST_F(ParseFlagsTest, UnrecognizedFlag) {
5976   const char* argv[] = {"foo.exe", "--gtest_break_on_failure",
5977                         "bar",  // Unrecognized by Google Test.
5978                         "--gtest_filter=b", nullptr};
5979
5980   const char* argv2[] = {"foo.exe", "bar", nullptr};
5981
5982   Flags flags;
5983   flags.break_on_failure = true;
5984   flags.filter = "b";
5985   GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5986 }
5987
5988 // Tests having a --gtest_list_tests flag
5989 TEST_F(ParseFlagsTest, ListTestsFlag) {
5990   const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr};
5991
5992   const char* argv2[] = {"foo.exe", nullptr};
5993
5994   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5995 }
5996
5997 // Tests having a --gtest_list_tests flag with a "true" value
5998 TEST_F(ParseFlagsTest, ListTestsTrue) {
5999   const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr};
6000
6001   const char* argv2[] = {"foo.exe", nullptr};
6002
6003   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
6004 }
6005
6006 // Tests having a --gtest_list_tests flag with a "false" value
6007 TEST_F(ParseFlagsTest, ListTestsFalse) {
6008   const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr};
6009
6010   const char* argv2[] = {"foo.exe", nullptr};
6011
6012   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6013 }
6014
6015 // Tests parsing --gtest_list_tests=f.
6016 TEST_F(ParseFlagsTest, ListTestsFalse_f) {
6017   const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr};
6018
6019   const char* argv2[] = {"foo.exe", nullptr};
6020
6021   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6022 }
6023
6024 // Tests parsing --gtest_list_tests=F.
6025 TEST_F(ParseFlagsTest, ListTestsFalse_F) {
6026   const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr};
6027
6028   const char* argv2[] = {"foo.exe", nullptr};
6029
6030   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6031 }
6032
6033 // Tests parsing --gtest_output (invalid).
6034 TEST_F(ParseFlagsTest, OutputEmpty) {
6035   const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
6036
6037   const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
6038
6039   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
6040 }
6041
6042 // Tests parsing --gtest_output=xml
6043 TEST_F(ParseFlagsTest, OutputXml) {
6044   const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
6045
6046   const char* argv2[] = {"foo.exe", nullptr};
6047
6048   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
6049 }
6050
6051 // Tests parsing --gtest_output=xml:file
6052 TEST_F(ParseFlagsTest, OutputXmlFile) {
6053   const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr};
6054
6055   const char* argv2[] = {"foo.exe", nullptr};
6056
6057   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
6058 }
6059
6060 // Tests parsing --gtest_output=xml:directory/path/
6061 TEST_F(ParseFlagsTest, OutputXmlDirectory) {
6062   const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/",
6063                         nullptr};
6064
6065   const char* argv2[] = {"foo.exe", nullptr};
6066
6067   GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6068                             Flags::Output("xml:directory/path/"), false);
6069 }
6070
6071 // Tests having a --gtest_brief flag
6072 TEST_F(ParseFlagsTest, BriefFlag) {
6073   const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
6074
6075   const char* argv2[] = {"foo.exe", nullptr};
6076
6077   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
6078 }
6079
6080 // Tests having a --gtest_brief flag with a "true" value
6081 TEST_F(ParseFlagsTest, BriefFlagTrue) {
6082   const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
6083
6084   const char* argv2[] = {"foo.exe", nullptr};
6085
6086   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
6087 }
6088
6089 // Tests having a --gtest_brief flag with a "false" value
6090 TEST_F(ParseFlagsTest, BriefFlagFalse) {
6091   const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
6092
6093   const char* argv2[] = {"foo.exe", nullptr};
6094
6095   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
6096 }
6097
6098 // Tests having a --gtest_print_time flag
6099 TEST_F(ParseFlagsTest, PrintTimeFlag) {
6100   const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
6101
6102   const char* argv2[] = {"foo.exe", nullptr};
6103
6104   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6105 }
6106
6107 // Tests having a --gtest_print_time flag with a "true" value
6108 TEST_F(ParseFlagsTest, PrintTimeTrue) {
6109   const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr};
6110
6111   const char* argv2[] = {"foo.exe", nullptr};
6112
6113   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6114 }
6115
6116 // Tests having a --gtest_print_time flag with a "false" value
6117 TEST_F(ParseFlagsTest, PrintTimeFalse) {
6118   const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr};
6119
6120   const char* argv2[] = {"foo.exe", nullptr};
6121
6122   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6123 }
6124
6125 // Tests parsing --gtest_print_time=f.
6126 TEST_F(ParseFlagsTest, PrintTimeFalse_f) {
6127   const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr};
6128
6129   const char* argv2[] = {"foo.exe", nullptr};
6130
6131   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6132 }
6133
6134 // Tests parsing --gtest_print_time=F.
6135 TEST_F(ParseFlagsTest, PrintTimeFalse_F) {
6136   const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr};
6137
6138   const char* argv2[] = {"foo.exe", nullptr};
6139
6140   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6141 }
6142
6143 // Tests parsing --gtest_random_seed=number
6144 TEST_F(ParseFlagsTest, RandomSeed) {
6145   const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr};
6146
6147   const char* argv2[] = {"foo.exe", nullptr};
6148
6149   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6150 }
6151
6152 // Tests parsing --gtest_repeat=number
6153 TEST_F(ParseFlagsTest, Repeat) {
6154   const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr};
6155
6156   const char* argv2[] = {"foo.exe", nullptr};
6157
6158   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
6159 }
6160
6161 // Tests parsing --gtest_recreate_environments_when_repeating
6162 TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) {
6163   const char* argv[] = {
6164       "foo.exe",
6165       "--gtest_recreate_environments_when_repeating=0",
6166       nullptr,
6167   };
6168
6169   const char* argv2[] = {"foo.exe", nullptr};
6170
6171   GTEST_TEST_PARSING_FLAGS_(
6172       argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false);
6173 }
6174
6175 // Tests having a --gtest_also_run_disabled_tests flag
6176 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
6177   const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
6178
6179   const char* argv2[] = {"foo.exe", nullptr};
6180
6181   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
6182                             false);
6183 }
6184
6185 // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6186 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {
6187   const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1",
6188                         nullptr};
6189
6190   const char* argv2[] = {"foo.exe", nullptr};
6191
6192   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
6193                             false);
6194 }
6195
6196 // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6197 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {
6198   const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0",
6199                         nullptr};
6200
6201   const char* argv2[] = {"foo.exe", nullptr};
6202
6203   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false),
6204                             false);
6205 }
6206
6207 // Tests parsing --gtest_shuffle.
6208 TEST_F(ParseFlagsTest, ShuffleWithoutValue) {
6209   const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr};
6210
6211   const char* argv2[] = {"foo.exe", nullptr};
6212
6213   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6214 }
6215
6216 // Tests parsing --gtest_shuffle=0.
6217 TEST_F(ParseFlagsTest, ShuffleFalse_0) {
6218   const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr};
6219
6220   const char* argv2[] = {"foo.exe", nullptr};
6221
6222   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6223 }
6224
6225 // Tests parsing a --gtest_shuffle flag that has a "true" definition.
6226 TEST_F(ParseFlagsTest, ShuffleTrue) {
6227   const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr};
6228
6229   const char* argv2[] = {"foo.exe", nullptr};
6230
6231   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6232 }
6233
6234 // Tests parsing --gtest_stack_trace_depth=number.
6235 TEST_F(ParseFlagsTest, StackTraceDepth) {
6236   const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr};
6237
6238   const char* argv2[] = {"foo.exe", nullptr};
6239
6240   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6241 }
6242
6243 TEST_F(ParseFlagsTest, StreamResultTo) {
6244   const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234",
6245                         nullptr};
6246
6247   const char* argv2[] = {"foo.exe", nullptr};
6248
6249   GTEST_TEST_PARSING_FLAGS_(
6250       argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
6251 }
6252
6253 // Tests parsing --gtest_throw_on_failure.
6254 TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
6255   const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr};
6256
6257   const char* argv2[] = {"foo.exe", nullptr};
6258
6259   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6260 }
6261
6262 // Tests parsing --gtest_throw_on_failure=0.
6263 TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {
6264   const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr};
6265
6266   const char* argv2[] = {"foo.exe", nullptr};
6267
6268   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
6269 }
6270
6271 // Tests parsing a --gtest_throw_on_failure flag that has a "true"
6272 // definition.
6273 TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
6274   const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr};
6275
6276   const char* argv2[] = {"foo.exe", nullptr};
6277
6278   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6279 }
6280
6281 # if GTEST_OS_WINDOWS
6282 // Tests parsing wide strings.
6283 TEST_F(ParseFlagsTest, WideStrings) {
6284   const wchar_t* argv[] = {
6285     L"foo.exe",
6286     L"--gtest_filter=Foo*",
6287     L"--gtest_list_tests=1",
6288     L"--gtest_break_on_failure",
6289     L"--non_gtest_flag",
6290     NULL
6291   };
6292
6293   const wchar_t* argv2[] = {
6294     L"foo.exe",
6295     L"--non_gtest_flag",
6296     NULL
6297   };
6298
6299   Flags expected_flags;
6300   expected_flags.break_on_failure = true;
6301   expected_flags.filter = "Foo*";
6302   expected_flags.list_tests = true;
6303
6304   GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6305 }
6306 # endif  // GTEST_OS_WINDOWS
6307
6308 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6309 class FlagfileTest : public ParseFlagsTest {
6310  public:
6311   void SetUp() override {
6312     ParseFlagsTest::SetUp();
6313
6314     testdata_path_.Set(internal::FilePath(
6315         testing::TempDir() + internal::GetCurrentExecutableName().string() +
6316         "_flagfile_test"));
6317     testing::internal::posix::RmDir(testdata_path_.c_str());
6318     EXPECT_TRUE(testdata_path_.CreateFolder());
6319   }
6320
6321   void TearDown() override {
6322     testing::internal::posix::RmDir(testdata_path_.c_str());
6323     ParseFlagsTest::TearDown();
6324   }
6325
6326   internal::FilePath CreateFlagfile(const char* contents) {
6327     internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
6328         testdata_path_, internal::FilePath("unique"), "txt"));
6329     FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
6330     fprintf(f, "%s", contents);
6331     fclose(f);
6332     return file_path;
6333   }
6334
6335  private:
6336   internal::FilePath testdata_path_;
6337 };
6338
6339 // Tests an empty flagfile.
6340 TEST_F(FlagfileTest, Empty) {
6341   internal::FilePath flagfile_path(CreateFlagfile(""));
6342   std::string flagfile_flag =
6343       std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6344
6345   const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6346
6347   const char* argv2[] = {"foo.exe", nullptr};
6348
6349   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
6350 }
6351
6352 // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
6353 TEST_F(FlagfileTest, FilterNonEmpty) {
6354   internal::FilePath flagfile_path(CreateFlagfile(
6355       "--"  GTEST_FLAG_PREFIX_  "filter=abc"));
6356   std::string flagfile_flag =
6357       std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6358
6359   const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6360
6361   const char* argv2[] = {"foo.exe", nullptr};
6362
6363   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
6364 }
6365
6366 // Tests passing several flags via --gtest_flagfile.
6367 TEST_F(FlagfileTest, SeveralFlags) {
6368   internal::FilePath flagfile_path(CreateFlagfile(
6369       "--"  GTEST_FLAG_PREFIX_  "filter=abc\n"
6370       "--"  GTEST_FLAG_PREFIX_  "break_on_failure\n"
6371       "--"  GTEST_FLAG_PREFIX_  "list_tests"));
6372   std::string flagfile_flag =
6373       std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6374
6375   const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6376
6377   const char* argv2[] = {"foo.exe", nullptr};
6378
6379   Flags expected_flags;
6380   expected_flags.break_on_failure = true;
6381   expected_flags.filter = "abc";
6382   expected_flags.list_tests = true;
6383
6384   GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6385 }
6386 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
6387
6388 // Tests current_test_info() in UnitTest.
6389 class CurrentTestInfoTest : public Test {
6390  protected:
6391   // Tests that current_test_info() returns NULL before the first test in
6392   // the test case is run.
6393   static void SetUpTestSuite() {
6394     // There should be no tests running at this point.
6395     const TestInfo* test_info =
6396       UnitTest::GetInstance()->current_test_info();
6397     EXPECT_TRUE(test_info == nullptr)
6398         << "There should be no tests running at this point.";
6399   }
6400
6401   // Tests that current_test_info() returns NULL after the last test in
6402   // the test case has run.
6403   static void TearDownTestSuite() {
6404     const TestInfo* test_info =
6405       UnitTest::GetInstance()->current_test_info();
6406     EXPECT_TRUE(test_info == nullptr)
6407         << "There should be no tests running at this point.";
6408   }
6409 };
6410
6411 // Tests that current_test_info() returns TestInfo for currently running
6412 // test by checking the expected test name against the actual one.
6413 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
6414   const TestInfo* test_info =
6415     UnitTest::GetInstance()->current_test_info();
6416   ASSERT_TRUE(nullptr != test_info)
6417       << "There is a test running so we should have a valid TestInfo.";
6418   EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6419       << "Expected the name of the currently running test suite.";
6420   EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
6421       << "Expected the name of the currently running test.";
6422 }
6423
6424 // Tests that current_test_info() returns TestInfo for currently running
6425 // test by checking the expected test name against the actual one.  We
6426 // use this test to see that the TestInfo object actually changed from
6427 // the previous invocation.
6428 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
6429   const TestInfo* test_info =
6430     UnitTest::GetInstance()->current_test_info();
6431   ASSERT_TRUE(nullptr != test_info)
6432       << "There is a test running so we should have a valid TestInfo.";
6433   EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6434       << "Expected the name of the currently running test suite.";
6435   EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
6436       << "Expected the name of the currently running test.";
6437 }
6438
6439 }  // namespace testing
6440
6441
6442 // These two lines test that we can define tests in a namespace that
6443 // has the name "testing" and is nested in another namespace.
6444 namespace my_namespace {
6445 namespace testing {
6446
6447 // Makes sure that TEST knows to use ::testing::Test instead of
6448 // ::my_namespace::testing::Test.
6449 class Test {};
6450
6451 // Makes sure that an assertion knows to use ::testing::Message instead of
6452 // ::my_namespace::testing::Message.
6453 class Message {};
6454
6455 // Makes sure that an assertion knows to use
6456 // ::testing::AssertionResult instead of
6457 // ::my_namespace::testing::AssertionResult.
6458 class AssertionResult {};
6459
6460 // Tests that an assertion that should succeed works as expected.
6461 TEST(NestedTestingNamespaceTest, Success) {
6462   EXPECT_EQ(1, 1) << "This shouldn't fail.";
6463 }
6464
6465 // Tests that an assertion that should fail works as expected.
6466 TEST(NestedTestingNamespaceTest, Failure) {
6467   EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6468                        "This failure is expected.");
6469 }
6470
6471 }  // namespace testing
6472 }  // namespace my_namespace
6473
6474 // Tests that one can call superclass SetUp and TearDown methods--
6475 // that is, that they are not private.
6476 // No tests are based on this fixture; the test "passes" if it compiles
6477 // successfully.
6478 class ProtectedFixtureMethodsTest : public Test {
6479  protected:
6480   void SetUp() override { Test::SetUp(); }
6481   void TearDown() override { Test::TearDown(); }
6482 };
6483
6484 // StreamingAssertionsTest tests the streaming versions of a representative
6485 // sample of assertions.
6486 TEST(StreamingAssertionsTest, Unconditional) {
6487   SUCCEED() << "expected success";
6488   EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6489                           "expected failure");
6490   EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6491                        "expected failure");
6492 }
6493
6494 #ifdef __BORLANDC__
6495 // Silences warnings: "Condition is always true", "Unreachable code"
6496 # pragma option push -w-ccc -w-rch
6497 #endif
6498
6499 TEST(StreamingAssertionsTest, Truth) {
6500   EXPECT_TRUE(true) << "unexpected failure";
6501   ASSERT_TRUE(true) << "unexpected failure";
6502   EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6503                           "expected failure");
6504   EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6505                        "expected failure");
6506 }
6507
6508 TEST(StreamingAssertionsTest, Truth2) {
6509   EXPECT_FALSE(false) << "unexpected failure";
6510   ASSERT_FALSE(false) << "unexpected failure";
6511   EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6512                           "expected failure");
6513   EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6514                        "expected failure");
6515 }
6516
6517 #ifdef __BORLANDC__
6518 // Restores warnings after previous "#pragma option push" suppressed them
6519 # pragma option pop
6520 #endif
6521
6522 TEST(StreamingAssertionsTest, IntegerEquals) {
6523   EXPECT_EQ(1, 1) << "unexpected failure";
6524   ASSERT_EQ(1, 1) << "unexpected failure";
6525   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6526                           "expected failure");
6527   EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6528                        "expected failure");
6529 }
6530
6531 TEST(StreamingAssertionsTest, IntegerLessThan) {
6532   EXPECT_LT(1, 2) << "unexpected failure";
6533   ASSERT_LT(1, 2) << "unexpected failure";
6534   EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6535                           "expected failure");
6536   EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6537                        "expected failure");
6538 }
6539
6540 TEST(StreamingAssertionsTest, StringsEqual) {
6541   EXPECT_STREQ("foo", "foo") << "unexpected failure";
6542   ASSERT_STREQ("foo", "foo") << "unexpected failure";
6543   EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6544                           "expected failure");
6545   EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6546                        "expected failure");
6547 }
6548
6549 TEST(StreamingAssertionsTest, StringsNotEqual) {
6550   EXPECT_STRNE("foo", "bar") << "unexpected failure";
6551   ASSERT_STRNE("foo", "bar") << "unexpected failure";
6552   EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6553                           "expected failure");
6554   EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6555                        "expected failure");
6556 }
6557
6558 TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6559   EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6560   ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6561   EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6562                           "expected failure");
6563   EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6564                        "expected failure");
6565 }
6566
6567 TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6568   EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6569   ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6570   EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6571                           "expected failure");
6572   EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6573                        "expected failure");
6574 }
6575
6576 TEST(StreamingAssertionsTest, FloatingPointEquals) {
6577   EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6578   ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6579   EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6580                           "expected failure");
6581   EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6582                        "expected failure");
6583 }
6584
6585 #if GTEST_HAS_EXCEPTIONS
6586
6587 TEST(StreamingAssertionsTest, Throw) {
6588   EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6589   ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6590   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6591                           "expected failure", "expected failure");
6592   EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6593                        "expected failure", "expected failure");
6594 }
6595
6596 TEST(StreamingAssertionsTest, NoThrow) {
6597   EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6598   ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6599   EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6600                           "expected failure", "expected failure");
6601   EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6602                        "expected failure", "expected failure");
6603 }
6604
6605 TEST(StreamingAssertionsTest, AnyThrow) {
6606   EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6607   ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6608   EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
6609                           "expected failure", "expected failure");
6610   EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
6611                        "expected failure", "expected failure");
6612 }
6613
6614 #endif  // GTEST_HAS_EXCEPTIONS
6615
6616 // Tests that Google Test correctly decides whether to use colors in the output.
6617
6618 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6619   GTEST_FLAG_SET(color, "yes");
6620
6621   SetEnv("TERM", "xterm");  // TERM supports colors.
6622   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6623   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
6624
6625   SetEnv("TERM", "dumb");  // TERM doesn't support colors.
6626   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6627   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
6628 }
6629
6630 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6631   SetEnv("TERM", "dumb");  // TERM doesn't support colors.
6632
6633   GTEST_FLAG_SET(color, "True");
6634   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
6635
6636   GTEST_FLAG_SET(color, "t");
6637   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
6638
6639   GTEST_FLAG_SET(color, "1");
6640   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
6641 }
6642
6643 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6644   GTEST_FLAG_SET(color, "no");
6645
6646   SetEnv("TERM", "xterm");  // TERM supports colors.
6647   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6648   EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
6649
6650   SetEnv("TERM", "dumb");  // TERM doesn't support colors.
6651   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6652   EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
6653 }
6654
6655 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6656   SetEnv("TERM", "xterm");  // TERM supports colors.
6657
6658   GTEST_FLAG_SET(color, "F");
6659   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6660
6661   GTEST_FLAG_SET(color, "0");
6662   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6663
6664   GTEST_FLAG_SET(color, "unknown");
6665   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6666 }
6667
6668 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6669   GTEST_FLAG_SET(color, "auto");
6670
6671   SetEnv("TERM", "xterm");  // TERM supports colors.
6672   EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
6673   EXPECT_TRUE(ShouldUseColor(true));    // Stdout is a TTY.
6674 }
6675
6676 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6677   GTEST_FLAG_SET(color, "auto");
6678
6679 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
6680   // On Windows, we ignore the TERM variable as it's usually not set.
6681
6682   SetEnv("TERM", "dumb");
6683   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6684
6685   SetEnv("TERM", "");
6686   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6687
6688   SetEnv("TERM", "xterm");
6689   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6690 #else
6691   // On non-Windows platforms, we rely on TERM to determine if the
6692   // terminal supports colors.
6693
6694   SetEnv("TERM", "dumb");  // TERM doesn't support colors.
6695   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6696
6697   SetEnv("TERM", "emacs");  // TERM doesn't support colors.
6698   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6699
6700   SetEnv("TERM", "vt100");  // TERM doesn't support colors.
6701   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6702
6703   SetEnv("TERM", "xterm-mono");  // TERM doesn't support colors.
6704   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
6705
6706   SetEnv("TERM", "xterm");  // TERM supports colors.
6707   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6708
6709   SetEnv("TERM", "xterm-color");  // TERM supports colors.
6710   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6711
6712   SetEnv("TERM", "xterm-256color");  // TERM supports colors.
6713   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6714
6715   SetEnv("TERM", "screen");  // TERM supports colors.
6716   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6717
6718   SetEnv("TERM", "screen-256color");  // TERM supports colors.
6719   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6720
6721   SetEnv("TERM", "tmux");  // TERM supports colors.
6722   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6723
6724   SetEnv("TERM", "tmux-256color");  // TERM supports colors.
6725   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6726
6727   SetEnv("TERM", "rxvt-unicode");  // TERM supports colors.
6728   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6729
6730   SetEnv("TERM", "rxvt-unicode-256color");  // TERM supports colors.
6731   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6732
6733   SetEnv("TERM", "linux");  // TERM supports colors.
6734   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6735
6736   SetEnv("TERM", "cygwin");  // TERM supports colors.
6737   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
6738 #endif  // GTEST_OS_WINDOWS
6739 }
6740
6741 // Verifies that StaticAssertTypeEq works in a namespace scope.
6742
6743 static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6744 static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6745     StaticAssertTypeEq<const int, const int>();
6746
6747 // Verifies that StaticAssertTypeEq works in a class.
6748
6749 template <typename T>
6750 class StaticAssertTypeEqTestHelper {
6751  public:
6752   StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6753 };
6754
6755 TEST(StaticAssertTypeEqTest, WorksInClass) {
6756   StaticAssertTypeEqTestHelper<bool>();
6757 }
6758
6759 // Verifies that StaticAssertTypeEq works inside a function.
6760
6761 typedef int IntAlias;
6762
6763 TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6764   StaticAssertTypeEq<int, IntAlias>();
6765   StaticAssertTypeEq<int*, IntAlias*>();
6766 }
6767
6768 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6769   EXPECT_FALSE(HasNonfatalFailure());
6770 }
6771
6772 static void FailFatally() { FAIL(); }
6773
6774 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6775   FailFatally();
6776   const bool has_nonfatal_failure = HasNonfatalFailure();
6777   ClearCurrentTestPartResults();
6778   EXPECT_FALSE(has_nonfatal_failure);
6779 }
6780
6781 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6782   ADD_FAILURE();
6783   const bool has_nonfatal_failure = HasNonfatalFailure();
6784   ClearCurrentTestPartResults();
6785   EXPECT_TRUE(has_nonfatal_failure);
6786 }
6787
6788 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6789   FailFatally();
6790   ADD_FAILURE();
6791   const bool has_nonfatal_failure = HasNonfatalFailure();
6792   ClearCurrentTestPartResults();
6793   EXPECT_TRUE(has_nonfatal_failure);
6794 }
6795
6796 // A wrapper for calling HasNonfatalFailure outside of a test body.
6797 static bool HasNonfatalFailureHelper() {
6798   return testing::Test::HasNonfatalFailure();
6799 }
6800
6801 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6802   EXPECT_FALSE(HasNonfatalFailureHelper());
6803 }
6804
6805 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6806   ADD_FAILURE();
6807   const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6808   ClearCurrentTestPartResults();
6809   EXPECT_TRUE(has_nonfatal_failure);
6810 }
6811
6812 TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6813   EXPECT_FALSE(HasFailure());
6814 }
6815
6816 TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6817   FailFatally();
6818   const bool has_failure = HasFailure();
6819   ClearCurrentTestPartResults();
6820   EXPECT_TRUE(has_failure);
6821 }
6822
6823 TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6824   ADD_FAILURE();
6825   const bool has_failure = HasFailure();
6826   ClearCurrentTestPartResults();
6827   EXPECT_TRUE(has_failure);
6828 }
6829
6830 TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6831   FailFatally();
6832   ADD_FAILURE();
6833   const bool has_failure = HasFailure();
6834   ClearCurrentTestPartResults();
6835   EXPECT_TRUE(has_failure);
6836 }
6837
6838 // A wrapper for calling HasFailure outside of a test body.
6839 static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6840
6841 TEST(HasFailureTest, WorksOutsideOfTestBody) {
6842   EXPECT_FALSE(HasFailureHelper());
6843 }
6844
6845 TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6846   ADD_FAILURE();
6847   const bool has_failure = HasFailureHelper();
6848   ClearCurrentTestPartResults();
6849   EXPECT_TRUE(has_failure);
6850 }
6851
6852 class TestListener : public EmptyTestEventListener {
6853  public:
6854   TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
6855   TestListener(int* on_start_counter, bool* is_destroyed)
6856       : on_start_counter_(on_start_counter),
6857         is_destroyed_(is_destroyed) {}
6858
6859   ~TestListener() override {
6860     if (is_destroyed_)
6861       *is_destroyed_ = true;
6862   }
6863
6864  protected:
6865   void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6866     if (on_start_counter_ != nullptr) (*on_start_counter_)++;
6867   }
6868
6869  private:
6870   int* on_start_counter_;
6871   bool* is_destroyed_;
6872 };
6873
6874 // Tests the constructor.
6875 TEST(TestEventListenersTest, ConstructionWorks) {
6876   TestEventListeners listeners;
6877
6878   EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr);
6879   EXPECT_TRUE(listeners.default_result_printer() == nullptr);
6880   EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
6881 }
6882
6883 // Tests that the TestEventListeners destructor deletes all the listeners it
6884 // owns.
6885 TEST(TestEventListenersTest, DestructionWorks) {
6886   bool default_result_printer_is_destroyed = false;
6887   bool default_xml_printer_is_destroyed = false;
6888   bool extra_listener_is_destroyed = false;
6889   TestListener* default_result_printer =
6890       new TestListener(nullptr, &default_result_printer_is_destroyed);
6891   TestListener* default_xml_printer =
6892       new TestListener(nullptr, &default_xml_printer_is_destroyed);
6893   TestListener* extra_listener =
6894       new TestListener(nullptr, &extra_listener_is_destroyed);
6895
6896   {
6897     TestEventListeners listeners;
6898     TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
6899                                                         default_result_printer);
6900     TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
6901                                                        default_xml_printer);
6902     listeners.Append(extra_listener);
6903   }
6904   EXPECT_TRUE(default_result_printer_is_destroyed);
6905   EXPECT_TRUE(default_xml_printer_is_destroyed);
6906   EXPECT_TRUE(extra_listener_is_destroyed);
6907 }
6908
6909 // Tests that a listener Append'ed to a TestEventListeners list starts
6910 // receiving events.
6911 TEST(TestEventListenersTest, Append) {
6912   int on_start_counter = 0;
6913   bool is_destroyed = false;
6914   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6915   {
6916     TestEventListeners listeners;
6917     listeners.Append(listener);
6918     TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6919         *UnitTest::GetInstance());
6920     EXPECT_EQ(1, on_start_counter);
6921   }
6922   EXPECT_TRUE(is_destroyed);
6923 }
6924
6925 // Tests that listeners receive events in the order they were appended to
6926 // the list, except for *End requests, which must be received in the reverse
6927 // order.
6928 class SequenceTestingListener : public EmptyTestEventListener {
6929  public:
6930   SequenceTestingListener(std::vector<std::string>* vector, const char* id)
6931       : vector_(vector), id_(id) {}
6932
6933  protected:
6934   void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6935     vector_->push_back(GetEventDescription("OnTestProgramStart"));
6936   }
6937
6938   void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {
6939     vector_->push_back(GetEventDescription("OnTestProgramEnd"));
6940   }
6941
6942   void OnTestIterationStart(const UnitTest& /*unit_test*/,
6943                             int /*iteration*/) override {
6944     vector_->push_back(GetEventDescription("OnTestIterationStart"));
6945   }
6946
6947   void OnTestIterationEnd(const UnitTest& /*unit_test*/,
6948                           int /*iteration*/) override {
6949     vector_->push_back(GetEventDescription("OnTestIterationEnd"));
6950   }
6951
6952  private:
6953   std::string GetEventDescription(const char* method) {
6954     Message message;
6955     message << id_ << "." << method;
6956     return message.GetString();
6957   }
6958
6959   std::vector<std::string>* vector_;
6960   const char* const id_;
6961
6962   GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
6963 };
6964
6965 TEST(EventListenerTest, AppendKeepsOrder) {
6966   std::vector<std::string> vec;
6967   TestEventListeners listeners;
6968   listeners.Append(new SequenceTestingListener(&vec, "1st"));
6969   listeners.Append(new SequenceTestingListener(&vec, "2nd"));
6970   listeners.Append(new SequenceTestingListener(&vec, "3rd"));
6971
6972   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6973       *UnitTest::GetInstance());
6974   ASSERT_EQ(3U, vec.size());
6975   EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
6976   EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
6977   EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
6978
6979   vec.clear();
6980   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
6981       *UnitTest::GetInstance());
6982   ASSERT_EQ(3U, vec.size());
6983   EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
6984   EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
6985   EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
6986
6987   vec.clear();
6988   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
6989       *UnitTest::GetInstance(), 0);
6990   ASSERT_EQ(3U, vec.size());
6991   EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
6992   EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
6993   EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
6994
6995   vec.clear();
6996   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
6997       *UnitTest::GetInstance(), 0);
6998   ASSERT_EQ(3U, vec.size());
6999   EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
7000   EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
7001   EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
7002 }
7003
7004 // Tests that a listener removed from a TestEventListeners list stops receiving
7005 // events and is not deleted when the list is destroyed.
7006 TEST(TestEventListenersTest, Release) {
7007   int on_start_counter = 0;
7008   bool is_destroyed = false;
7009   // Although Append passes the ownership of this object to the list,
7010   // the following calls release it, and we need to delete it before the
7011   // test ends.
7012   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7013   {
7014     TestEventListeners listeners;
7015     listeners.Append(listener);
7016     EXPECT_EQ(listener, listeners.Release(listener));
7017     TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7018         *UnitTest::GetInstance());
7019     EXPECT_TRUE(listeners.Release(listener) == nullptr);
7020   }
7021   EXPECT_EQ(0, on_start_counter);
7022   EXPECT_FALSE(is_destroyed);
7023   delete listener;
7024 }
7025
7026 // Tests that no events are forwarded when event forwarding is disabled.
7027 TEST(EventListenerTest, SuppressEventForwarding) {
7028   int on_start_counter = 0;
7029   TestListener* listener = new TestListener(&on_start_counter, nullptr);
7030
7031   TestEventListeners listeners;
7032   listeners.Append(listener);
7033   ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7034   TestEventListenersAccessor::SuppressEventForwarding(&listeners);
7035   ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7036   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7037       *UnitTest::GetInstance());
7038   EXPECT_EQ(0, on_start_counter);
7039 }
7040
7041 // Tests that events generated by Google Test are not forwarded in
7042 // death test subprocesses.
7043 TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
7044   EXPECT_DEATH_IF_SUPPORTED({
7045       GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
7046           *GetUnitTestImpl()->listeners())) << "expected failure";},
7047       "expected failure");
7048 }
7049
7050 // Tests that a listener installed via SetDefaultResultPrinter() starts
7051 // receiving events and is returned via default_result_printer() and that
7052 // the previous default_result_printer is removed from the list and deleted.
7053 TEST(EventListenerTest, default_result_printer) {
7054   int on_start_counter = 0;
7055   bool is_destroyed = false;
7056   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7057
7058   TestEventListeners listeners;
7059   TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7060
7061   EXPECT_EQ(listener, listeners.default_result_printer());
7062
7063   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7064       *UnitTest::GetInstance());
7065
7066   EXPECT_EQ(1, on_start_counter);
7067
7068   // Replacing default_result_printer with something else should remove it
7069   // from the list and destroy it.
7070   TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr);
7071
7072   EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7073   EXPECT_TRUE(is_destroyed);
7074
7075   // After broadcasting an event the counter is still the same, indicating
7076   // the listener is not in the list anymore.
7077   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7078       *UnitTest::GetInstance());
7079   EXPECT_EQ(1, on_start_counter);
7080 }
7081
7082 // Tests that the default_result_printer listener stops receiving events
7083 // when removed via Release and that is not owned by the list anymore.
7084 TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
7085   int on_start_counter = 0;
7086   bool is_destroyed = false;
7087   // Although Append passes the ownership of this object to the list,
7088   // the following calls release it, and we need to delete it before the
7089   // test ends.
7090   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7091   {
7092     TestEventListeners listeners;
7093     TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7094
7095     EXPECT_EQ(listener, listeners.Release(listener));
7096     EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7097     EXPECT_FALSE(is_destroyed);
7098
7099     // Broadcasting events now should not affect default_result_printer.
7100     TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7101         *UnitTest::GetInstance());
7102     EXPECT_EQ(0, on_start_counter);
7103   }
7104   // Destroying the list should not affect the listener now, too.
7105   EXPECT_FALSE(is_destroyed);
7106   delete listener;
7107 }
7108
7109 // Tests that a listener installed via SetDefaultXmlGenerator() starts
7110 // receiving events and is returned via default_xml_generator() and that
7111 // the previous default_xml_generator is removed from the list and deleted.
7112 TEST(EventListenerTest, default_xml_generator) {
7113   int on_start_counter = 0;
7114   bool is_destroyed = false;
7115   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7116
7117   TestEventListeners listeners;
7118   TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7119
7120   EXPECT_EQ(listener, listeners.default_xml_generator());
7121
7122   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7123       *UnitTest::GetInstance());
7124
7125   EXPECT_EQ(1, on_start_counter);
7126
7127   // Replacing default_xml_generator with something else should remove it
7128   // from the list and destroy it.
7129   TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr);
7130
7131   EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7132   EXPECT_TRUE(is_destroyed);
7133
7134   // After broadcasting an event the counter is still the same, indicating
7135   // the listener is not in the list anymore.
7136   TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7137       *UnitTest::GetInstance());
7138   EXPECT_EQ(1, on_start_counter);
7139 }
7140
7141 // Tests that the default_xml_generator listener stops receiving events
7142 // when removed via Release and that is not owned by the list anymore.
7143 TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
7144   int on_start_counter = 0;
7145   bool is_destroyed = false;
7146   // Although Append passes the ownership of this object to the list,
7147   // the following calls release it, and we need to delete it before the
7148   // test ends.
7149   TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7150   {
7151     TestEventListeners listeners;
7152     TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7153
7154     EXPECT_EQ(listener, listeners.Release(listener));
7155     EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7156     EXPECT_FALSE(is_destroyed);
7157
7158     // Broadcasting events now should not affect default_xml_generator.
7159     TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7160         *UnitTest::GetInstance());
7161     EXPECT_EQ(0, on_start_counter);
7162   }
7163   // Destroying the list should not affect the listener now, too.
7164   EXPECT_FALSE(is_destroyed);
7165   delete listener;
7166 }
7167
7168 // Sanity tests to ensure that the alternative, verbose spellings of
7169 // some of the macros work.  We don't test them thoroughly as that
7170 // would be quite involved.  Since their implementations are
7171 // straightforward, and they are rarely used, we'll just rely on the
7172 // users to tell us when they are broken.
7173 GTEST_TEST(AlternativeNameTest, Works) {  // GTEST_TEST is the same as TEST.
7174   GTEST_SUCCEED() << "OK";  // GTEST_SUCCEED is the same as SUCCEED.
7175
7176   // GTEST_FAIL is the same as FAIL.
7177   EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
7178                        "An expected failure");
7179
7180   // GTEST_ASSERT_XY is the same as ASSERT_XY.
7181
7182   GTEST_ASSERT_EQ(0, 0);
7183   EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
7184                        "An expected failure");
7185   EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
7186                        "An expected failure");
7187
7188   GTEST_ASSERT_NE(0, 1);
7189   GTEST_ASSERT_NE(1, 0);
7190   EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
7191                        "An expected failure");
7192
7193   GTEST_ASSERT_LE(0, 0);
7194   GTEST_ASSERT_LE(0, 1);
7195   EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
7196                        "An expected failure");
7197
7198   GTEST_ASSERT_LT(0, 1);
7199   EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
7200                        "An expected failure");
7201   EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
7202                        "An expected failure");
7203
7204   GTEST_ASSERT_GE(0, 0);
7205   GTEST_ASSERT_GE(1, 0);
7206   EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
7207                        "An expected failure");
7208
7209   GTEST_ASSERT_GT(1, 0);
7210   EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
7211                        "An expected failure");
7212   EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
7213                        "An expected failure");
7214 }
7215
7216 // Tests for internal utilities necessary for implementation of the universal
7217 // printing.
7218
7219 class ConversionHelperBase {};
7220 class ConversionHelperDerived : public ConversionHelperBase {};
7221
7222 struct HasDebugStringMethods {
7223   std::string DebugString() const { return ""; }
7224   std::string ShortDebugString() const { return ""; }
7225 };
7226
7227 struct InheritsDebugStringMethods : public HasDebugStringMethods {};
7228
7229 struct WrongTypeDebugStringMethod {
7230   std::string DebugString() const { return ""; }
7231   int ShortDebugString() const { return 1; }
7232 };
7233
7234 struct NotConstDebugStringMethod {
7235   std::string DebugString() { return ""; }
7236   std::string ShortDebugString() const { return ""; }
7237 };
7238
7239 struct MissingDebugStringMethod {
7240   std::string DebugString() { return ""; }
7241 };
7242
7243 struct IncompleteType;
7244
7245 // Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
7246 // constant.
7247 TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
7248   GTEST_COMPILE_ASSERT_(
7249       HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
7250       const_true);
7251   GTEST_COMPILE_ASSERT_(
7252       HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
7253       const_true);
7254   GTEST_COMPILE_ASSERT_(HasDebugStringAndShortDebugString<
7255                             const InheritsDebugStringMethods>::value,
7256                         const_true);
7257   GTEST_COMPILE_ASSERT_(
7258       !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
7259       const_false);
7260   GTEST_COMPILE_ASSERT_(
7261       !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
7262       const_false);
7263   GTEST_COMPILE_ASSERT_(
7264       !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
7265       const_false);
7266   GTEST_COMPILE_ASSERT_(
7267       !HasDebugStringAndShortDebugString<IncompleteType>::value, const_false);
7268   GTEST_COMPILE_ASSERT_(!HasDebugStringAndShortDebugString<int>::value,
7269                         const_false);
7270 }
7271
7272 // Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
7273 // needed methods.
7274 TEST(HasDebugStringAndShortDebugStringTest,
7275      ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
7276   EXPECT_TRUE(
7277       HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
7278 }
7279
7280 // Tests that HasDebugStringAndShortDebugString<T>::value is false when T
7281 // doesn't have needed methods.
7282 TEST(HasDebugStringAndShortDebugStringTest,
7283      ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7284   EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);
7285   EXPECT_FALSE(
7286       HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);
7287 }
7288
7289 // Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7290
7291 template <typename T1, typename T2>
7292 void TestGTestRemoveReferenceAndConst() {
7293   static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value,
7294                 "GTEST_REMOVE_REFERENCE_AND_CONST_ failed.");
7295 }
7296
7297 TEST(RemoveReferenceToConstTest, Works) {
7298   TestGTestRemoveReferenceAndConst<int, int>();
7299   TestGTestRemoveReferenceAndConst<double, double&>();
7300   TestGTestRemoveReferenceAndConst<char, const char>();
7301   TestGTestRemoveReferenceAndConst<char, const char&>();
7302   TestGTestRemoveReferenceAndConst<const char*, const char*>();
7303 }
7304
7305 // Tests GTEST_REFERENCE_TO_CONST_.
7306
7307 template <typename T1, typename T2>
7308 void TestGTestReferenceToConst() {
7309   static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value,
7310                 "GTEST_REFERENCE_TO_CONST_ failed.");
7311 }
7312
7313 TEST(GTestReferenceToConstTest, Works) {
7314   TestGTestReferenceToConst<const char&, char>();
7315   TestGTestReferenceToConst<const int&, const int>();
7316   TestGTestReferenceToConst<const double&, double>();
7317   TestGTestReferenceToConst<const std::string&, const std::string&>();
7318 }
7319
7320
7321 // Tests IsContainerTest.
7322
7323 class NonContainer {};
7324
7325 TEST(IsContainerTestTest, WorksForNonContainer) {
7326   EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7327   EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7328   EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7329 }
7330
7331 TEST(IsContainerTestTest, WorksForContainer) {
7332   EXPECT_EQ(sizeof(IsContainer),
7333             sizeof(IsContainerTest<std::vector<bool> >(0)));
7334   EXPECT_EQ(sizeof(IsContainer),
7335             sizeof(IsContainerTest<std::map<int, double> >(0)));
7336 }
7337
7338 struct ConstOnlyContainerWithPointerIterator {
7339   using const_iterator = int*;
7340   const_iterator begin() const;
7341   const_iterator end() const;
7342 };
7343
7344 struct ConstOnlyContainerWithClassIterator {
7345   struct const_iterator {
7346     const int& operator*() const;
7347     const_iterator& operator++(/* pre-increment */);
7348   };
7349   const_iterator begin() const;
7350   const_iterator end() const;
7351 };
7352
7353 TEST(IsContainerTestTest, ConstOnlyContainer) {
7354   EXPECT_EQ(sizeof(IsContainer),
7355             sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
7356   EXPECT_EQ(sizeof(IsContainer),
7357             sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
7358 }
7359
7360 // Tests IsHashTable.
7361 struct AHashTable {
7362   typedef void hasher;
7363 };
7364 struct NotReallyAHashTable {
7365   typedef void hasher;
7366   typedef void reverse_iterator;
7367 };
7368 TEST(IsHashTable, Basic) {
7369   EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value);
7370   EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value);
7371   EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value);
7372   EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value);
7373 }
7374
7375 // Tests ArrayEq().
7376
7377 TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7378   EXPECT_TRUE(ArrayEq(5, 5L));
7379   EXPECT_FALSE(ArrayEq('a', 0));
7380 }
7381
7382 TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7383   // Note that a and b are distinct but compatible types.
7384   const int a[] = { 0, 1 };
7385   long b[] = { 0, 1 };
7386   EXPECT_TRUE(ArrayEq(a, b));
7387   EXPECT_TRUE(ArrayEq(a, 2, b));
7388
7389   b[0] = 2;
7390   EXPECT_FALSE(ArrayEq(a, b));
7391   EXPECT_FALSE(ArrayEq(a, 1, b));
7392 }
7393
7394 TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7395   const char a[][3] = { "hi", "lo" };
7396   const char b[][3] = { "hi", "lo" };
7397   const char c[][3] = { "hi", "li" };
7398
7399   EXPECT_TRUE(ArrayEq(a, b));
7400   EXPECT_TRUE(ArrayEq(a, 2, b));
7401
7402   EXPECT_FALSE(ArrayEq(a, c));
7403   EXPECT_FALSE(ArrayEq(a, 2, c));
7404 }
7405
7406 // Tests ArrayAwareFind().
7407
7408 TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7409   const char a[] = "hello";
7410   EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7411   EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7412 }
7413
7414 TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7415   int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
7416   const int b[2] = { 2, 3 };
7417   EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7418
7419   const int c[2] = { 6, 7 };
7420   EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7421 }
7422
7423 // Tests CopyArray().
7424
7425 TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7426   int n = 0;
7427   CopyArray('a', &n);
7428   EXPECT_EQ('a', n);
7429 }
7430
7431 TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7432   const char a[3] = "hi";
7433   int b[3];
7434 #ifndef __BORLANDC__  // C++Builder cannot compile some array size deductions.
7435   CopyArray(a, &b);
7436   EXPECT_TRUE(ArrayEq(a, b));
7437 #endif
7438
7439   int c[3];
7440   CopyArray(a, 3, c);
7441   EXPECT_TRUE(ArrayEq(a, c));
7442 }
7443
7444 TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7445   const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
7446   int b[2][3];
7447 #ifndef __BORLANDC__  // C++Builder cannot compile some array size deductions.
7448   CopyArray(a, &b);
7449   EXPECT_TRUE(ArrayEq(a, b));
7450 #endif
7451
7452   int c[2][3];
7453   CopyArray(a, 2, c);
7454   EXPECT_TRUE(ArrayEq(a, c));
7455 }
7456
7457 // Tests NativeArray.
7458
7459 TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7460   const int a[3] = { 0, 1, 2 };
7461   NativeArray<int> na(a, 3, RelationToSourceReference());
7462   EXPECT_EQ(3U, na.size());
7463   EXPECT_EQ(a, na.begin());
7464 }
7465
7466 TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7467   typedef int Array[2];
7468   Array* a = new Array[1];
7469   (*a)[0] = 0;
7470   (*a)[1] = 1;
7471   NativeArray<int> na(*a, 2, RelationToSourceCopy());
7472   EXPECT_NE(*a, na.begin());
7473   delete[] a;
7474   EXPECT_EQ(0, na.begin()[0]);
7475   EXPECT_EQ(1, na.begin()[1]);
7476
7477   // We rely on the heap checker to verify that na deletes the copy of
7478   // array.
7479 }
7480
7481 TEST(NativeArrayTest, TypeMembersAreCorrect) {
7482   StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7483   StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7484
7485   StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7486   StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7487 }
7488
7489 TEST(NativeArrayTest, MethodsWork) {
7490   const int a[3] = { 0, 1, 2 };
7491   NativeArray<int> na(a, 3, RelationToSourceCopy());
7492   ASSERT_EQ(3U, na.size());
7493   EXPECT_EQ(3, na.end() - na.begin());
7494
7495   NativeArray<int>::const_iterator it = na.begin();
7496   EXPECT_EQ(0, *it);
7497   ++it;
7498   EXPECT_EQ(1, *it);
7499   it++;
7500   EXPECT_EQ(2, *it);
7501   ++it;
7502   EXPECT_EQ(na.end(), it);
7503
7504   EXPECT_TRUE(na == na);
7505
7506   NativeArray<int> na2(a, 3, RelationToSourceReference());
7507   EXPECT_TRUE(na == na2);
7508
7509   const int b1[3] = { 0, 1, 1 };
7510   const int b2[4] = { 0, 1, 2, 3 };
7511   EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
7512   EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
7513 }
7514
7515 TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7516   const char a[2][3] = { "hi", "lo" };
7517   NativeArray<char[3]> na(a, 2, RelationToSourceReference());
7518   ASSERT_EQ(2U, na.size());
7519   EXPECT_EQ(a, na.begin());
7520 }
7521
7522 // IndexSequence
7523 TEST(IndexSequence, MakeIndexSequence) {
7524   using testing::internal::IndexSequence;
7525   using testing::internal::MakeIndexSequence;
7526   EXPECT_TRUE(
7527       (std::is_same<IndexSequence<>, MakeIndexSequence<0>::type>::value));
7528   EXPECT_TRUE(
7529       (std::is_same<IndexSequence<0>, MakeIndexSequence<1>::type>::value));
7530   EXPECT_TRUE(
7531       (std::is_same<IndexSequence<0, 1>, MakeIndexSequence<2>::type>::value));
7532   EXPECT_TRUE((
7533       std::is_same<IndexSequence<0, 1, 2>, MakeIndexSequence<3>::type>::value));
7534   EXPECT_TRUE(
7535       (std::is_base_of<IndexSequence<0, 1, 2>, MakeIndexSequence<3>>::value));
7536 }
7537
7538 // ElemFromList
7539 TEST(ElemFromList, Basic) {
7540   using testing::internal::ElemFromList;
7541   EXPECT_TRUE(
7542       (std::is_same<int, ElemFromList<0, int, double, char>::type>::value));
7543   EXPECT_TRUE(
7544       (std::is_same<double, ElemFromList<1, int, double, char>::type>::value));
7545   EXPECT_TRUE(
7546       (std::is_same<char, ElemFromList<2, int, double, char>::type>::value));
7547   EXPECT_TRUE((
7548       std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int,
7549                                       char, int, int, int, int>::type>::value));
7550 }
7551
7552 // FlatTuple
7553 TEST(FlatTuple, Basic) {
7554   using testing::internal::FlatTuple;
7555
7556   FlatTuple<int, double, const char*> tuple = {};
7557   EXPECT_EQ(0, tuple.Get<0>());
7558   EXPECT_EQ(0.0, tuple.Get<1>());
7559   EXPECT_EQ(nullptr, tuple.Get<2>());
7560
7561   tuple = FlatTuple<int, double, const char*>(
7562       testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo");
7563   EXPECT_EQ(7, tuple.Get<0>());
7564   EXPECT_EQ(3.2, tuple.Get<1>());
7565   EXPECT_EQ(std::string("Foo"), tuple.Get<2>());
7566
7567   tuple.Get<1>() = 5.1;
7568   EXPECT_EQ(5.1, tuple.Get<1>());
7569 }
7570
7571 namespace {
7572 std::string AddIntToString(int i, const std::string& s) {
7573   return s + std::to_string(i);
7574 }
7575 }  // namespace
7576
7577 TEST(FlatTuple, Apply) {
7578   using testing::internal::FlatTuple;
7579
7580   FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},
7581                                     5, "Hello"};
7582
7583   // Lambda.
7584   EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
7585     return i == static_cast<int>(s.size());
7586   }));
7587
7588   // Function.
7589   EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
7590
7591   // Mutating operations.
7592   tuple.Apply([](int& i, std::string& s) {
7593     ++i;
7594     s += s;
7595   });
7596   EXPECT_EQ(tuple.Get<0>(), 6);
7597   EXPECT_EQ(tuple.Get<1>(), "HelloHello");
7598 }
7599
7600 struct ConstructionCounting {
7601   ConstructionCounting() { ++default_ctor_calls; }
7602   ~ConstructionCounting() { ++dtor_calls; }
7603   ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }
7604   ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }
7605   ConstructionCounting& operator=(const ConstructionCounting&) {
7606     ++copy_assignment_calls;
7607     return *this;
7608   }
7609   ConstructionCounting& operator=(ConstructionCounting&&) noexcept {
7610     ++move_assignment_calls;
7611     return *this;
7612   }
7613
7614   static void Reset() {
7615     default_ctor_calls = 0;
7616     dtor_calls = 0;
7617     copy_ctor_calls = 0;
7618     move_ctor_calls = 0;
7619     copy_assignment_calls = 0;
7620     move_assignment_calls = 0;
7621   }
7622
7623   static int default_ctor_calls;
7624   static int dtor_calls;
7625   static int copy_ctor_calls;
7626   static int move_ctor_calls;
7627   static int copy_assignment_calls;
7628   static int move_assignment_calls;
7629 };
7630
7631 int ConstructionCounting::default_ctor_calls = 0;
7632 int ConstructionCounting::dtor_calls = 0;
7633 int ConstructionCounting::copy_ctor_calls = 0;
7634 int ConstructionCounting::move_ctor_calls = 0;
7635 int ConstructionCounting::copy_assignment_calls = 0;
7636 int ConstructionCounting::move_assignment_calls = 0;
7637
7638 TEST(FlatTuple, ConstructorCalls) {
7639   using testing::internal::FlatTuple;
7640
7641   // Default construction.
7642   ConstructionCounting::Reset();
7643   { FlatTuple<ConstructionCounting> tuple; }
7644   EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7645   EXPECT_EQ(ConstructionCounting::dtor_calls, 1);
7646   EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7647   EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7648   EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7649   EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7650
7651   // Copy construction.
7652   ConstructionCounting::Reset();
7653   {
7654     ConstructionCounting elem;
7655     FlatTuple<ConstructionCounting> tuple{
7656         testing::internal::FlatTupleConstructTag{}, elem};
7657   }
7658   EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7659   EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7660   EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);
7661   EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7662   EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7663   EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7664
7665   // Move construction.
7666   ConstructionCounting::Reset();
7667   {
7668     FlatTuple<ConstructionCounting> tuple{
7669         testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}};
7670   }
7671   EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7672   EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7673   EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7674   EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);
7675   EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7676   EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7677
7678   // Copy assignment.
7679   // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7680   // elements
7681   ConstructionCounting::Reset();
7682   {
7683     FlatTuple<ConstructionCounting> tuple;
7684     ConstructionCounting elem;
7685     tuple.Get<0>() = elem;
7686   }
7687   EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
7688   EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7689   EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7690   EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7691   EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);
7692   EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7693
7694   // Move assignment.
7695   // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7696   // elements
7697   ConstructionCounting::Reset();
7698   {
7699     FlatTuple<ConstructionCounting> tuple;
7700     tuple.Get<0>() = ConstructionCounting{};
7701   }
7702   EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
7703   EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7704   EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7705   EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7706   EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7707   EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);
7708
7709   ConstructionCounting::Reset();
7710 }
7711
7712 TEST(FlatTuple, ManyTypes) {
7713   using testing::internal::FlatTuple;
7714
7715   // Instantiate FlatTuple with 257 ints.
7716   // Tests show that we can do it with thousands of elements, but very long
7717   // compile times makes it unusuitable for this test.
7718 #define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int,
7719 #define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8
7720 #define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16
7721 #define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32
7722 #define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64
7723 #define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128
7724
7725   // Let's make sure that we can have a very long list of types without blowing
7726   // up the template instantiation depth.
7727   FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple;
7728
7729   tuple.Get<0>() = 7;
7730   tuple.Get<99>() = 17;
7731   tuple.Get<256>() = 1000;
7732   EXPECT_EQ(7, tuple.Get<0>());
7733   EXPECT_EQ(17, tuple.Get<99>());
7734   EXPECT_EQ(1000, tuple.Get<256>());
7735 }
7736
7737 // Tests SkipPrefix().
7738
7739 TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7740   const char* const str = "hello";
7741
7742   const char* p = str;
7743   EXPECT_TRUE(SkipPrefix("", &p));
7744   EXPECT_EQ(str, p);
7745
7746   p = str;
7747   EXPECT_TRUE(SkipPrefix("hell", &p));
7748   EXPECT_EQ(str + 4, p);
7749 }
7750
7751 TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7752   const char* const str = "world";
7753
7754   const char* p = str;
7755   EXPECT_FALSE(SkipPrefix("W", &p));
7756   EXPECT_EQ(str, p);
7757
7758   p = str;
7759   EXPECT_FALSE(SkipPrefix("world!", &p));
7760   EXPECT_EQ(str, p);
7761 }
7762
7763 // Tests ad_hoc_test_result().
7764 TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
7765   const testing::TestResult& test_result =
7766       testing::UnitTest::GetInstance()->ad_hoc_test_result();
7767   EXPECT_FALSE(test_result.Failed());
7768 }
7769
7770 class DynamicUnitTestFixture : public testing::Test {};
7771
7772 class DynamicTest : public DynamicUnitTestFixture {
7773   void TestBody() override { EXPECT_TRUE(true); }
7774 };
7775
7776 auto* dynamic_test = testing::RegisterTest(
7777     "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__,
7778     __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });
7779
7780 TEST(RegisterTest, WasRegistered) {
7781   auto* unittest = testing::UnitTest::GetInstance();
7782   for (int i = 0; i < unittest->total_test_suite_count(); ++i) {
7783     auto* tests = unittest->GetTestSuite(i);
7784     if (tests->name() != std::string("DynamicUnitTestFixture")) continue;
7785     for (int j = 0; j < tests->total_test_count(); ++j) {
7786       if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue;
7787       // Found it.
7788       EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE");
7789       EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE");
7790       return;
7791     }
7792   }
7793
7794   FAIL() << "Didn't find the test!";
7795 }