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