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