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