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