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