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// his 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 string& message) { output_ += message; }
90
91    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, 0, NULL) {}
98
99 protected:
100  string* output() { return &(fake_sock_writer_->output_); }
101
102  FakeSocketWriter* const fake_sock_writer_;
103  StreamingListener streamer_;
104  UnitTest unit_test_;
105  TestInfo test_info_obj_;  // The name test_info_ was taken by testing::Test.
106};
107
108TEST_F(StreamingListenerTest, OnTestProgramEnd) {
109  *output() = "";
110  streamer_.OnTestProgramEnd(unit_test_);
111  EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
112}
113
114TEST_F(StreamingListenerTest, OnTestIterationEnd) {
115  *output() = "";
116  streamer_.OnTestIterationEnd(unit_test_, 42);
117  EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
118}
119
120TEST_F(StreamingListenerTest, OnTestCaseStart) {
121  *output() = "";
122  streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", NULL, NULL));
123  EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
124}
125
126TEST_F(StreamingListenerTest, OnTestCaseEnd) {
127  *output() = "";
128  streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", NULL, NULL));
129  EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
130}
131
132TEST_F(StreamingListenerTest, OnTestStart) {
133  *output() = "";
134  streamer_.OnTestStart(test_info_obj_);
135  EXPECT_EQ("event=TestStart&name=Bar\n", *output());
136}
137
138TEST_F(StreamingListenerTest, OnTestEnd) {
139  *output() = "";
140  streamer_.OnTestEnd(test_info_obj_);
141  EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
142}
143
144TEST_F(StreamingListenerTest, OnTestPartResult) {
145  *output() = "";
146  streamer_.OnTestPartResult(TestPartResult(
147      TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
148
149  // Meta characters in the failure message should be properly escaped.
150  EXPECT_EQ(
151      "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
152      *output());
153}
154
155#endif  // GTEST_CAN_STREAM_RESULTS_
156
157// Provides access to otherwise private parts of the TestEventListeners class
158// that are needed to test it.
159class TestEventListenersAccessor {
160 public:
161  static TestEventListener* GetRepeater(TestEventListeners* listeners) {
162    return listeners->repeater();
163  }
164
165  static void SetDefaultResultPrinter(TestEventListeners* listeners,
166                                      TestEventListener* listener) {
167    listeners->SetDefaultResultPrinter(listener);
168  }
169  static void SetDefaultXmlGenerator(TestEventListeners* listeners,
170                                     TestEventListener* listener) {
171    listeners->SetDefaultXmlGenerator(listener);
172  }
173
174  static bool EventForwardingEnabled(const TestEventListeners& listeners) {
175    return listeners.EventForwardingEnabled();
176  }
177
178  static void SuppressEventForwarding(TestEventListeners* listeners) {
179    listeners->SuppressEventForwarding();
180  }
181};
182
183class UnitTestRecordPropertyTestHelper : public Test {
184 protected:
185  UnitTestRecordPropertyTestHelper() {}
186
187  // Forwards to UnitTest::RecordProperty() to bypass access controls.
188  void UnitTestRecordProperty(const char* key, const std::string& value) {
189    unit_test_.RecordProperty(key, value);
190  }
191
192  UnitTest unit_test_;
193};
194
195}  // namespace internal
196}  // namespace testing
197
198using testing::AssertionFailure;
199using testing::AssertionResult;
200using testing::AssertionSuccess;
201using testing::DoubleLE;
202using testing::EmptyTestEventListener;
203using testing::Environment;
204using testing::FloatLE;
205using testing::GTEST_FLAG(also_run_disabled_tests);
206using testing::GTEST_FLAG(break_on_failure);
207using testing::GTEST_FLAG(catch_exceptions);
208using testing::GTEST_FLAG(color);
209using testing::GTEST_FLAG(death_test_use_fork);
210using testing::GTEST_FLAG(filter);
211using testing::GTEST_FLAG(list_tests);
212using testing::GTEST_FLAG(output);
213using testing::GTEST_FLAG(print_time);
214using testing::GTEST_FLAG(random_seed);
215using testing::GTEST_FLAG(repeat);
216using testing::GTEST_FLAG(show_internal_stack_frames);
217using testing::GTEST_FLAG(shuffle);
218using testing::GTEST_FLAG(stack_trace_depth);
219using testing::GTEST_FLAG(stream_result_to);
220using testing::GTEST_FLAG(throw_on_failure);
221using testing::IsNotSubstring;
222using testing::IsSubstring;
223using testing::Message;
224using testing::ScopedFakeTestPartResultReporter;
225using testing::StaticAssertTypeEq;
226using testing::Test;
227using testing::TestCase;
228using testing::TestEventListeners;
229using testing::TestInfo;
230using testing::TestPartResult;
231using testing::TestPartResultArray;
232using testing::TestProperty;
233using testing::TestResult;
234using testing::TimeInMillis;
235using testing::UnitTest;
236using testing::internal::AddReference;
237using testing::internal::AlwaysFalse;
238using testing::internal::AlwaysTrue;
239using testing::internal::AppendUserMessage;
240using testing::internal::ArrayAwareFind;
241using testing::internal::ArrayEq;
242using testing::internal::CodePointToUtf8;
243using testing::internal::CompileAssertTypesEqual;
244using testing::internal::CopyArray;
245using testing::internal::CountIf;
246using testing::internal::EqFailure;
247using testing::internal::FloatingPoint;
248using testing::internal::ForEach;
249using testing::internal::FormatEpochTimeInMillisAsIso8601;
250using testing::internal::FormatTimeInMillisAsSeconds;
251using testing::internal::GTestFlagSaver;
252using testing::internal::GetCurrentOsStackTraceExceptTop;
253using testing::internal::GetElementOr;
254using testing::internal::GetNextRandomSeed;
255using testing::internal::GetRandomSeedFromFlag;
256using testing::internal::GetTestTypeId;
257using testing::internal::GetTimeInMillis;
258using testing::internal::GetTypeId;
259using testing::internal::GetUnitTestImpl;
260using testing::internal::ImplicitlyConvertible;
261using testing::internal::Int32;
262using testing::internal::Int32FromEnvOrDie;
263using testing::internal::IsAProtocolMessage;
264using testing::internal::IsContainer;
265using testing::internal::IsContainerTest;
266using testing::internal::IsNotContainer;
267using testing::internal::NativeArray;
268using testing::internal::ParseInt32Flag;
269using testing::internal::RelationToSourceCopy;
270using testing::internal::RelationToSourceReference;
271using testing::internal::RemoveConst;
272using testing::internal::RemoveReference;
273using testing::internal::ShouldRunTestOnShard;
274using testing::internal::ShouldShard;
275using testing::internal::ShouldUseColor;
276using testing::internal::Shuffle;
277using testing::internal::ShuffleRange;
278using testing::internal::SkipPrefix;
279using testing::internal::StreamableToString;
280using testing::internal::String;
281using testing::internal::TestEventListenersAccessor;
282using testing::internal::TestResultAccessor;
283using testing::internal::UInt32;
284using testing::internal::WideStringToUtf8;
285using testing::internal::edit_distance::CalculateOptimalEdits;
286using testing::internal::edit_distance::CreateUnifiedDiff;
287using testing::internal::edit_distance::EditType;
288using testing::internal::kMaxRandomSeed;
289using testing::internal::kTestTypeIdInGoogleTest;
290using testing::internal::scoped_ptr;
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
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 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 that GTestFlagSaver works on Windows and Mac.
1522
1523class GTestFlagSaverTest : public Test {
1524 protected:
1525  // Saves the Google Test flags such that we can restore them later, and
1526  // then sets them to their default values.  This will be called
1527  // before the first test in this test case is run.
1528  static void SetUpTestCase() {
1529    saver_ = new GTestFlagSaver;
1530
1531    GTEST_FLAG(also_run_disabled_tests) = false;
1532    GTEST_FLAG(break_on_failure) = false;
1533    GTEST_FLAG(catch_exceptions) = false;
1534    GTEST_FLAG(death_test_use_fork) = false;
1535    GTEST_FLAG(color) = "auto";
1536    GTEST_FLAG(filter) = "";
1537    GTEST_FLAG(list_tests) = false;
1538    GTEST_FLAG(output) = "";
1539    GTEST_FLAG(print_time) = true;
1540    GTEST_FLAG(random_seed) = 0;
1541    GTEST_FLAG(repeat) = 1;
1542    GTEST_FLAG(shuffle) = false;
1543    GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
1544    GTEST_FLAG(stream_result_to) = "";
1545    GTEST_FLAG(throw_on_failure) = false;
1546  }
1547
1548  // Restores the Google Test flags that the tests have modified.  This will
1549  // be called after the last test in this test case is run.
1550  static void TearDownTestCase() {
1551    delete saver_;
1552    saver_ = NULL;
1553  }
1554
1555  // Verifies that the Google Test flags have their default values, and then
1556  // modifies each of them.
1557  void VerifyAndModifyFlags() {
1558    EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
1559    EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1560    EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1561    EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
1562    EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
1563    EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1564    EXPECT_FALSE(GTEST_FLAG(list_tests));
1565    EXPECT_STREQ("", GTEST_FLAG(output).c_str());
1566    EXPECT_TRUE(GTEST_FLAG(print_time));
1567    EXPECT_EQ(0, GTEST_FLAG(random_seed));
1568    EXPECT_EQ(1, GTEST_FLAG(repeat));
1569    EXPECT_FALSE(GTEST_FLAG(shuffle));
1570    EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
1571    EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
1572    EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
1573
1574    GTEST_FLAG(also_run_disabled_tests) = true;
1575    GTEST_FLAG(break_on_failure) = true;
1576    GTEST_FLAG(catch_exceptions) = true;
1577    GTEST_FLAG(color) = "no";
1578    GTEST_FLAG(death_test_use_fork) = true;
1579    GTEST_FLAG(filter) = "abc";
1580    GTEST_FLAG(list_tests) = true;
1581    GTEST_FLAG(output) = "xml:foo.xml";
1582    GTEST_FLAG(print_time) = false;
1583    GTEST_FLAG(random_seed) = 1;
1584    GTEST_FLAG(repeat) = 100;
1585    GTEST_FLAG(shuffle) = true;
1586    GTEST_FLAG(stack_trace_depth) = 1;
1587    GTEST_FLAG(stream_result_to) = "localhost:1234";
1588    GTEST_FLAG(throw_on_failure) = true;
1589  }
1590
1591 private:
1592  // For saving Google Test flags during this test case.
1593  static GTestFlagSaver* saver_;
1594};
1595
1596GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
1597
1598// Google Test doesn't guarantee the order of tests.  The following two
1599// tests are designed to work regardless of their order.
1600
1601// Modifies the Google Test flags in the test body.
1602TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1603  VerifyAndModifyFlags();
1604}
1605
1606// Verifies that the Google Test flags in the body of the previous test were
1607// restored to their original values.
1608TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1609  VerifyAndModifyFlags();
1610}
1611
1612// Sets an environment variable with the given name to the given
1613// value.  If the value argument is "", unsets the environment
1614// variable.  The caller must ensure that both arguments are not NULL.
1615static void SetEnv(const char* name, const char* value) {
1616#if GTEST_OS_WINDOWS_MOBILE
1617  // Environment variables are not supported on Windows CE.
1618  return;
1619#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1620  // C++Builder's putenv only stores a pointer to its parameter; we have to
1621  // ensure that the string remains valid as long as it might be needed.
1622  // We use an std::map to do so.
1623  static std::map<std::string, std::string*> added_env;
1624
1625  // Because putenv stores a pointer to the string buffer, we can't delete the
1626  // previous string (if present) until after it's replaced.
1627  std::string *prev_env = NULL;
1628  if (added_env.find(name) != added_env.end()) {
1629    prev_env = added_env[name];
1630  }
1631  added_env[name] = new std::string(
1632      (Message() << name << "=" << value).GetString());
1633
1634  // The standard signature of putenv accepts a 'char*' argument. Other
1635  // implementations, like C++Builder's, accept a 'const char*'.
1636  // We cast away the 'const' since that would work for both variants.
1637  putenv(const_cast<char*>(added_env[name]->c_str()));
1638  delete prev_env;
1639#elif GTEST_OS_WINDOWS  // If we are on Windows proper.
1640  _putenv((Message() << name << "=" << value).GetString().c_str());
1641#else
1642  if (*value == '\0') {
1643    unsetenv(name);
1644  } else {
1645    setenv(name, value, 1);
1646  }
1647#endif  // GTEST_OS_WINDOWS_MOBILE
1648}
1649
1650#if !GTEST_OS_WINDOWS_MOBILE
1651// Environment variables are not supported on Windows CE.
1652
1653using testing::internal::Int32FromGTestEnv;
1654
1655// Tests Int32FromGTestEnv().
1656
1657// Tests that Int32FromGTestEnv() returns the default value when the
1658// environment variable is not set.
1659TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1660  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1661  EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1662}
1663
1664// Tests that Int32FromGTestEnv() returns the default value when the
1665// environment variable overflows as an Int32.
1666TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1667  printf("(expecting 2 warnings)\n");
1668
1669  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1670  EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1671
1672  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1673  EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1674}
1675
1676// Tests that Int32FromGTestEnv() returns the default value when the
1677// environment variable does not represent a valid decimal integer.
1678TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1679  printf("(expecting 2 warnings)\n");
1680
1681  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1682  EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1683
1684  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1685  EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1686}
1687
1688// Tests that Int32FromGTestEnv() parses and returns the value of the
1689// environment variable when it represents a valid decimal integer in
1690// the range of an Int32.
1691TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1692  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1693  EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1694
1695  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1696  EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1697}
1698#endif  // !GTEST_OS_WINDOWS_MOBILE
1699
1700// Tests ParseInt32Flag().
1701
1702// Tests that ParseInt32Flag() returns false and doesn't change the
1703// output value when the flag has wrong format
1704TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1705  Int32 value = 123;
1706  EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1707  EXPECT_EQ(123, value);
1708
1709  EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1710  EXPECT_EQ(123, value);
1711}
1712
1713// Tests that ParseInt32Flag() returns false and doesn't change the
1714// output value when the flag overflows as an Int32.
1715TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1716  printf("(expecting 2 warnings)\n");
1717
1718  Int32 value = 123;
1719  EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1720  EXPECT_EQ(123, value);
1721
1722  EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1723  EXPECT_EQ(123, value);
1724}
1725
1726// Tests that ParseInt32Flag() returns false and doesn't change the
1727// output value when the flag does not represent a valid decimal
1728// integer.
1729TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1730  printf("(expecting 2 warnings)\n");
1731
1732  Int32 value = 123;
1733  EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1734  EXPECT_EQ(123, value);
1735
1736  EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1737  EXPECT_EQ(123, value);
1738}
1739
1740// Tests that ParseInt32Flag() parses the value of the flag and
1741// returns true when the flag represents a valid decimal integer in
1742// the range of an Int32.
1743TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1744  Int32 value = 123;
1745  EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1746  EXPECT_EQ(456, value);
1747
1748  EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1749                             "abc", &value));
1750  EXPECT_EQ(-789, value);
1751}
1752
1753// Tests that Int32FromEnvOrDie() parses the value of the var or
1754// returns the correct default.
1755// Environment variables are not supported on Windows CE.
1756#if !GTEST_OS_WINDOWS_MOBILE
1757TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1758  EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1759  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1760  EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1761  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1762  EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1763}
1764#endif  // !GTEST_OS_WINDOWS_MOBILE
1765
1766// Tests that Int32FromEnvOrDie() aborts with an error message
1767// if the variable is not an Int32.
1768TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1769  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1770  EXPECT_DEATH_IF_SUPPORTED(
1771      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1772      ".*");
1773}
1774
1775// Tests that Int32FromEnvOrDie() aborts with an error message
1776// if the variable cannot be represnted by an Int32.
1777TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1778  SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1779  EXPECT_DEATH_IF_SUPPORTED(
1780      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1781      ".*");
1782}
1783
1784// Tests that ShouldRunTestOnShard() selects all tests
1785// where there is 1 shard.
1786TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1787  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1788  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1789  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1790  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1791  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1792}
1793
1794class ShouldShardTest : public testing::Test {
1795 protected:
1796  virtual void SetUp() {
1797    index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1798    total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1799  }
1800
1801  virtual void TearDown() {
1802    SetEnv(index_var_, "");
1803    SetEnv(total_var_, "");
1804  }
1805
1806  const char* index_var_;
1807  const char* total_var_;
1808};
1809
1810// Tests that sharding is disabled if neither of the environment variables
1811// are set.
1812TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1813  SetEnv(index_var_, "");
1814  SetEnv(total_var_, "");
1815
1816  EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1817  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1818}
1819
1820// Tests that sharding is not enabled if total_shards  == 1.
1821TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1822  SetEnv(index_var_, "0");
1823  SetEnv(total_var_, "1");
1824  EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1825  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1826}
1827
1828// Tests that sharding is enabled if total_shards > 1 and
1829// we are not in a death test subprocess.
1830// Environment variables are not supported on Windows CE.
1831#if !GTEST_OS_WINDOWS_MOBILE
1832TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1833  SetEnv(index_var_, "4");
1834  SetEnv(total_var_, "22");
1835  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1836  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1837
1838  SetEnv(index_var_, "8");
1839  SetEnv(total_var_, "9");
1840  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1841  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1842
1843  SetEnv(index_var_, "0");
1844  SetEnv(total_var_, "9");
1845  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1846  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1847}
1848#endif  // !GTEST_OS_WINDOWS_MOBILE
1849
1850// Tests that we exit in error if the sharding values are not valid.
1851
1852typedef ShouldShardTest ShouldShardDeathTest;
1853
1854TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
1855  SetEnv(index_var_, "4");
1856  SetEnv(total_var_, "4");
1857  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1858
1859  SetEnv(index_var_, "4");
1860  SetEnv(total_var_, "-2");
1861  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1862
1863  SetEnv(index_var_, "5");
1864  SetEnv(total_var_, "");
1865  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1866
1867  SetEnv(index_var_, "");
1868  SetEnv(total_var_, "5");
1869  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1870}
1871
1872// Tests that ShouldRunTestOnShard is a partition when 5
1873// shards are used.
1874TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1875  // Choose an arbitrary number of tests and shards.
1876  const int num_tests = 17;
1877  const int num_shards = 5;
1878
1879  // Check partitioning: each test should be on exactly 1 shard.
1880  for (int test_id = 0; test_id < num_tests; test_id++) {
1881    int prev_selected_shard_index = -1;
1882    for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1883      if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1884        if (prev_selected_shard_index < 0) {
1885          prev_selected_shard_index = shard_index;
1886        } else {
1887          ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1888            << shard_index << " are both selected to run test " << test_id;
1889        }
1890      }
1891    }
1892  }
1893
1894  // Check balance: This is not required by the sharding protocol, but is a
1895  // desirable property for performance.
1896  for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1897    int num_tests_on_shard = 0;
1898    for (int test_id = 0; test_id < num_tests; test_id++) {
1899      num_tests_on_shard +=
1900        ShouldRunTestOnShard(num_shards, shard_index, test_id);
1901    }
1902    EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1903  }
1904}
1905
1906// For the same reason we are not explicitly testing everything in the
1907// Test class, there are no separate tests for the following classes
1908// (except for some trivial cases):
1909//
1910//   TestCase, UnitTest, UnitTestResultPrinter.
1911//
1912// Similarly, there are no separate tests for the following macros:
1913//
1914//   TEST, TEST_F, RUN_ALL_TESTS
1915
1916TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1917  ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
1918  EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1919}
1920
1921TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
1922  EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
1923  EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
1924}
1925
1926// When a property using a reserved key is supplied to this function, it
1927// tests that a non-fatal failure is added, a fatal failure is not added,
1928// and that the property is not recorded.
1929void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1930    const TestResult& test_result, const char* key) {
1931  EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
1932  ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
1933                                                  << "' recorded unexpectedly.";
1934}
1935
1936void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
1937    const char* key) {
1938  const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
1939  ASSERT_TRUE(test_info != NULL);
1940  ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
1941                                                        key);
1942}
1943
1944void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1945    const char* key) {
1946  const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
1947  ASSERT_TRUE(test_case != NULL);
1948  ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1949      test_case->ad_hoc_test_result(), key);
1950}
1951
1952void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
1953    const char* key) {
1954  ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1955      UnitTest::GetInstance()->ad_hoc_test_result(), key);
1956}
1957
1958// Tests that property recording functions in UnitTest outside of tests
1959// functions correcly.  Creating a separate instance of UnitTest ensures it
1960// is in a state similar to the UnitTest's singleton's between tests.
1961class UnitTestRecordPropertyTest :
1962    public testing::internal::UnitTestRecordPropertyTestHelper {
1963 public:
1964  static void SetUpTestCase() {
1965    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1966        "disabled");
1967    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1968        "errors");
1969    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1970        "failures");
1971    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1972        "name");
1973    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1974        "tests");
1975    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1976        "time");
1977
1978    Test::RecordProperty("test_case_key_1", "1");
1979    const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
1980    ASSERT_TRUE(test_case != NULL);
1981
1982    ASSERT_EQ(1, test_case->ad_hoc_test_result().test_property_count());
1983    EXPECT_STREQ("test_case_key_1",
1984                 test_case->ad_hoc_test_result().GetTestProperty(0).key());
1985    EXPECT_STREQ("1",
1986                 test_case->ad_hoc_test_result().GetTestProperty(0).value());
1987  }
1988};
1989
1990// Tests TestResult has the expected property when added.
1991TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
1992  UnitTestRecordProperty("key_1", "1");
1993
1994  ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
1995
1996  EXPECT_STREQ("key_1",
1997               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
1998  EXPECT_STREQ("1",
1999               unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2000}
2001
2002// Tests TestResult has multiple properties when added.
2003TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
2004  UnitTestRecordProperty("key_1", "1");
2005  UnitTestRecordProperty("key_2", "2");
2006
2007  ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2008
2009  EXPECT_STREQ("key_1",
2010               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2011  EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2012
2013  EXPECT_STREQ("key_2",
2014               unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2015  EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2016}
2017
2018// Tests TestResult::RecordProperty() overrides values for duplicate keys.
2019TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
2020  UnitTestRecordProperty("key_1", "1");
2021  UnitTestRecordProperty("key_2", "2");
2022  UnitTestRecordProperty("key_1", "12");
2023  UnitTestRecordProperty("key_2", "22");
2024
2025  ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2026
2027  EXPECT_STREQ("key_1",
2028               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2029  EXPECT_STREQ("12",
2030               unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2031
2032  EXPECT_STREQ("key_2",
2033               unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2034  EXPECT_STREQ("22",
2035               unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2036}
2037
2038TEST_F(UnitTestRecordPropertyTest,
2039       AddFailureInsideTestsWhenUsingTestCaseReservedKeys) {
2040  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2041      "name");
2042  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2043      "value_param");
2044  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2045      "type_param");
2046  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2047      "status");
2048  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2049      "time");
2050  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2051      "classname");
2052}
2053
2054TEST_F(UnitTestRecordPropertyTest,
2055       AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
2056  EXPECT_NONFATAL_FAILURE(
2057      Test::RecordProperty("name", "1"),
2058      "'classname', 'name', 'status', 'time', 'type_param', and 'value_param'"
2059      " are reserved");
2060}
2061
2062class UnitTestRecordPropertyTestEnvironment : public Environment {
2063 public:
2064  virtual void TearDown() {
2065    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2066        "tests");
2067    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2068        "failures");
2069    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2070        "disabled");
2071    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2072        "errors");
2073    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2074        "name");
2075    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2076        "timestamp");
2077    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2078        "time");
2079    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2080        "random_seed");
2081  }
2082};
2083
2084// This will test property recording outside of any test or test case.
2085static Environment* record_property_env =
2086    AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
2087
2088// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2089// of various arities.  They do not attempt to be exhaustive.  Rather,
2090// view them as smoke tests that can be easily reviewed and verified.
2091// A more complete set of tests for predicate assertions can be found
2092// in gtest_pred_impl_unittest.cc.
2093
2094// First, some predicates and predicate-formatters needed by the tests.
2095
2096// Returns true iff the argument is an even number.
2097bool IsEven(int n) {
2098  return (n % 2) == 0;
2099}
2100
2101// A functor that returns true iff the argument is an even number.
2102struct IsEvenFunctor {
2103  bool operator()(int n) { return IsEven(n); }
2104};
2105
2106// A predicate-formatter function that asserts the argument is an even
2107// number.
2108AssertionResult AssertIsEven(const char* expr, int n) {
2109  if (IsEven(n)) {
2110    return AssertionSuccess();
2111  }
2112
2113  Message msg;
2114  msg << expr << " evaluates to " << n << ", which is not even.";
2115  return AssertionFailure(msg);
2116}
2117
2118// A predicate function that returns AssertionResult for use in
2119// EXPECT/ASSERT_TRUE/FALSE.
2120AssertionResult ResultIsEven(int n) {
2121  if (IsEven(n))
2122    return AssertionSuccess() << n << " is even";
2123  else
2124    return AssertionFailure() << n << " is odd";
2125}
2126
2127// A predicate function that returns AssertionResult but gives no
2128// explanation why it succeeds. Needed for testing that
2129// EXPECT/ASSERT_FALSE handles such functions correctly.
2130AssertionResult ResultIsEvenNoExplanation(int n) {
2131  if (IsEven(n))
2132    return AssertionSuccess();
2133  else
2134    return AssertionFailure() << n << " is odd";
2135}
2136
2137// A predicate-formatter functor that asserts the argument is an even
2138// number.
2139struct AssertIsEvenFunctor {
2140  AssertionResult operator()(const char* expr, int n) {
2141    return AssertIsEven(expr, n);
2142  }
2143};
2144
2145// Returns true iff the sum of the arguments is an even number.
2146bool SumIsEven2(int n1, int n2) {
2147  return IsEven(n1 + n2);
2148}
2149
2150// A functor that returns true iff the sum of the arguments is an even
2151// number.
2152struct SumIsEven3Functor {
2153  bool operator()(int n1, int n2, int n3) {
2154    return IsEven(n1 + n2 + n3);
2155  }
2156};
2157
2158// A predicate-formatter function that asserts the sum of the
2159// arguments is an even number.
2160AssertionResult AssertSumIsEven4(
2161    const char* e1, const char* e2, const char* e3, const char* e4,
2162    int n1, int n2, int n3, int n4) {
2163  const int sum = n1 + n2 + n3 + n4;
2164  if (IsEven(sum)) {
2165    return AssertionSuccess();
2166  }
2167
2168  Message msg;
2169  msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2170      << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2171      << ") evaluates to " << sum << ", which is not even.";
2172  return AssertionFailure(msg);
2173}
2174
2175// A predicate-formatter functor that asserts the sum of the arguments
2176// is an even number.
2177struct AssertSumIsEven5Functor {
2178  AssertionResult operator()(
2179      const char* e1, const char* e2, const char* e3, const char* e4,
2180      const char* e5, int n1, int n2, int n3, int n4, int n5) {
2181    const int sum = n1 + n2 + n3 + n4 + n5;
2182    if (IsEven(sum)) {
2183      return AssertionSuccess();
2184    }
2185
2186    Message msg;
2187    msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2188        << " ("
2189        << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2190        << ") evaluates to " << sum << ", which is not even.";
2191    return AssertionFailure(msg);
2192  }
2193};
2194
2195
2196// Tests unary predicate assertions.
2197
2198// Tests unary predicate assertions that don't use a custom formatter.
2199TEST(Pred1Test, WithoutFormat) {
2200  // Success cases.
2201  EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2202  ASSERT_PRED1(IsEven, 4);
2203
2204  // Failure cases.
2205  EXPECT_NONFATAL_FAILURE({  // NOLINT
2206    EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2207  }, "This failure is expected.");
2208  EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2209                       "evaluates to false");
2210}
2211
2212// Tests unary predicate assertions that use a custom formatter.
2213TEST(Pred1Test, WithFormat) {
2214  // Success cases.
2215  EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2216  ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2217    << "This failure is UNEXPECTED!";
2218
2219  // Failure cases.
2220  const int n = 5;
2221  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2222                          "n evaluates to 5, which is not even.");
2223  EXPECT_FATAL_FAILURE({  // NOLINT
2224    ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2225  }, "This failure is expected.");
2226}
2227
2228// Tests that unary predicate assertions evaluates their arguments
2229// exactly once.
2230TEST(Pred1Test, SingleEvaluationOnFailure) {
2231  // A success case.
2232  static int n = 0;
2233  EXPECT_PRED1(IsEven, n++);
2234  EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2235
2236  // A failure case.
2237  EXPECT_FATAL_FAILURE({  // NOLINT
2238    ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2239        << "This failure is expected.";
2240  }, "This failure is expected.");
2241  EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2242}
2243
2244
2245// Tests predicate assertions whose arity is >= 2.
2246
2247// Tests predicate assertions that don't use a custom formatter.
2248TEST(PredTest, WithoutFormat) {
2249  // Success cases.
2250  ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2251  EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2252
2253  // Failure cases.
2254  const int n1 = 1;
2255  const int n2 = 2;
2256  EXPECT_NONFATAL_FAILURE({  // NOLINT
2257    EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2258  }, "This failure is expected.");
2259  EXPECT_FATAL_FAILURE({  // NOLINT
2260    ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2261  }, "evaluates to false");
2262}
2263
2264// Tests predicate assertions that use a custom formatter.
2265TEST(PredTest, WithFormat) {
2266  // Success cases.
2267  ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2268    "This failure is UNEXPECTED!";
2269  EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2270
2271  // Failure cases.
2272  const int n1 = 1;
2273  const int n2 = 2;
2274  const int n3 = 4;
2275  const int n4 = 6;
2276  EXPECT_NONFATAL_FAILURE({  // NOLINT
2277    EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2278  }, "evaluates to 13, which is not even.");
2279  EXPECT_FATAL_FAILURE({  // NOLINT
2280    ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2281        << "This failure is expected.";
2282  }, "This failure is expected.");
2283}
2284
2285// Tests that predicate assertions evaluates their arguments
2286// exactly once.
2287TEST(PredTest, SingleEvaluationOnFailure) {
2288  // A success case.
2289  int n1 = 0;
2290  int n2 = 0;
2291  EXPECT_PRED2(SumIsEven2, n1++, n2++);
2292  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2293  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2294
2295  // Another success case.
2296  n1 = n2 = 0;
2297  int n3 = 0;
2298  int n4 = 0;
2299  int n5 = 0;
2300  ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2301                      n1++, n2++, n3++, n4++, n5++)
2302                        << "This failure is UNEXPECTED!";
2303  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2304  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2305  EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2306  EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2307  EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2308
2309  // A failure case.
2310  n1 = n2 = n3 = 0;
2311  EXPECT_NONFATAL_FAILURE({  // NOLINT
2312    EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2313        << "This failure is expected.";
2314  }, "This failure is expected.");
2315  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2316  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2317  EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2318
2319  // Another failure case.
2320  n1 = n2 = n3 = n4 = 0;
2321  EXPECT_NONFATAL_FAILURE({  // NOLINT
2322    EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2323  }, "evaluates to 1, which is not even.");
2324  EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2325  EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2326  EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2327  EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2328}
2329
2330
2331// Some helper functions for testing using overloaded/template
2332// functions with ASSERT_PREDn and EXPECT_PREDn.
2333
2334bool IsPositive(double x) {
2335  return x > 0;
2336}
2337
2338template <typename T>
2339bool IsNegative(T x) {
2340  return x < 0;
2341}
2342
2343template <typename T1, typename T2>
2344bool GreaterThan(T1 x1, T2 x2) {
2345  return x1 > x2;
2346}
2347
2348// Tests that overloaded functions can be used in *_PRED* as long as
2349// their types are explicitly specified.
2350TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2351  // C++Builder requires C-style casts rather than static_cast.
2352  EXPECT_PRED1((bool (*)(int))(IsPositive), 5);  // NOLINT
2353  ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0);  // NOLINT
2354}
2355
2356// Tests that template functions can be used in *_PRED* as long as
2357// their types are explicitly specified.
2358TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2359  EXPECT_PRED1(IsNegative<int>, -5);
2360  // Makes sure that we can handle templates with more than one
2361  // parameter.
2362  ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2363}
2364
2365
2366// Some helper functions for testing using overloaded/template
2367// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2368
2369AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2370  return n > 0 ? AssertionSuccess() :
2371      AssertionFailure(Message() << "Failure");
2372}
2373
2374AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2375  return x > 0 ? AssertionSuccess() :
2376      AssertionFailure(Message() << "Failure");
2377}
2378
2379template <typename T>
2380AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2381  return x < 0 ? AssertionSuccess() :
2382      AssertionFailure(Message() << "Failure");
2383}
2384
2385template <typename T1, typename T2>
2386AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2387                             const T1& x1, const T2& x2) {
2388  return x1 == x2 ? AssertionSuccess() :
2389      AssertionFailure(Message() << "Failure");
2390}
2391
2392// Tests that overloaded functions can be used in *_PRED_FORMAT*
2393// without explicitly specifying their types.
2394TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2395  EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2396  ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2397}
2398
2399// Tests that template functions can be used in *_PRED_FORMAT* without
2400// explicitly specifying their types.
2401TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2402  EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2403  ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2404}
2405
2406
2407// Tests string assertions.
2408
2409// Tests ASSERT_STREQ with non-NULL arguments.
2410TEST(StringAssertionTest, ASSERT_STREQ) {
2411  const char * const p1 = "good";
2412  ASSERT_STREQ(p1, p1);
2413
2414  // Let p2 have the same content as p1, but be at a different address.
2415  const char p2[] = "good";
2416  ASSERT_STREQ(p1, p2);
2417
2418  EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2419                       "Expected: \"bad\"");
2420}
2421
2422// Tests ASSERT_STREQ with NULL arguments.
2423TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2424  ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2425  EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2426                       "non-null");
2427}
2428
2429// Tests ASSERT_STREQ with NULL arguments.
2430TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2431  EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2432                       "non-null");
2433}
2434
2435// Tests ASSERT_STRNE.
2436TEST(StringAssertionTest, ASSERT_STRNE) {
2437  ASSERT_STRNE("hi", "Hi");
2438  ASSERT_STRNE("Hi", NULL);
2439  ASSERT_STRNE(NULL, "Hi");
2440  ASSERT_STRNE("", NULL);
2441  ASSERT_STRNE(NULL, "");
2442  ASSERT_STRNE("", "Hi");
2443  ASSERT_STRNE("Hi", "");
2444  EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2445                       "\"Hi\" vs \"Hi\"");
2446}
2447
2448// Tests ASSERT_STRCASEEQ.
2449TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2450  ASSERT_STRCASEEQ("hi", "Hi");
2451  ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2452
2453  ASSERT_STRCASEEQ("", "");
2454  EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2455                       "(ignoring case)");
2456}
2457
2458// Tests ASSERT_STRCASENE.
2459TEST(StringAssertionTest, ASSERT_STRCASENE) {
2460  ASSERT_STRCASENE("hi1", "Hi2");
2461  ASSERT_STRCASENE("Hi", NULL);
2462  ASSERT_STRCASENE(NULL, "Hi");
2463  ASSERT_STRCASENE("", NULL);
2464  ASSERT_STRCASENE(NULL, "");
2465  ASSERT_STRCASENE("", "Hi");
2466  ASSERT_STRCASENE("Hi", "");
2467  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2468                       "(ignoring case)");
2469}
2470
2471// Tests *_STREQ on wide strings.
2472TEST(StringAssertionTest, STREQ_Wide) {
2473  // NULL strings.
2474  ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2475
2476  // Empty strings.
2477  ASSERT_STREQ(L"", L"");
2478
2479  // Non-null vs NULL.
2480  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2481                          "non-null");
2482
2483  // Equal strings.
2484  EXPECT_STREQ(L"Hi", L"Hi");
2485
2486  // Unequal strings.
2487  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2488                          "Abc");
2489
2490  // Strings containing wide characters.
2491  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2492                          "abc");
2493
2494  // The streaming variation.
2495  EXPECT_NONFATAL_FAILURE({  // NOLINT
2496    EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
2497  }, "Expected failure");
2498}
2499
2500// Tests *_STRNE on wide strings.
2501TEST(StringAssertionTest, STRNE_Wide) {
2502  // NULL strings.
2503  EXPECT_NONFATAL_FAILURE({  // NOLINT
2504    EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2505  }, "");
2506
2507  // Empty strings.
2508  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2509                          "L\"\"");
2510
2511  // Non-null vs NULL.
2512  ASSERT_STRNE(L"non-null", NULL);
2513
2514  // Equal strings.
2515  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2516                          "L\"Hi\"");
2517
2518  // Unequal strings.
2519  EXPECT_STRNE(L"abc", L"Abc");
2520
2521  // Strings containing wide characters.
2522  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2523                          "abc");
2524
2525  // The streaming variation.
2526  ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
2527}
2528
2529// Tests for ::testing::IsSubstring().
2530
2531// Tests that IsSubstring() returns the correct result when the input
2532// argument type is const char*.
2533TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2534  EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2535  EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2536  EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2537
2538  EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2539  EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2540}
2541
2542// Tests that IsSubstring() returns the correct result when the input
2543// argument type is const wchar_t*.
2544TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2545  EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2546  EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
2547  EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2548
2549  EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2550  EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2551}
2552
2553// Tests that IsSubstring() generates the correct message when the input
2554// argument type is const char*.
2555TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2556  EXPECT_STREQ("Value of: needle_expr\n"
2557               "  Actual: \"needle\"\n"
2558               "Expected: a substring of haystack_expr\n"
2559               "Which is: \"haystack\"",
2560               IsSubstring("needle_expr", "haystack_expr",
2561                           "needle", "haystack").failure_message());
2562}
2563
2564// Tests that IsSubstring returns the correct result when the input
2565// argument type is ::std::string.
2566TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2567  EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2568  EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2569}
2570
2571#if GTEST_HAS_STD_WSTRING
2572// Tests that IsSubstring returns the correct result when the input
2573// argument type is ::std::wstring.
2574TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2575  EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2576  EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2577}
2578
2579// Tests that IsSubstring() generates the correct message when the input
2580// argument type is ::std::wstring.
2581TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2582  EXPECT_STREQ("Value of: needle_expr\n"
2583               "  Actual: L\"needle\"\n"
2584               "Expected: a substring of haystack_expr\n"
2585               "Which is: L\"haystack\"",
2586               IsSubstring(
2587                   "needle_expr", "haystack_expr",
2588                   ::std::wstring(L"needle"), L"haystack").failure_message());
2589}
2590
2591#endif  // GTEST_HAS_STD_WSTRING
2592
2593// Tests for ::testing::IsNotSubstring().
2594
2595// Tests that IsNotSubstring() returns the correct result when the input
2596// argument type is const char*.
2597TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2598  EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2599  EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2600}
2601
2602// Tests that IsNotSubstring() returns the correct result when the input
2603// argument type is const wchar_t*.
2604TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2605  EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2606  EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2607}
2608
2609// Tests that IsNotSubstring() generates the correct message when the input
2610// argument type is const wchar_t*.
2611TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2612  EXPECT_STREQ("Value of: needle_expr\n"
2613               "  Actual: L\"needle\"\n"
2614               "Expected: not a substring of haystack_expr\n"
2615               "Which is: L\"two needles\"",
2616               IsNotSubstring(
2617                   "needle_expr", "haystack_expr",
2618                   L"needle", L"two needles").failure_message());
2619}
2620
2621// Tests that IsNotSubstring returns the correct result when the input
2622// argument type is ::std::string.
2623TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2624  EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2625  EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2626}
2627
2628// Tests that IsNotSubstring() generates the correct message when the input
2629// argument type is ::std::string.
2630TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2631  EXPECT_STREQ("Value of: needle_expr\n"
2632               "  Actual: \"needle\"\n"
2633               "Expected: not a substring of haystack_expr\n"
2634               "Which is: \"two needles\"",
2635               IsNotSubstring(
2636                   "needle_expr", "haystack_expr",
2637                   ::std::string("needle"), "two needles").failure_message());
2638}
2639
2640#if GTEST_HAS_STD_WSTRING
2641
2642// Tests that IsNotSubstring returns the correct result when the input
2643// argument type is ::std::wstring.
2644TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2645  EXPECT_FALSE(
2646      IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2647  EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2648}
2649
2650#endif  // GTEST_HAS_STD_WSTRING
2651
2652// Tests floating-point assertions.
2653
2654template <typename RawType>
2655class FloatingPointTest : public Test {
2656 protected:
2657  // Pre-calculated numbers to be used by the tests.
2658  struct TestValues {
2659    RawType close_to_positive_zero;
2660    RawType close_to_negative_zero;
2661    RawType further_from_negative_zero;
2662
2663    RawType close_to_one;
2664    RawType further_from_one;
2665
2666    RawType infinity;
2667    RawType close_to_infinity;
2668    RawType further_from_infinity;
2669
2670    RawType nan1;
2671    RawType nan2;
2672  };
2673
2674  typedef typename testing::internal::FloatingPoint<RawType> Floating;
2675  typedef typename Floating::Bits Bits;
2676
2677  virtual void SetUp() {
2678    const size_t max_ulps = Floating::kMaxUlps;
2679
2680    // The bits that represent 0.0.
2681    const Bits zero_bits = Floating(0).bits();
2682
2683    // Makes some numbers close to 0.0.
2684    values_.close_to_positive_zero = Floating::ReinterpretBits(
2685        zero_bits + max_ulps/2);
2686    values_.close_to_negative_zero = -Floating::ReinterpretBits(
2687        zero_bits + max_ulps - max_ulps/2);
2688    values_.further_from_negative_zero = -Floating::ReinterpretBits(
2689        zero_bits + max_ulps + 1 - max_ulps/2);
2690
2691    // The bits that represent 1.0.
2692    const Bits one_bits = Floating(1).bits();
2693
2694    // Makes some numbers close to 1.0.
2695    values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2696    values_.further_from_one = Floating::ReinterpretBits(
2697        one_bits + max_ulps + 1);
2698
2699    // +infinity.
2700    values_.infinity = Floating::Infinity();
2701
2702    // The bits that represent +infinity.
2703    const Bits infinity_bits = Floating(values_.infinity).bits();
2704
2705    // Makes some numbers close to infinity.
2706    values_.close_to_infinity = Floating::ReinterpretBits(
2707        infinity_bits - max_ulps);
2708    values_.further_from_infinity = Floating::ReinterpretBits(
2709        infinity_bits - max_ulps - 1);
2710
2711    // Makes some NAN's.  Sets the most significant bit of the fraction so that
2712    // our NaN's are quiet; trying to process a signaling NaN would raise an
2713    // exception if our environment enables floating point exceptions.
2714    values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2715        | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2716    values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2717        | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
2718  }
2719
2720  void TestSize() {
2721    EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2722  }
2723
2724  static TestValues values_;
2725};
2726
2727template <typename RawType>
2728typename FloatingPointTest<RawType>::TestValues
2729    FloatingPointTest<RawType>::values_;
2730
2731// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2732typedef FloatingPointTest<float> FloatTest;
2733
2734// Tests that the size of Float::Bits matches the size of float.
2735TEST_F(FloatTest, Size) {
2736  TestSize();
2737}
2738
2739// Tests comparing with +0 and -0.
2740TEST_F(FloatTest, Zeros) {
2741  EXPECT_FLOAT_EQ(0.0, -0.0);
2742  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2743                          "1.0");
2744  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2745                       "1.5");
2746}
2747
2748// Tests comparing numbers close to 0.
2749//
2750// This ensures that *_FLOAT_EQ handles the sign correctly and no
2751// overflow occurs when comparing numbers whose absolute value is very
2752// small.
2753TEST_F(FloatTest, AlmostZeros) {
2754  // In C++Builder, names within local classes (such as used by
2755  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2756  // scoping class.  Use a static local alias as a workaround.
2757  // We use the assignment syntax since some compilers, like Sun Studio,
2758  // don't allow initializing references using construction syntax
2759  // (parentheses).
2760  static const FloatTest::TestValues& v = this->values_;
2761
2762  EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2763  EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2764  EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2765
2766  EXPECT_FATAL_FAILURE({  // NOLINT
2767    ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2768                    v.further_from_negative_zero);
2769  }, "v.further_from_negative_zero");
2770}
2771
2772// Tests comparing numbers close to each other.
2773TEST_F(FloatTest, SmallDiff) {
2774  EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2775  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2776                          "values_.further_from_one");
2777}
2778
2779// Tests comparing numbers far apart.
2780TEST_F(FloatTest, LargeDiff) {
2781  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2782                          "3.0");
2783}
2784
2785// Tests comparing with infinity.
2786//
2787// This ensures that no overflow occurs when comparing numbers whose
2788// absolute value is very large.
2789TEST_F(FloatTest, Infinity) {
2790  EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2791  EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
2792#if !GTEST_OS_SYMBIAN
2793  // Nokia's STLport crashes if we try to output infinity or NaN.
2794  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2795                          "-values_.infinity");
2796
2797  // This is interesting as the representations of infinity and nan1
2798  // are only 1 DLP apart.
2799  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2800                          "values_.nan1");
2801#endif  // !GTEST_OS_SYMBIAN
2802}
2803
2804// Tests that comparing with NAN always returns false.
2805TEST_F(FloatTest, NaN) {
2806#if !GTEST_OS_SYMBIAN
2807// Nokia's STLport crashes if we try to output infinity or NaN.
2808
2809  // In C++Builder, names within local classes (such as used by
2810  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2811  // scoping class.  Use a static local alias as a workaround.
2812  // We use the assignment syntax since some compilers, like Sun Studio,
2813  // don't allow initializing references using construction syntax
2814  // (parentheses).
2815  static const FloatTest::TestValues& v = this->values_;
2816
2817  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2818                          "v.nan1");
2819  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2820                          "v.nan2");
2821  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2822                          "v.nan1");
2823
2824  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2825                       "v.infinity");
2826#endif  // !GTEST_OS_SYMBIAN
2827}
2828
2829// Tests that *_FLOAT_EQ are reflexive.
2830TEST_F(FloatTest, Reflexive) {
2831  EXPECT_FLOAT_EQ(0.0, 0.0);
2832  EXPECT_FLOAT_EQ(1.0, 1.0);
2833  ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
2834}
2835
2836// Tests that *_FLOAT_EQ are commutative.
2837TEST_F(FloatTest, Commutative) {
2838  // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2839  EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2840
2841  // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2842  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2843                          "1.0");
2844}
2845
2846// Tests EXPECT_NEAR.
2847TEST_F(FloatTest, EXPECT_NEAR) {
2848  EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2849  EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2850  EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f),  // NOLINT
2851                          "The difference between 1.0f and 1.5f is 0.5, "
2852                          "which exceeds 0.25f");
2853  // To work around a bug in gcc 2.95.0, there is intentionally no
2854  // space after the first comma in the previous line.
2855}
2856
2857// Tests ASSERT_NEAR.
2858TEST_F(FloatTest, ASSERT_NEAR) {
2859  ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2860  ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2861  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f),  // NOLINT
2862                       "The difference between 1.0f and 1.5f is 0.5, "
2863                       "which exceeds 0.25f");
2864  // To work around a bug in gcc 2.95.0, there is intentionally no
2865  // space after the first comma in the previous line.
2866}
2867
2868// Tests the cases where FloatLE() should succeed.
2869TEST_F(FloatTest, FloatLESucceeds) {
2870  EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f);  // When val1 < val2,
2871  ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f);  // val1 == val2,
2872
2873  // or when val1 is greater than, but almost equals to, val2.
2874  EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2875}
2876
2877// Tests the cases where FloatLE() should fail.
2878TEST_F(FloatTest, FloatLEFails) {
2879  // When val1 is greater than val2 by a large margin,
2880  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2881                          "(2.0f) <= (1.0f)");
2882
2883  // or by a small yet non-negligible margin,
2884  EXPECT_NONFATAL_FAILURE({  // NOLINT
2885    EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2886  }, "(values_.further_from_one) <= (1.0f)");
2887
2888#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2889  // Nokia's STLport crashes if we try to output infinity or NaN.
2890  // C++Builder gives bad results for ordered comparisons involving NaNs
2891  // due to compiler bugs.
2892  EXPECT_NONFATAL_FAILURE({  // NOLINT
2893    EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2894  }, "(values_.nan1) <= (values_.infinity)");
2895  EXPECT_NONFATAL_FAILURE({  // NOLINT
2896    EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2897  }, "(-values_.infinity) <= (values_.nan1)");
2898  EXPECT_FATAL_FAILURE({  // NOLINT
2899    ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2900  }, "(values_.nan1) <= (values_.nan1)");
2901#endif  // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2902}
2903
2904// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2905typedef FloatingPointTest<double> DoubleTest;
2906
2907// Tests that the size of Double::Bits matches the size of double.
2908TEST_F(DoubleTest, Size) {
2909  TestSize();
2910}
2911
2912// Tests comparing with +0 and -0.
2913TEST_F(DoubleTest, Zeros) {
2914  EXPECT_DOUBLE_EQ(0.0, -0.0);
2915  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2916                          "1.0");
2917  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2918                       "1.0");
2919}
2920
2921// Tests comparing numbers close to 0.
2922//
2923// This ensures that *_DOUBLE_EQ handles the sign correctly and no
2924// overflow occurs when comparing numbers whose absolute value is very
2925// small.
2926TEST_F(DoubleTest, AlmostZeros) {
2927  // In C++Builder, names within local classes (such as used by
2928  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2929  // scoping class.  Use a static local alias as a workaround.
2930  // We use the assignment syntax since some compilers, like Sun Studio,
2931  // don't allow initializing references using construction syntax
2932  // (parentheses).
2933  static const DoubleTest::TestValues& v = this->values_;
2934
2935  EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2936  EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2937  EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2938
2939  EXPECT_FATAL_FAILURE({  // NOLINT
2940    ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2941                     v.further_from_negative_zero);
2942  }, "v.further_from_negative_zero");
2943}
2944
2945// Tests comparing numbers close to each other.
2946TEST_F(DoubleTest, SmallDiff) {
2947  EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2948  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2949                          "values_.further_from_one");
2950}
2951
2952// Tests comparing numbers far apart.
2953TEST_F(DoubleTest, LargeDiff) {
2954  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2955                          "3.0");
2956}
2957
2958// Tests comparing with infinity.
2959//
2960// This ensures that no overflow occurs when comparing numbers whose
2961// absolute value is very large.
2962TEST_F(DoubleTest, Infinity) {
2963  EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
2964  EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
2965#if !GTEST_OS_SYMBIAN
2966  // Nokia's STLport crashes if we try to output infinity or NaN.
2967  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
2968                          "-values_.infinity");
2969
2970  // This is interesting as the representations of infinity_ and nan1_
2971  // are only 1 DLP apart.
2972  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
2973                          "values_.nan1");
2974#endif  // !GTEST_OS_SYMBIAN
2975}
2976
2977// Tests that comparing with NAN always returns false.
2978TEST_F(DoubleTest, NaN) {
2979#if !GTEST_OS_SYMBIAN
2980  // In C++Builder, names within local classes (such as used by
2981  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2982  // scoping class.  Use a static local alias as a workaround.
2983  // We use the assignment syntax since some compilers, like Sun Studio,
2984  // don't allow initializing references using construction syntax
2985  // (parentheses).
2986  static const DoubleTest::TestValues& v = this->values_;
2987
2988  // Nokia's STLport crashes if we try to output infinity or NaN.
2989  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
2990                          "v.nan1");
2991  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
2992  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
2993  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
2994                       "v.infinity");
2995#endif  // !GTEST_OS_SYMBIAN
2996}
2997
2998// Tests that *_DOUBLE_EQ are reflexive.
2999TEST_F(DoubleTest, Reflexive) {
3000  EXPECT_DOUBLE_EQ(0.0, 0.0);
3001  EXPECT_DOUBLE_EQ(1.0, 1.0);
3002#if !GTEST_OS_SYMBIAN
3003  // Nokia's STLport crashes if we try to output infinity or NaN.
3004  ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
3005#endif  // !GTEST_OS_SYMBIAN
3006}
3007
3008// Tests that *_DOUBLE_EQ are commutative.
3009TEST_F(DoubleTest, Commutative) {
3010  // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3011  EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
3012
3013  // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3014  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3015                          "1.0");
3016}
3017
3018// Tests EXPECT_NEAR.
3019TEST_F(DoubleTest, EXPECT_NEAR) {
3020  EXPECT_NEAR(-1.0, -1.1, 0.2);
3021  EXPECT_NEAR(2.0, 3.0, 1.0);
3022  EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25),  // NOLINT
3023                          "The difference between 1.0 and 1.5 is 0.5, "
3024                          "which exceeds 0.25");
3025  // To work around a bug in gcc 2.95.0, there is intentionally no
3026  // space after the first comma in the previous statement.
3027}
3028
3029// Tests ASSERT_NEAR.
3030TEST_F(DoubleTest, ASSERT_NEAR) {
3031  ASSERT_NEAR(-1.0, -1.1, 0.2);
3032  ASSERT_NEAR(2.0, 3.0, 1.0);
3033  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25),  // NOLINT
3034                       "The difference between 1.0 and 1.5 is 0.5, "
3035                       "which exceeds 0.25");
3036  // To work around a bug in gcc 2.95.0, there is intentionally no
3037  // space after the first comma in the previous statement.
3038}
3039
3040// Tests the cases where DoubleLE() should succeed.
3041TEST_F(DoubleTest, DoubleLESucceeds) {
3042  EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0);  // When val1 < val2,
3043  ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0);  // val1 == val2,
3044
3045  // or when val1 is greater than, but almost equals to, val2.
3046  EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3047}
3048
3049// Tests the cases where DoubleLE() should fail.
3050TEST_F(DoubleTest, DoubleLEFails) {
3051  // When val1 is greater than val2 by a large margin,
3052  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
3053                          "(2.0) <= (1.0)");
3054
3055  // or by a small yet non-negligible margin,
3056  EXPECT_NONFATAL_FAILURE({  // NOLINT
3057    EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3058  }, "(values_.further_from_one) <= (1.0)");
3059
3060#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3061  // Nokia's STLport crashes if we try to output infinity or NaN.
3062  // C++Builder gives bad results for ordered comparisons involving NaNs
3063  // due to compiler bugs.
3064  EXPECT_NONFATAL_FAILURE({  // NOLINT
3065    EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3066  }, "(values_.nan1) <= (values_.infinity)");
3067  EXPECT_NONFATAL_FAILURE({  // NOLINT
3068    EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3069  }, " (-values_.infinity) <= (values_.nan1)");
3070  EXPECT_FATAL_FAILURE({  // NOLINT
3071    ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3072  }, "(values_.nan1) <= (values_.nan1)");
3073#endif  // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3074}
3075
3076
3077// Verifies that a test or test case whose name starts with DISABLED_ is
3078// not run.
3079
3080// A test whose name starts with DISABLED_.
3081// Should not run.
3082TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3083  FAIL() << "Unexpected failure: Disabled test should not be run.";
3084}
3085
3086// A test whose name does not start with DISABLED_.
3087// Should run.
3088TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3089  EXPECT_EQ(1, 1);
3090}
3091
3092// A test case whose name starts with DISABLED_.
3093// Should not run.
3094TEST(DISABLED_TestCase, TestShouldNotRun) {
3095  FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3096}
3097
3098// A test case and test whose names start with DISABLED_.
3099// Should not run.
3100TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
3101  FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3102}
3103
3104// Check that when all tests in a test case are disabled, SetupTestCase() and
3105// TearDownTestCase() are not called.
3106class DisabledTestsTest : public Test {
3107 protected:
3108  static void SetUpTestCase() {
3109    FAIL() << "Unexpected failure: All tests disabled in test case. "
3110              "SetupTestCase() should not be called.";
3111  }
3112
3113  static void TearDownTestCase() {
3114    FAIL() << "Unexpected failure: All tests disabled in test case. "
3115              "TearDownTestCase() should not be called.";
3116  }
3117};
3118
3119TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3120  FAIL() << "Unexpected failure: Disabled test should not be run.";
3121}
3122
3123TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3124  FAIL() << "Unexpected failure: Disabled test should not be run.";
3125}
3126
3127// Tests that disabled typed tests aren't run.
3128
3129#if GTEST_HAS_TYPED_TEST
3130
3131template <typename T>
3132class TypedTest : public Test {
3133};
3134
3135typedef testing::Types<int, double> NumericTypes;
3136TYPED_TEST_CASE(TypedTest, NumericTypes);
3137
3138TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3139  FAIL() << "Unexpected failure: Disabled typed test should not run.";
3140}
3141
3142template <typename T>
3143class DISABLED_TypedTest : public Test {
3144};
3145
3146TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
3147
3148TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3149  FAIL() << "Unexpected failure: Disabled typed test should not run.";
3150}
3151
3152#endif  // GTEST_HAS_TYPED_TEST
3153
3154// Tests that disabled type-parameterized tests aren't run.
3155
3156#if GTEST_HAS_TYPED_TEST_P
3157
3158template <typename T>
3159class TypedTestP : public Test {
3160};
3161
3162TYPED_TEST_CASE_P(TypedTestP);
3163
3164TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3165  FAIL() << "Unexpected failure: "
3166         << "Disabled type-parameterized test should not run.";
3167}
3168
3169REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
3170
3171INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
3172
3173template <typename T>
3174class DISABLED_TypedTestP : public Test {
3175};
3176
3177TYPED_TEST_CASE_P(DISABLED_TypedTestP);
3178
3179TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3180  FAIL() << "Unexpected failure: "
3181         << "Disabled type-parameterized test should not run.";
3182}
3183
3184REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
3185
3186INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
3187
3188#endif  // GTEST_HAS_TYPED_TEST_P
3189
3190// Tests that assertion macros evaluate their arguments exactly once.
3191
3192class SingleEvaluationTest : public Test {
3193 public:  // Must be public and not protected due to a bug in g++ 3.4.2.
3194  // This helper function is needed by the FailedASSERT_STREQ test
3195  // below.  It's public to work around C++Builder's bug with scoping local
3196  // classes.
3197  static void CompareAndIncrementCharPtrs() {
3198    ASSERT_STREQ(p1_++, p2_++);
3199  }
3200
3201  // This helper function is needed by the FailedASSERT_NE test below.  It's
3202  // public to work around C++Builder's bug with scoping local classes.
3203  static void CompareAndIncrementInts() {
3204    ASSERT_NE(a_++, b_++);
3205  }
3206
3207 protected:
3208  SingleEvaluationTest() {
3209    p1_ = s1_;
3210    p2_ = s2_;
3211    a_ = 0;
3212    b_ = 0;
3213  }
3214
3215  static const char* const s1_;
3216  static const char* const s2_;
3217  static const char* p1_;
3218  static const char* p2_;
3219
3220  static int a_;
3221  static int b_;
3222};
3223
3224const char* const SingleEvaluationTest::s1_ = "01234";
3225const char* const SingleEvaluationTest::s2_ = "abcde";
3226const char* SingleEvaluationTest::p1_;
3227const char* SingleEvaluationTest::p2_;
3228int SingleEvaluationTest::a_;
3229int SingleEvaluationTest::b_;
3230
3231// Tests that when ASSERT_STREQ fails, it evaluates its arguments
3232// exactly once.
3233TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3234  EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3235                       "p2_++");
3236  EXPECT_EQ(s1_ + 1, p1_);
3237  EXPECT_EQ(s2_ + 1, p2_);
3238}
3239
3240// Tests that string assertion arguments are evaluated exactly once.
3241TEST_F(SingleEvaluationTest, ASSERT_STR) {
3242  // successful EXPECT_STRNE
3243  EXPECT_STRNE(p1_++, p2_++);
3244  EXPECT_EQ(s1_ + 1, p1_);
3245  EXPECT_EQ(s2_ + 1, p2_);
3246
3247  // failed EXPECT_STRCASEEQ
3248  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3249                          "ignoring case");
3250  EXPECT_EQ(s1_ + 2, p1_);
3251  EXPECT_EQ(s2_ + 2, p2_);
3252}
3253
3254// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3255// once.
3256TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3257  EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3258                       "(a_++) != (b_++)");
3259  EXPECT_EQ(1, a_);
3260  EXPECT_EQ(1, b_);
3261}
3262
3263// Tests that assertion arguments are evaluated exactly once.
3264TEST_F(SingleEvaluationTest, OtherCases) {
3265  // successful EXPECT_TRUE
3266  EXPECT_TRUE(0 == a_++);  // NOLINT
3267  EXPECT_EQ(1, a_);
3268
3269  // failed EXPECT_TRUE
3270  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3271  EXPECT_EQ(2, a_);
3272
3273  // successful EXPECT_GT
3274  EXPECT_GT(a_++, b_++);
3275  EXPECT_EQ(3, a_);
3276  EXPECT_EQ(1, b_);
3277
3278  // failed EXPECT_LT
3279  EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3280  EXPECT_EQ(4, a_);
3281  EXPECT_EQ(2, b_);
3282
3283  // successful ASSERT_TRUE
3284  ASSERT_TRUE(0 < a_++);  // NOLINT
3285  EXPECT_EQ(5, a_);
3286
3287  // successful ASSERT_GT
3288  ASSERT_GT(a_++, b_++);
3289  EXPECT_EQ(6, a_);
3290  EXPECT_EQ(3, b_);
3291}
3292
3293#if GTEST_HAS_EXCEPTIONS
3294
3295void ThrowAnInteger() {
3296  throw 1;
3297}
3298
3299// Tests that assertion arguments are evaluated exactly once.
3300TEST_F(SingleEvaluationTest, ExceptionTests) {
3301  // successful EXPECT_THROW
3302  EXPECT_THROW({  // NOLINT
3303    a_++;
3304    ThrowAnInteger();
3305  }, int);
3306  EXPECT_EQ(1, a_);
3307
3308  // failed EXPECT_THROW, throws different
3309  EXPECT_NONFATAL_FAILURE(EXPECT_THROW({  // NOLINT
3310    a_++;
3311    ThrowAnInteger();
3312  }, bool), "throws a different type");
3313  EXPECT_EQ(2, a_);
3314
3315  // failed EXPECT_THROW, throws nothing
3316  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3317  EXPECT_EQ(3, a_);
3318
3319  // successful EXPECT_NO_THROW
3320  EXPECT_NO_THROW(a_++);
3321  EXPECT_EQ(4, a_);
3322
3323  // failed EXPECT_NO_THROW
3324  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({  // NOLINT
3325    a_++;
3326    ThrowAnInteger();
3327  }), "it throws");
3328  EXPECT_EQ(5, a_);
3329
3330  // successful EXPECT_ANY_THROW
3331  EXPECT_ANY_THROW({  // NOLINT
3332    a_++;
3333    ThrowAnInteger();
3334  });
3335  EXPECT_EQ(6, a_);
3336
3337  // failed EXPECT_ANY_THROW
3338  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3339  EXPECT_EQ(7, a_);
3340}
3341
3342#endif  // GTEST_HAS_EXCEPTIONS
3343
3344// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3345class NoFatalFailureTest : public Test {
3346 protected:
3347  void Succeeds() {}
3348  void FailsNonFatal() {
3349    ADD_FAILURE() << "some non-fatal failure";
3350  }
3351  void Fails() {
3352    FAIL() << "some fatal failure";
3353  }
3354
3355  void DoAssertNoFatalFailureOnFails() {
3356    ASSERT_NO_FATAL_FAILURE(Fails());
3357    ADD_FAILURE() << "shold not reach here.";
3358  }
3359
3360  void DoExpectNoFatalFailureOnFails() {
3361    EXPECT_NO_FATAL_FAILURE(Fails());
3362    ADD_FAILURE() << "other failure";
3363  }
3364};
3365
3366TEST_F(NoFatalFailureTest, NoFailure) {
3367  EXPECT_NO_FATAL_FAILURE(Succeeds());
3368  ASSERT_NO_FATAL_FAILURE(Succeeds());
3369}
3370
3371TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3372  EXPECT_NONFATAL_FAILURE(
3373      EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3374      "some non-fatal failure");
3375  EXPECT_NONFATAL_FAILURE(
3376      ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3377      "some non-fatal failure");
3378}
3379
3380TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3381  TestPartResultArray gtest_failures;
3382  {
3383    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3384    DoAssertNoFatalFailureOnFails();
3385  }
3386  ASSERT_EQ(2, gtest_failures.size());
3387  EXPECT_EQ(TestPartResult::kFatalFailure,
3388            gtest_failures.GetTestPartResult(0).type());
3389  EXPECT_EQ(TestPartResult::kFatalFailure,
3390            gtest_failures.GetTestPartResult(1).type());
3391  EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3392                      gtest_failures.GetTestPartResult(0).message());
3393  EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3394                      gtest_failures.GetTestPartResult(1).message());
3395}
3396
3397TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3398  TestPartResultArray gtest_failures;
3399  {
3400    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3401    DoExpectNoFatalFailureOnFails();
3402  }
3403  ASSERT_EQ(3, gtest_failures.size());
3404  EXPECT_EQ(TestPartResult::kFatalFailure,
3405            gtest_failures.GetTestPartResult(0).type());
3406  EXPECT_EQ(TestPartResult::kNonFatalFailure,
3407            gtest_failures.GetTestPartResult(1).type());
3408  EXPECT_EQ(TestPartResult::kNonFatalFailure,
3409            gtest_failures.GetTestPartResult(2).type());
3410  EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3411                      gtest_failures.GetTestPartResult(0).message());
3412  EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3413                      gtest_failures.GetTestPartResult(1).message());
3414  EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3415                      gtest_failures.GetTestPartResult(2).message());
3416}
3417
3418TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3419  TestPartResultArray gtest_failures;
3420  {
3421    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3422    EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3423  }
3424  ASSERT_EQ(2, gtest_failures.size());
3425  EXPECT_EQ(TestPartResult::kNonFatalFailure,
3426            gtest_failures.GetTestPartResult(0).type());
3427  EXPECT_EQ(TestPartResult::kNonFatalFailure,
3428            gtest_failures.GetTestPartResult(1).type());
3429  EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3430                      gtest_failures.GetTestPartResult(0).message());
3431  EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3432                      gtest_failures.GetTestPartResult(1).message());
3433}
3434
3435// Tests non-string assertions.
3436
3437std::string EditsToString(const std::vector<EditType>& edits) {
3438  std::string out;
3439  for (size_t i = 0; i < edits.size(); ++i) {
3440    static const char kEdits[] = " +-/";
3441    out.append(1, kEdits[edits[i]]);
3442  }
3443  return out;
3444}
3445
3446std::vector<size_t> CharsToIndices(const std::string& str) {
3447  std::vector<size_t> out;
3448  for (size_t i = 0; i < str.size(); ++i) {
3449    out.push_back(str[i]);
3450  }
3451  return out;
3452}
3453
3454std::vector<std::string> CharsToLines(const std::string& str) {
3455  std::vector<std::string> out;
3456  for (size_t i = 0; i < str.size(); ++i) {
3457    out.push_back(str.substr(i, 1));
3458  }
3459  return out;
3460}
3461
3462TEST(EditDistance, TestCases) {
3463  struct Case {
3464    int line;
3465    const char* left;
3466    const char* right;
3467    const char* expected_edits;
3468    const char* expected_diff;
3469  };
3470  static const Case kCases[] = {
3471      // No change.
3472      {__LINE__, "A", "A", " ", ""},
3473      {__LINE__, "ABCDE", "ABCDE", "     ", ""},
3474      // Simple adds.
3475      {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
3476      {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
3477      // Simple removes.
3478      {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
3479      {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
3480      // Simple replaces.
3481      {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
3482      {__LINE__, "ABCD", "abcd", "////",
3483       "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
3484      // Path finding.
3485      {__LINE__, "ABCDEFGH", "ABXEGH1", "  -/ -  +",
3486       "@@ -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"},
3487      {__LINE__, "AAAABCCCC", "ABABCDCDC", "- /   + / ",
3488       "@@ -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"},
3489      {__LINE__, "ABCDE", "BCDCD", "-   +/",
3490       "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
3491      {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++     --   ++",
3492       "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
3493       "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
3494      {}};
3495  for (const Case* c = kCases; c->left; ++c) {
3496    EXPECT_TRUE(c->expected_edits ==
3497                EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3498                                                    CharsToIndices(c->right))))
3499        << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
3500        << EditsToString(CalculateOptimalEdits(
3501               CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
3502    EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
3503                                                      CharsToLines(c->right)))
3504        << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
3505        << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
3506        << ">";
3507  }
3508}
3509
3510// Tests EqFailure(), used for implementing *EQ* assertions.
3511TEST(AssertionTest, EqFailure) {
3512  const std::string foo_val("5"), bar_val("6");
3513  const std::string msg1(
3514      EqFailure("foo", "bar", foo_val, bar_val, false)
3515      .failure_message());
3516  EXPECT_STREQ(
3517      "Value of: bar\n"
3518      "  Actual: 6\n"
3519      "Expected: foo\n"
3520      "Which is: 5",
3521      msg1.c_str());
3522
3523  const std::string msg2(
3524      EqFailure("foo", "6", foo_val, bar_val, false)
3525      .failure_message());
3526  EXPECT_STREQ(
3527      "Value of: 6\n"
3528      "Expected: foo\n"
3529      "Which is: 5",
3530      msg2.c_str());
3531
3532  const std::string msg3(
3533      EqFailure("5", "bar", foo_val, bar_val, false)
3534      .failure_message());
3535  EXPECT_STREQ(
3536      "Value of: bar\n"
3537      "  Actual: 6\n"
3538      "Expected: 5",
3539      msg3.c_str());
3540
3541  const std::string msg4(
3542      EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3543  EXPECT_STREQ(
3544      "Value of: 6\n"
3545      "Expected: 5",
3546      msg4.c_str());
3547
3548  const std::string msg5(
3549      EqFailure("foo", "bar",
3550                std::string("\"x\""), std::string("\"y\""),
3551                true).failure_message());
3552  EXPECT_STREQ(
3553      "Value of: bar\n"
3554      "  Actual: \"y\"\n"
3555      "Expected: foo (ignoring case)\n"
3556      "Which is: \"x\"",
3557      msg5.c_str());
3558}
3559
3560TEST(AssertionTest, EqFailureWithDiff) {
3561  const std::string left(
3562      "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
3563  const std::string right(
3564      "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
3565  const std::string msg1(
3566      EqFailure("left", "right", left, right, false).failure_message());
3567  EXPECT_STREQ(
3568      "Value of: right\n"
3569      "  Actual: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3570      "Expected: left\n"
3571      "Which is: "
3572      "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3573      "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
3574      "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
3575      msg1.c_str());
3576}
3577
3578// Tests AppendUserMessage(), used for implementing the *EQ* macros.
3579TEST(AssertionTest, AppendUserMessage) {
3580  const std::string foo("foo");
3581
3582  Message msg;
3583  EXPECT_STREQ("foo",
3584               AppendUserMessage(foo, msg).c_str());
3585
3586  msg << "bar";
3587  EXPECT_STREQ("foo\nbar",
3588               AppendUserMessage(foo, msg).c_str());
3589}
3590
3591#ifdef __BORLANDC__
3592// Silences warnings: "Condition is always true", "Unreachable code"
3593# pragma option push -w-ccc -w-rch
3594#endif
3595
3596// Tests ASSERT_TRUE.
3597TEST(AssertionTest, ASSERT_TRUE) {
3598  ASSERT_TRUE(2 > 1);  // NOLINT
3599  EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3600                       "2 < 1");
3601}
3602
3603// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3604TEST(AssertionTest, AssertTrueWithAssertionResult) {
3605  ASSERT_TRUE(ResultIsEven(2));
3606#ifndef __BORLANDC__
3607  // ICE's in C++Builder.
3608  EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3609                       "Value of: ResultIsEven(3)\n"
3610                       "  Actual: false (3 is odd)\n"
3611                       "Expected: true");
3612#endif
3613  ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3614  EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3615                       "Value of: ResultIsEvenNoExplanation(3)\n"
3616                       "  Actual: false (3 is odd)\n"
3617                       "Expected: true");
3618}
3619
3620// Tests ASSERT_FALSE.
3621TEST(AssertionTest, ASSERT_FALSE) {
3622  ASSERT_FALSE(2 < 1);  // NOLINT
3623  EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3624                       "Value of: 2 > 1\n"
3625                       "  Actual: true\n"
3626                       "Expected: false");
3627}
3628
3629// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3630TEST(AssertionTest, AssertFalseWithAssertionResult) {
3631  ASSERT_FALSE(ResultIsEven(3));
3632#ifndef __BORLANDC__
3633  // ICE's in C++Builder.
3634  EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3635                       "Value of: ResultIsEven(2)\n"
3636                       "  Actual: true (2 is even)\n"
3637                       "Expected: false");
3638#endif
3639  ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3640  EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3641                       "Value of: ResultIsEvenNoExplanation(2)\n"
3642                       "  Actual: true\n"
3643                       "Expected: false");
3644}
3645
3646#ifdef __BORLANDC__
3647// Restores warnings after previous "#pragma option push" supressed them
3648# pragma option pop
3649#endif
3650
3651// Tests using ASSERT_EQ on double values.  The purpose is to make
3652// sure that the specialization we did for integer and anonymous enums
3653// isn't used for double arguments.
3654TEST(ExpectTest, ASSERT_EQ_Double) {
3655  // A success.
3656  ASSERT_EQ(5.6, 5.6);
3657
3658  // A failure.
3659  EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3660                       "5.1");
3661}
3662
3663// Tests ASSERT_EQ.
3664TEST(AssertionTest, ASSERT_EQ) {
3665  ASSERT_EQ(5, 2 + 3);
3666  EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3667                       "Value of: 2*3\n"
3668                       "  Actual: 6\n"
3669                       "Expected: 5");
3670}
3671
3672// Tests ASSERT_EQ(NULL, pointer).
3673#if GTEST_CAN_COMPARE_NULL
3674TEST(AssertionTest, ASSERT_EQ_NULL) {
3675  // A success.
3676  const char* p = NULL;
3677  // Some older GCC versions may issue a spurious waring in this or the next
3678  // assertion statement. This warning should not be suppressed with
3679  // static_cast since the test verifies the ability to use bare NULL as the
3680  // expected parameter to the macro.
3681  ASSERT_EQ(NULL, p);
3682
3683  // A failure.
3684  static int n = 0;
3685  EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3686                       "Value of: &n\n");
3687}
3688#endif  // GTEST_CAN_COMPARE_NULL
3689
3690// Tests ASSERT_EQ(0, non_pointer).  Since the literal 0 can be
3691// treated as a null pointer by the compiler, we need to make sure
3692// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3693// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3694TEST(ExpectTest, ASSERT_EQ_0) {
3695  int n = 0;
3696
3697  // A success.
3698  ASSERT_EQ(0, n);
3699
3700  // A failure.
3701  EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3702                       "Expected: 0");
3703}
3704
3705// Tests ASSERT_NE.
3706TEST(AssertionTest, ASSERT_NE) {
3707  ASSERT_NE(6, 7);
3708  EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3709                       "Expected: ('a') != ('a'), "
3710                       "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3711}
3712
3713// Tests ASSERT_LE.
3714TEST(AssertionTest, ASSERT_LE) {
3715  ASSERT_LE(2, 3);
3716  ASSERT_LE(2, 2);
3717  EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3718                       "Expected: (2) <= (0), actual: 2 vs 0");
3719}
3720
3721// Tests ASSERT_LT.
3722TEST(AssertionTest, ASSERT_LT) {
3723  ASSERT_LT(2, 3);
3724  EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3725                       "Expected: (2) < (2), actual: 2 vs 2");
3726}
3727
3728// Tests ASSERT_GE.
3729TEST(AssertionTest, ASSERT_GE) {
3730  ASSERT_GE(2, 1);
3731  ASSERT_GE(2, 2);
3732  EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3733                       "Expected: (2) >= (3), actual: 2 vs 3");
3734}
3735
3736// Tests ASSERT_GT.
3737TEST(AssertionTest, ASSERT_GT) {
3738  ASSERT_GT(2, 1);
3739  EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3740                       "Expected: (2) > (2), actual: 2 vs 2");
3741}
3742
3743#if GTEST_HAS_EXCEPTIONS
3744
3745void ThrowNothing() {}
3746
3747// Tests ASSERT_THROW.
3748TEST(AssertionTest, ASSERT_THROW) {
3749  ASSERT_THROW(ThrowAnInteger(), int);
3750
3751# ifndef __BORLANDC__
3752
3753  // ICE's in C++Builder 2007 and 2009.
3754  EXPECT_FATAL_FAILURE(
3755      ASSERT_THROW(ThrowAnInteger(), bool),
3756      "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3757      "  Actual: it throws a different type.");
3758# endif
3759
3760  EXPECT_FATAL_FAILURE(
3761      ASSERT_THROW(ThrowNothing(), bool),
3762      "Expected: ThrowNothing() throws an exception of type bool.\n"
3763      "  Actual: it throws nothing.");
3764}
3765
3766// Tests ASSERT_NO_THROW.
3767TEST(AssertionTest, ASSERT_NO_THROW) {
3768  ASSERT_NO_THROW(ThrowNothing());
3769  EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3770                       "Expected: ThrowAnInteger() doesn't throw an exception."
3771                       "\n  Actual: it throws.");
3772}
3773
3774// Tests ASSERT_ANY_THROW.
3775TEST(AssertionTest, ASSERT_ANY_THROW) {
3776  ASSERT_ANY_THROW(ThrowAnInteger());
3777  EXPECT_FATAL_FAILURE(
3778      ASSERT_ANY_THROW(ThrowNothing()),
3779      "Expected: ThrowNothing() throws an exception.\n"
3780      "  Actual: it doesn't.");
3781}
3782
3783#endif  // GTEST_HAS_EXCEPTIONS
3784
3785// Makes sure we deal with the precedence of <<.  This test should
3786// compile.
3787TEST(AssertionTest, AssertPrecedence) {
3788  ASSERT_EQ(1 < 2, true);
3789  bool false_value = false;
3790  ASSERT_EQ(true && false_value, false);
3791}
3792
3793// A subroutine used by the following test.
3794void TestEq1(int x) {
3795  ASSERT_EQ(1, x);
3796}
3797
3798// Tests calling a test subroutine that's not part of a fixture.
3799TEST(AssertionTest, NonFixtureSubroutine) {
3800  EXPECT_FATAL_FAILURE(TestEq1(2),
3801                       "Value of: x");
3802}
3803
3804// An uncopyable class.
3805class Uncopyable {
3806 public:
3807  explicit Uncopyable(int a_value) : value_(a_value) {}
3808
3809  int value() const { return value_; }
3810  bool operator==(const Uncopyable& rhs) const {
3811    return value() == rhs.value();
3812  }
3813 private:
3814  // This constructor deliberately has no implementation, as we don't
3815  // want this class to be copyable.
3816  Uncopyable(const Uncopyable&);  // NOLINT
3817
3818  int value_;
3819};
3820
3821::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3822  return os << value.value();
3823}
3824
3825
3826bool IsPositiveUncopyable(const Uncopyable& x) {
3827  return x.value() > 0;
3828}
3829
3830// A subroutine used by the following test.
3831void TestAssertNonPositive() {
3832  Uncopyable y(-1);
3833  ASSERT_PRED1(IsPositiveUncopyable, y);
3834}
3835// A subroutine used by the following test.
3836void TestAssertEqualsUncopyable() {
3837  Uncopyable x(5);
3838  Uncopyable y(-1);
3839  ASSERT_EQ(x, y);
3840}
3841
3842// Tests that uncopyable objects can be used in assertions.
3843TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3844  Uncopyable x(5);
3845  ASSERT_PRED1(IsPositiveUncopyable, x);
3846  ASSERT_EQ(x, x);
3847  EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3848    "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3849  EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3850    "Value of: y\n  Actual: -1\nExpected: x\nWhich is: 5");
3851}
3852
3853// Tests that uncopyable objects can be used in expects.
3854TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3855  Uncopyable x(5);
3856  EXPECT_PRED1(IsPositiveUncopyable, x);
3857  Uncopyable y(-1);
3858  EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3859    "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3860  EXPECT_EQ(x, x);
3861  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3862    "Value of: y\n  Actual: -1\nExpected: x\nWhich is: 5");
3863}
3864
3865enum NamedEnum {
3866  kE1 = 0,
3867  kE2 = 1
3868};
3869
3870TEST(AssertionTest, NamedEnum) {
3871  EXPECT_EQ(kE1, kE1);
3872  EXPECT_LT(kE1, kE2);
3873  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3874  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1");
3875}
3876
3877// The version of gcc used in XCode 2.2 has a bug and doesn't allow
3878// anonymous enums in assertions.  Therefore the following test is not
3879// done on Mac.
3880// Sun Studio and HP aCC also reject this code.
3881#if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3882
3883// Tests using assertions with anonymous enums.
3884enum {
3885  kCaseA = -1,
3886
3887# if GTEST_OS_LINUX
3888
3889  // We want to test the case where the size of the anonymous enum is
3890  // larger than sizeof(int), to make sure our implementation of the
3891  // assertions doesn't truncate the enums.  However, MSVC
3892  // (incorrectly) doesn't allow an enum value to exceed the range of
3893  // an int, so this has to be conditionally compiled.
3894  //
3895  // On Linux, kCaseB and kCaseA have the same value when truncated to
3896  // int size.  We want to test whether this will confuse the
3897  // assertions.
3898  kCaseB = testing::internal::kMaxBiggestInt,
3899
3900# else
3901
3902  kCaseB = INT_MAX,
3903
3904# endif  // GTEST_OS_LINUX
3905
3906  kCaseC = 42
3907};
3908
3909TEST(AssertionTest, AnonymousEnum) {
3910# if GTEST_OS_LINUX
3911
3912  EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
3913
3914# endif  // GTEST_OS_LINUX
3915
3916  EXPECT_EQ(kCaseA, kCaseA);
3917  EXPECT_NE(kCaseA, kCaseB);
3918  EXPECT_LT(kCaseA, kCaseB);
3919  EXPECT_LE(kCaseA, kCaseB);
3920  EXPECT_GT(kCaseB, kCaseA);
3921  EXPECT_GE(kCaseA, kCaseA);
3922  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
3923                          "(kCaseA) >= (kCaseB)");
3924  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
3925                          "-1 vs 42");
3926
3927  ASSERT_EQ(kCaseA, kCaseA);
3928  ASSERT_NE(kCaseA, kCaseB);
3929  ASSERT_LT(kCaseA, kCaseB);
3930  ASSERT_LE(kCaseA, kCaseB);
3931  ASSERT_GT(kCaseB, kCaseA);
3932  ASSERT_GE(kCaseA, kCaseA);
3933
3934# ifndef __BORLANDC__
3935
3936  // ICE's in C++Builder.
3937  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
3938                       "Value of: kCaseB");
3939  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3940                       "Actual: 42");
3941# endif
3942
3943  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3944                       "Which is: -1");
3945}
3946
3947#endif  // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
3948
3949#if GTEST_OS_WINDOWS
3950
3951static HRESULT UnexpectedHRESULTFailure() {
3952  return E_UNEXPECTED;
3953}
3954
3955static HRESULT OkHRESULTSuccess() {
3956  return S_OK;
3957}
3958
3959static HRESULT FalseHRESULTSuccess() {
3960  return S_FALSE;
3961}
3962
3963// HRESULT assertion tests test both zero and non-zero
3964// success codes as well as failure message for each.
3965//
3966// Windows CE doesn't support message texts.
3967TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3968  EXPECT_HRESULT_SUCCEEDED(S_OK);
3969  EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3970
3971  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3972    "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3973    "  Actual: 0x8000FFFF");
3974}
3975
3976TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3977  ASSERT_HRESULT_SUCCEEDED(S_OK);
3978  ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3979
3980  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3981    "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3982    "  Actual: 0x8000FFFF");
3983}
3984
3985TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
3986  EXPECT_HRESULT_FAILED(E_UNEXPECTED);
3987
3988  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
3989    "Expected: (OkHRESULTSuccess()) fails.\n"
3990    "  Actual: 0x0");
3991  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
3992    "Expected: (FalseHRESULTSuccess()) fails.\n"
3993    "  Actual: 0x1");
3994}
3995
3996TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
3997  ASSERT_HRESULT_FAILED(E_UNEXPECTED);
3998
3999# ifndef __BORLANDC__
4000
4001  // ICE's in C++Builder 2007 and 2009.
4002  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4003    "Expected: (OkHRESULTSuccess()) fails.\n"
4004    "  Actual: 0x0");
4005# endif
4006
4007  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4008    "Expected: (FalseHRESULTSuccess()) fails.\n"
4009    "  Actual: 0x1");
4010}
4011
4012// Tests that streaming to the HRESULT macros works.
4013TEST(HRESULTAssertionTest, Streaming) {
4014  EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4015  ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4016  EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4017  ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4018
4019  EXPECT_NONFATAL_FAILURE(
4020      EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4021      "expected failure");
4022
4023# ifndef __BORLANDC__
4024
4025  // ICE's in C++Builder 2007 and 2009.
4026  EXPECT_FATAL_FAILURE(
4027      ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4028      "expected failure");
4029# endif
4030
4031  EXPECT_NONFATAL_FAILURE(
4032      EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4033      "expected failure");
4034
4035  EXPECT_FATAL_FAILURE(
4036      ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4037      "expected failure");
4038}
4039
4040#endif  // GTEST_OS_WINDOWS
4041
4042#ifdef __BORLANDC__
4043// Silences warnings: "Condition is always true", "Unreachable code"
4044# pragma option push -w-ccc -w-rch
4045#endif
4046
4047// Tests that the assertion macros behave like single statements.
4048TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4049  if (AlwaysFalse())
4050    ASSERT_TRUE(false) << "This should never be executed; "
4051                          "It's a compilation test only.";
4052
4053  if (AlwaysTrue())
4054    EXPECT_FALSE(false);
4055  else
4056    ;  // NOLINT
4057
4058  if (AlwaysFalse())
4059    ASSERT_LT(1, 3);
4060
4061  if (AlwaysFalse())
4062    ;  // NOLINT
4063  else
4064    EXPECT_GT(3, 2) << "";
4065}
4066
4067#if GTEST_HAS_EXCEPTIONS
4068// Tests that the compiler will not complain about unreachable code in the
4069// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4070TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4071  int n = 0;
4072
4073  EXPECT_THROW(throw 1, int);
4074  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4075  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4076  EXPECT_NO_THROW(n++);
4077  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4078  EXPECT_ANY_THROW(throw 1);
4079  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4080}
4081
4082TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4083  if (AlwaysFalse())
4084    EXPECT_THROW(ThrowNothing(), bool);
4085
4086  if (AlwaysTrue())
4087    EXPECT_THROW(ThrowAnInteger(), int);
4088  else
4089    ;  // NOLINT
4090
4091  if (AlwaysFalse())
4092    EXPECT_NO_THROW(ThrowAnInteger());
4093
4094  if (AlwaysTrue())
4095    EXPECT_NO_THROW(ThrowNothing());
4096  else
4097    ;  // NOLINT
4098
4099  if (AlwaysFalse())
4100    EXPECT_ANY_THROW(ThrowNothing());
4101
4102  if (AlwaysTrue())
4103    EXPECT_ANY_THROW(ThrowAnInteger());
4104  else
4105    ;  // NOLINT
4106}
4107#endif  // GTEST_HAS_EXCEPTIONS
4108
4109TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4110  if (AlwaysFalse())
4111    EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4112                                    << "It's a compilation test only.";
4113  else
4114    ;  // NOLINT
4115
4116  if (AlwaysFalse())
4117    ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4118  else
4119    ;  // NOLINT
4120
4121  if (AlwaysTrue())
4122    EXPECT_NO_FATAL_FAILURE(SUCCEED());
4123  else
4124    ;  // NOLINT
4125
4126  if (AlwaysFalse())
4127    ;  // NOLINT
4128  else
4129    ASSERT_NO_FATAL_FAILURE(SUCCEED());
4130}
4131
4132// Tests that the assertion macros work well with switch statements.
4133TEST(AssertionSyntaxTest, WorksWithSwitch) {
4134  switch (0) {
4135    case 1:
4136      break;
4137    default:
4138      ASSERT_TRUE(true);
4139  }
4140
4141  switch (0)
4142    case 0:
4143      EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4144
4145  // Binary assertions are implemented using a different code path
4146  // than the Boolean assertions.  Hence we test them separately.
4147  switch (0) {
4148    case 1:
4149    default:
4150      ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4151  }
4152
4153  switch (0)
4154    case 0:
4155      EXPECT_NE(1, 2);
4156}
4157
4158#if GTEST_HAS_EXCEPTIONS
4159
4160void ThrowAString() {
4161    throw "std::string";
4162}
4163
4164// Test that the exception assertion macros compile and work with const
4165// type qualifier.
4166TEST(AssertionSyntaxTest, WorksWithConst) {
4167    ASSERT_THROW(ThrowAString(), const char*);
4168
4169    EXPECT_THROW(ThrowAString(), const char*);
4170}
4171
4172#endif  // GTEST_HAS_EXCEPTIONS
4173
4174}  // namespace
4175
4176namespace testing {
4177
4178// Tests that Google Test tracks SUCCEED*.
4179TEST(SuccessfulAssertionTest, SUCCEED) {
4180  SUCCEED();
4181  SUCCEED() << "OK";
4182  EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4183}
4184
4185// Tests that Google Test doesn't track successful EXPECT_*.
4186TEST(SuccessfulAssertionTest, EXPECT) {
4187  EXPECT_TRUE(true);
4188  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4189}
4190
4191// Tests that Google Test doesn't track successful EXPECT_STR*.
4192TEST(SuccessfulAssertionTest, EXPECT_STR) {
4193  EXPECT_STREQ("", "");
4194  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4195}
4196
4197// Tests that Google Test doesn't track successful ASSERT_*.
4198TEST(SuccessfulAssertionTest, ASSERT) {
4199  ASSERT_TRUE(true);
4200  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4201}
4202
4203// Tests that Google Test doesn't track successful ASSERT_STR*.
4204TEST(SuccessfulAssertionTest, ASSERT_STR) {
4205  ASSERT_STREQ("", "");
4206  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4207}
4208
4209}  // namespace testing
4210
4211namespace {
4212
4213// Tests the message streaming variation of assertions.
4214
4215TEST(AssertionWithMessageTest, EXPECT) {
4216  EXPECT_EQ(1, 1) << "This should succeed.";
4217  EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4218                          "Expected failure #1");
4219  EXPECT_LE(1, 2) << "This should succeed.";
4220  EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4221                          "Expected failure #2.");
4222  EXPECT_GE(1, 0) << "This should succeed.";
4223  EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4224                          "Expected failure #3.");
4225
4226  EXPECT_STREQ("1", "1") << "This should succeed.";
4227  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4228                          "Expected failure #4.");
4229  EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4230  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4231                          "Expected failure #5.");
4232
4233  EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4234  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4235                          "Expected failure #6.");
4236  EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4237}
4238
4239TEST(AssertionWithMessageTest, ASSERT) {
4240  ASSERT_EQ(1, 1) << "This should succeed.";
4241  ASSERT_NE(1, 2) << "This should succeed.";
4242  ASSERT_LE(1, 2) << "This should succeed.";
4243  ASSERT_LT(1, 2) << "This should succeed.";
4244  ASSERT_GE(1, 0) << "This should succeed.";
4245  EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4246                       "Expected failure.");
4247}
4248
4249TEST(AssertionWithMessageTest, ASSERT_STR) {
4250  ASSERT_STREQ("1", "1") << "This should succeed.";
4251  ASSERT_STRNE("1", "2") << "This should succeed.";
4252  ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4253  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4254                       "Expected failure.");
4255}
4256
4257TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4258  ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4259  ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4260  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.",  // NOLINT
4261                       "Expect failure.");
4262  // To work around a bug in gcc 2.95.0, there is intentionally no
4263  // space after the first comma in the previous statement.
4264}
4265
4266// Tests using ASSERT_FALSE with a streamed message.
4267TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4268  ASSERT_FALSE(false) << "This shouldn't fail.";
4269  EXPECT_FATAL_FAILURE({  // NOLINT
4270    ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4271                       << " evaluates to " << true;
4272  }, "Expected failure");
4273}
4274
4275// Tests using FAIL with a streamed message.
4276TEST(AssertionWithMessageTest, FAIL) {
4277  EXPECT_FATAL_FAILURE(FAIL() << 0,
4278                       "0");
4279}
4280
4281// Tests using SUCCEED with a streamed message.
4282TEST(AssertionWithMessageTest, SUCCEED) {
4283  SUCCEED() << "Success == " << 1;
4284}
4285
4286// Tests using ASSERT_TRUE with a streamed message.
4287TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4288  ASSERT_TRUE(true) << "This should succeed.";
4289  ASSERT_TRUE(true) << true;
4290  EXPECT_FATAL_FAILURE({  // NOLINT
4291    ASSERT_TRUE(false) << static_cast<const char *>(NULL)
4292                       << static_cast<char *>(NULL);
4293  }, "(null)(null)");
4294}
4295
4296#if GTEST_OS_WINDOWS
4297// Tests using wide strings in assertion messages.
4298TEST(AssertionWithMessageTest, WideStringMessage) {
4299  EXPECT_NONFATAL_FAILURE({  // NOLINT
4300    EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4301  }, "This failure is expected.");
4302  EXPECT_FATAL_FAILURE({  // NOLINT
4303    ASSERT_EQ(1, 2) << "This failure is "
4304                    << L"expected too.\x8120";
4305  }, "This failure is expected too.");
4306}
4307#endif  // GTEST_OS_WINDOWS
4308
4309// Tests EXPECT_TRUE.
4310TEST(ExpectTest, EXPECT_TRUE) {
4311  EXPECT_TRUE(true) << "Intentional success";
4312  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4313                          "Intentional failure #1.");
4314  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4315                          "Intentional failure #2.");
4316  EXPECT_TRUE(2 > 1);  // NOLINT
4317  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4318                          "Value of: 2 < 1\n"
4319                          "  Actual: false\n"
4320                          "Expected: true");
4321  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4322                          "2 > 3");
4323}
4324
4325// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4326TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4327  EXPECT_TRUE(ResultIsEven(2));
4328  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4329                          "Value of: ResultIsEven(3)\n"
4330                          "  Actual: false (3 is odd)\n"
4331                          "Expected: true");
4332  EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4333  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4334                          "Value of: ResultIsEvenNoExplanation(3)\n"
4335                          "  Actual: false (3 is odd)\n"
4336                          "Expected: true");
4337}
4338
4339// Tests EXPECT_FALSE with a streamed message.
4340TEST(ExpectTest, EXPECT_FALSE) {
4341  EXPECT_FALSE(2 < 1);  // NOLINT
4342  EXPECT_FALSE(false) << "Intentional success";
4343  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4344                          "Intentional failure #1.");
4345  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4346                          "Intentional failure #2.");
4347  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4348                          "Value of: 2 > 1\n"
4349                          "  Actual: true\n"
4350                          "Expected: false");
4351  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4352                          "2 < 3");
4353}
4354
4355// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4356TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4357  EXPECT_FALSE(ResultIsEven(3));
4358  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4359                          "Value of: ResultIsEven(2)\n"
4360                          "  Actual: true (2 is even)\n"
4361                          "Expected: false");
4362  EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4363  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4364                          "Value of: ResultIsEvenNoExplanation(2)\n"
4365                          "  Actual: true\n"
4366                          "Expected: false");
4367}
4368
4369#ifdef __BORLANDC__
4370// Restores warnings after previous "#pragma option push" supressed them
4371# pragma option pop
4372#endif
4373
4374// Tests EXPECT_EQ.
4375TEST(ExpectTest, EXPECT_EQ) {
4376  EXPECT_EQ(5, 2 + 3);
4377  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4378                          "Value of: 2*3\n"
4379                          "  Actual: 6\n"
4380                          "Expected: 5");
4381  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4382                          "2 - 3");
4383}
4384
4385// Tests using EXPECT_EQ on double values.  The purpose is to make
4386// sure that the specialization we did for integer and anonymous enums
4387// isn't used for double arguments.
4388TEST(ExpectTest, EXPECT_EQ_Double) {
4389  // A success.
4390  EXPECT_EQ(5.6, 5.6);
4391
4392  // A failure.
4393  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4394                          "5.1");
4395}
4396
4397#if GTEST_CAN_COMPARE_NULL
4398// Tests EXPECT_EQ(NULL, pointer).
4399TEST(ExpectTest, EXPECT_EQ_NULL) {
4400  // A success.
4401  const char* p = NULL;
4402  // Some older GCC versions may issue a spurious warning in this or the next
4403  // assertion statement. This warning should not be suppressed with
4404  // static_cast since the test verifies the ability to use bare NULL as the
4405  // expected parameter to the macro.
4406  EXPECT_EQ(NULL, p);
4407
4408  // A failure.
4409  int n = 0;
4410  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
4411                          "Value of: &n\n");
4412}
4413#endif  // GTEST_CAN_COMPARE_NULL
4414
4415// Tests EXPECT_EQ(0, non_pointer).  Since the literal 0 can be
4416// treated as a null pointer by the compiler, we need to make sure
4417// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4418// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4419TEST(ExpectTest, EXPECT_EQ_0) {
4420  int n = 0;
4421
4422  // A success.
4423  EXPECT_EQ(0, n);
4424
4425  // A failure.
4426  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4427                          "Expected: 0");
4428}
4429
4430// Tests EXPECT_NE.
4431TEST(ExpectTest, EXPECT_NE) {
4432  EXPECT_NE(6, 7);
4433
4434  EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4435                          "Expected: ('a') != ('a'), "
4436                          "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4437  EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4438                          "2");
4439  char* const p0 = NULL;
4440  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4441                          "p0");
4442  // Only way to get the Nokia compiler to compile the cast
4443  // is to have a separate void* variable first. Putting
4444  // the two casts on the same line doesn't work, neither does
4445  // a direct C-style to char*.
4446  void* pv1 = (void*)0x1234;  // NOLINT
4447  char* const p1 = reinterpret_cast<char*>(pv1);
4448  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4449                          "p1");
4450}
4451
4452// Tests EXPECT_LE.
4453TEST(ExpectTest, EXPECT_LE) {
4454  EXPECT_LE(2, 3);
4455  EXPECT_LE(2, 2);
4456  EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4457                          "Expected: (2) <= (0), actual: 2 vs 0");
4458  EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4459                          "(1.1) <= (0.9)");
4460}
4461
4462// Tests EXPECT_LT.
4463TEST(ExpectTest, EXPECT_LT) {
4464  EXPECT_LT(2, 3);
4465  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4466                          "Expected: (2) < (2), actual: 2 vs 2");
4467  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4468                          "(2) < (1)");
4469}
4470
4471// Tests EXPECT_GE.
4472TEST(ExpectTest, EXPECT_GE) {
4473  EXPECT_GE(2, 1);
4474  EXPECT_GE(2, 2);
4475  EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4476                          "Expected: (2) >= (3), actual: 2 vs 3");
4477  EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4478                          "(0.9) >= (1.1)");
4479}
4480
4481// Tests EXPECT_GT.
4482TEST(ExpectTest, EXPECT_GT) {
4483  EXPECT_GT(2, 1);
4484  EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4485                          "Expected: (2) > (2), actual: 2 vs 2");
4486  EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4487                          "(2) > (3)");
4488}
4489
4490#if GTEST_HAS_EXCEPTIONS
4491
4492// Tests EXPECT_THROW.
4493TEST(ExpectTest, EXPECT_THROW) {
4494  EXPECT_THROW(ThrowAnInteger(), int);
4495  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4496                          "Expected: ThrowAnInteger() throws an exception of "
4497                          "type bool.\n  Actual: it throws a different type.");
4498  EXPECT_NONFATAL_FAILURE(
4499      EXPECT_THROW(ThrowNothing(), bool),
4500      "Expected: ThrowNothing() throws an exception of type bool.\n"
4501      "  Actual: it throws nothing.");
4502}
4503
4504// Tests EXPECT_NO_THROW.
4505TEST(ExpectTest, EXPECT_NO_THROW) {
4506  EXPECT_NO_THROW(ThrowNothing());
4507  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4508                          "Expected: ThrowAnInteger() doesn't throw an "
4509                          "exception.\n  Actual: it throws.");
4510}
4511
4512// Tests EXPECT_ANY_THROW.
4513TEST(ExpectTest, EXPECT_ANY_THROW) {
4514  EXPECT_ANY_THROW(ThrowAnInteger());
4515  EXPECT_NONFATAL_FAILURE(
4516      EXPECT_ANY_THROW(ThrowNothing()),
4517      "Expected: ThrowNothing() throws an exception.\n"
4518      "  Actual: it doesn't.");
4519}
4520
4521#endif  // GTEST_HAS_EXCEPTIONS
4522
4523// Make sure we deal with the precedence of <<.
4524TEST(ExpectTest, ExpectPrecedence) {
4525  EXPECT_EQ(1 < 2, true);
4526  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4527                          "Value of: true && false");
4528}
4529
4530
4531// Tests the StreamableToString() function.
4532
4533// Tests using StreamableToString() on a scalar.
4534TEST(StreamableToStringTest, Scalar) {
4535  EXPECT_STREQ("5", StreamableToString(5).c_str());
4536}
4537
4538// Tests using StreamableToString() on a non-char pointer.
4539TEST(StreamableToStringTest, Pointer) {
4540  int n = 0;
4541  int* p = &n;
4542  EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4543}
4544
4545// Tests using StreamableToString() on a NULL non-char pointer.
4546TEST(StreamableToStringTest, NullPointer) {
4547  int* p = NULL;
4548  EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4549}
4550
4551// Tests using StreamableToString() on a C string.
4552TEST(StreamableToStringTest, CString) {
4553  EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4554}
4555
4556// Tests using StreamableToString() on a NULL C string.
4557TEST(StreamableToStringTest, NullCString) {
4558  char* p = NULL;
4559  EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4560}
4561
4562// Tests using streamable values as assertion messages.
4563
4564// Tests using std::string as an assertion message.
4565TEST(StreamableTest, string) {
4566  static const std::string str(
4567      "This failure message is a std::string, and is expected.");
4568  EXPECT_FATAL_FAILURE(FAIL() << str,
4569                       str.c_str());
4570}
4571
4572// Tests that we can output strings containing embedded NULs.
4573// Limited to Linux because we can only do this with std::string's.
4574TEST(StreamableTest, stringWithEmbeddedNUL) {
4575  static const char char_array_with_nul[] =
4576      "Here's a NUL\0 and some more string";
4577  static const std::string string_with_nul(char_array_with_nul,
4578                                           sizeof(char_array_with_nul)
4579                                           - 1);  // drops the trailing NUL
4580  EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4581                       "Here's a NUL\\0 and some more string");
4582}
4583
4584// Tests that we can output a NUL char.
4585TEST(StreamableTest, NULChar) {
4586  EXPECT_FATAL_FAILURE({  // NOLINT
4587    FAIL() << "A NUL" << '\0' << " and some more string";
4588  }, "A NUL\\0 and some more string");
4589}
4590
4591// Tests using int as an assertion message.
4592TEST(StreamableTest, int) {
4593  EXPECT_FATAL_FAILURE(FAIL() << 900913,
4594                       "900913");
4595}
4596
4597// Tests using NULL char pointer as an assertion message.
4598//
4599// In MSVC, streaming a NULL char * causes access violation.  Google Test
4600// implemented a workaround (substituting "(null)" for NULL).  This
4601// tests whether the workaround works.
4602TEST(StreamableTest, NullCharPtr) {
4603  EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4604                       "(null)");
4605}
4606
4607// Tests that basic IO manipulators (endl, ends, and flush) can be
4608// streamed to testing::Message.
4609TEST(StreamableTest, BasicIoManip) {
4610  EXPECT_FATAL_FAILURE({  // NOLINT
4611    FAIL() << "Line 1." << std::endl
4612           << "A NUL char " << std::ends << std::flush << " in line 2.";
4613  }, "Line 1.\nA NUL char \\0 in line 2.");
4614}
4615
4616// Tests the macros that haven't been covered so far.
4617
4618void AddFailureHelper(bool* aborted) {
4619  *aborted = true;
4620  ADD_FAILURE() << "Intentional failure.";
4621  *aborted = false;
4622}
4623
4624// Tests ADD_FAILURE.
4625TEST(MacroTest, ADD_FAILURE) {
4626  bool aborted = true;
4627  EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4628                          "Intentional failure.");
4629  EXPECT_FALSE(aborted);
4630}
4631
4632// Tests ADD_FAILURE_AT.
4633TEST(MacroTest, ADD_FAILURE_AT) {
4634  // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4635  // the failure message contains the user-streamed part.
4636  EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4637
4638  // Verifies that the user-streamed part is optional.
4639  EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4640
4641  // Unfortunately, we cannot verify that the failure message contains
4642  // the right file path and line number the same way, as
4643  // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4644  // line number.  Instead, we do that in gtest_output_test_.cc.
4645}
4646
4647// Tests FAIL.
4648TEST(MacroTest, FAIL) {
4649  EXPECT_FATAL_FAILURE(FAIL(),
4650                       "Failed");
4651  EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4652                       "Intentional failure.");
4653}
4654
4655// Tests SUCCEED
4656TEST(MacroTest, SUCCEED) {
4657  SUCCEED();
4658  SUCCEED() << "Explicit success.";
4659}
4660
4661// Tests for EXPECT_EQ() and ASSERT_EQ().
4662//
4663// These tests fail *intentionally*, s.t. the failure messages can be
4664// generated and tested.
4665//
4666// We have different tests for different argument types.
4667
4668// Tests using bool values in {EXPECT|ASSERT}_EQ.
4669TEST(EqAssertionTest, Bool) {
4670  EXPECT_EQ(true,  true);
4671  EXPECT_FATAL_FAILURE({
4672      bool false_value = false;
4673      ASSERT_EQ(false_value, true);
4674    }, "Value of: true");
4675}
4676
4677// Tests using int values in {EXPECT|ASSERT}_EQ.
4678TEST(EqAssertionTest, Int) {
4679  ASSERT_EQ(32, 32);
4680  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4681                          "33");
4682}
4683
4684// Tests using time_t values in {EXPECT|ASSERT}_EQ.
4685TEST(EqAssertionTest, Time_T) {
4686  EXPECT_EQ(static_cast<time_t>(0),
4687            static_cast<time_t>(0));
4688  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4689                                 static_cast<time_t>(1234)),
4690                       "1234");
4691}
4692
4693// Tests using char values in {EXPECT|ASSERT}_EQ.
4694TEST(EqAssertionTest, Char) {
4695  ASSERT_EQ('z', 'z');
4696  const char ch = 'b';
4697  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4698                          "ch");
4699  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4700                          "ch");
4701}
4702
4703// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4704TEST(EqAssertionTest, WideChar) {
4705  EXPECT_EQ(L'b', L'b');
4706
4707  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4708                          "Value of: L'x'\n"
4709                          "  Actual: L'x' (120, 0x78)\n"
4710                          "Expected: L'\0'\n"
4711                          "Which is: L'\0' (0, 0x0)");
4712
4713  static wchar_t wchar;
4714  wchar = L'b';
4715  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4716                          "wchar");
4717  wchar = 0x8119;
4718  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
4719                       "Value of: wchar");
4720}
4721
4722// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4723TEST(EqAssertionTest, StdString) {
4724  // Compares a const char* to an std::string that has identical
4725  // content.
4726  ASSERT_EQ("Test", ::std::string("Test"));
4727
4728  // Compares two identical std::strings.
4729  static const ::std::string str1("A * in the middle");
4730  static const ::std::string str2(str1);
4731  EXPECT_EQ(str1, str2);
4732
4733  // Compares a const char* to an std::string that has different
4734  // content
4735  EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4736                          "\"test\"");
4737
4738  // Compares an std::string to a char* that has different content.
4739  char* const p1 = const_cast<char*>("foo");
4740  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4741                          "p1");
4742
4743  // Compares two std::strings that have different contents, one of
4744  // which having a NUL character in the middle.  This should fail.
4745  static ::std::string str3(str1);
4746  str3.at(2) = '\0';
4747  EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4748                       "Value of: str3\n"
4749                       "  Actual: \"A \\0 in the middle\"");
4750}
4751
4752#if GTEST_HAS_STD_WSTRING
4753
4754// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4755TEST(EqAssertionTest, StdWideString) {
4756  // Compares two identical std::wstrings.
4757  const ::std::wstring wstr1(L"A * in the middle");
4758  const ::std::wstring wstr2(wstr1);
4759  ASSERT_EQ(wstr1, wstr2);
4760
4761  // Compares an std::wstring to a const wchar_t* that has identical
4762  // content.
4763  const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4764  EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4765
4766  // Compares an std::wstring to a const wchar_t* that has different
4767  // content.
4768  const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4769  EXPECT_NONFATAL_FAILURE({  // NOLINT
4770    EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4771  }, "kTestX8120");
4772
4773  // Compares two std::wstrings that have different contents, one of
4774  // which having a NUL character in the middle.
4775  ::std::wstring wstr3(wstr1);
4776  wstr3.at(2) = L'\0';
4777  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4778                          "wstr3");
4779
4780  // Compares a wchar_t* to an std::wstring that has different
4781  // content.
4782  EXPECT_FATAL_FAILURE({  // NOLINT
4783    ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4784  }, "");
4785}
4786
4787#endif  // GTEST_HAS_STD_WSTRING
4788
4789#if GTEST_HAS_GLOBAL_STRING
4790// Tests using ::string values in {EXPECT|ASSERT}_EQ.
4791TEST(EqAssertionTest, GlobalString) {
4792  // Compares a const char* to a ::string that has identical content.
4793  EXPECT_EQ("Test", ::string("Test"));
4794
4795  // Compares two identical ::strings.
4796  const ::string str1("A * in the middle");
4797  const ::string str2(str1);
4798  ASSERT_EQ(str1, str2);
4799
4800  // Compares a ::string to a const char* that has different content.
4801  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4802                          "test");
4803
4804  // Compares two ::strings that have different contents, one of which
4805  // having a NUL character in the middle.
4806  ::string str3(str1);
4807  str3.at(2) = '\0';
4808  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4809                          "str3");
4810
4811  // Compares a ::string to a char* that has different content.
4812  EXPECT_FATAL_FAILURE({  // NOLINT
4813    ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4814  }, "");
4815}
4816
4817#endif  // GTEST_HAS_GLOBAL_STRING
4818
4819#if GTEST_HAS_GLOBAL_WSTRING
4820
4821// Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4822TEST(EqAssertionTest, GlobalWideString) {
4823  // Compares two identical ::wstrings.
4824  static const ::wstring wstr1(L"A * in the middle");
4825  static const ::wstring wstr2(wstr1);
4826  EXPECT_EQ(wstr1, wstr2);
4827
4828  // Compares a const wchar_t* to a ::wstring that has identical content.
4829  const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4830  ASSERT_EQ(kTestX8119, ::wstring(kTestX8119));
4831
4832  // Compares a const wchar_t* to a ::wstring that has different
4833  // content.
4834  const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4835  EXPECT_NONFATAL_FAILURE({  // NOLINT
4836    EXPECT_EQ(kTestX8120, ::wstring(kTestX8119));
4837  }, "Test\\x8119");
4838
4839  // Compares a wchar_t* to a ::wstring that has different content.
4840  wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4841  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4842                          "bar");
4843
4844  // Compares two ::wstrings that have different contents, one of which
4845  // having a NUL character in the middle.
4846  static ::wstring wstr3;
4847  wstr3 = wstr1;
4848  wstr3.at(2) = L'\0';
4849  EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4850                       "wstr3");
4851}
4852
4853#endif  // GTEST_HAS_GLOBAL_WSTRING
4854
4855// Tests using char pointers in {EXPECT|ASSERT}_EQ.
4856TEST(EqAssertionTest, CharPointer) {
4857  char* const p0 = NULL;
4858  // Only way to get the Nokia compiler to compile the cast
4859  // is to have a separate void* variable first. Putting
4860  // the two casts on the same line doesn't work, neither does
4861  // a direct C-style to char*.
4862  void* pv1 = (void*)0x1234;  // NOLINT
4863  void* pv2 = (void*)0xABC0;  // NOLINT
4864  char* const p1 = reinterpret_cast<char*>(pv1);
4865  char* const p2 = reinterpret_cast<char*>(pv2);
4866  ASSERT_EQ(p1, p1);
4867
4868  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4869                          "Value of: p2");
4870  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4871                          "p2");
4872  EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4873                                 reinterpret_cast<char*>(0xABC0)),
4874                       "ABC0");
4875}
4876
4877// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4878TEST(EqAssertionTest, WideCharPointer) {
4879  wchar_t* const p0 = NULL;
4880  // Only way to get the Nokia compiler to compile the cast
4881  // is to have a separate void* variable first. Putting
4882  // the two casts on the same line doesn't work, neither does
4883  // a direct C-style to char*.
4884  void* pv1 = (void*)0x1234;  // NOLINT
4885  void* pv2 = (void*)0xABC0;  // NOLINT
4886  wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4887  wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4888  EXPECT_EQ(p0, p0);
4889
4890  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4891                          "Value of: p2");
4892  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4893                          "p2");
4894  void* pv3 = (void*)0x1234;  // NOLINT
4895  void* pv4 = (void*)0xABC0;  // NOLINT
4896  const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4897  const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4898  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4899                          "p4");
4900}
4901
4902// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4903TEST(EqAssertionTest, OtherPointer) {
4904  ASSERT_EQ(static_cast<const int*>(NULL),
4905            static_cast<const int*>(NULL));
4906  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4907                                 reinterpret_cast<const int*>(0x1234)),
4908                       "0x1234");
4909}
4910
4911// A class that supports binary comparison operators but not streaming.
4912class UnprintableChar {
4913 public:
4914  explicit UnprintableChar(char ch) : char_(ch) {}
4915
4916  bool operator==(const UnprintableChar& rhs) const {
4917    return char_ == rhs.char_;
4918  }
4919  bool operator!=(const UnprintableChar& rhs) const {
4920    return char_ != rhs.char_;
4921  }
4922  bool operator<(const UnprintableChar& rhs) const {
4923    return char_ < rhs.char_;
4924  }
4925  bool operator<=(const UnprintableChar& rhs) const {
4926    return char_ <= rhs.char_;
4927  }
4928  bool operator>(const UnprintableChar& rhs) const {
4929    return char_ > rhs.char_;
4930  }
4931  bool operator>=(const UnprintableChar& rhs) const {
4932    return char_ >= rhs.char_;
4933  }
4934
4935 private:
4936  char char_;
4937};
4938
4939// Tests that ASSERT_EQ() and friends don't require the arguments to
4940// be printable.
4941TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4942  const UnprintableChar x('x'), y('y');
4943  ASSERT_EQ(x, x);
4944  EXPECT_NE(x, y);
4945  ASSERT_LT(x, y);
4946  EXPECT_LE(x, y);
4947  ASSERT_GT(y, x);
4948  EXPECT_GE(x, x);
4949
4950  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
4951  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
4952  EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
4953  EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
4954  EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
4955
4956  // Code tested by EXPECT_FATAL_FAILURE cannot reference local
4957  // variables, so we have to write UnprintableChar('x') instead of x.
4958#ifndef __BORLANDC__
4959  // ICE's in C++Builder.
4960  EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
4961                       "1-byte object <78>");
4962  EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4963                       "1-byte object <78>");
4964#endif
4965  EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4966                       "1-byte object <79>");
4967  EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4968                       "1-byte object <78>");
4969  EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4970                       "1-byte object <79>");
4971}
4972
4973// Tests the FRIEND_TEST macro.
4974
4975// This class has a private member we want to test.  We will test it
4976// both in a TEST and in a TEST_F.
4977class Foo {
4978 public:
4979  Foo() {}
4980
4981 private:
4982  int Bar() const { return 1; }
4983
4984  // Declares the friend tests that can access the private member
4985  // Bar().
4986  FRIEND_TEST(FRIEND_TEST_Test, TEST);
4987  FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4988};
4989
4990// Tests that the FRIEND_TEST declaration allows a TEST to access a
4991// class's private members.  This should compile.
4992TEST(FRIEND_TEST_Test, TEST) {
4993  ASSERT_EQ(1, Foo().Bar());
4994}
4995
4996// The fixture needed to test using FRIEND_TEST with TEST_F.
4997class FRIEND_TEST_Test2 : public Test {
4998 protected:
4999  Foo foo;
5000};
5001
5002// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
5003// class's private members.  This should compile.
5004TEST_F(FRIEND_TEST_Test2, TEST_F) {
5005  ASSERT_EQ(1, foo.Bar());
5006}
5007
5008// Tests the life cycle of Test objects.
5009
5010// The test fixture for testing the life cycle of Test objects.
5011//
5012// This class counts the number of live test objects that uses this
5013// fixture.
5014class TestLifeCycleTest : public Test {
5015 protected:
5016  // Constructor.  Increments the number of test objects that uses
5017  // this fixture.
5018  TestLifeCycleTest() { count_++; }
5019
5020  // Destructor.  Decrements the number of test objects that uses this
5021  // fixture.
5022  ~TestLifeCycleTest() { count_--; }
5023
5024  // Returns the number of live test objects that uses this fixture.
5025  int count() const { return count_; }
5026
5027 private:
5028  static int count_;
5029};
5030
5031int TestLifeCycleTest::count_ = 0;
5032
5033// Tests the life cycle of test objects.
5034TEST_F(TestLifeCycleTest, Test1) {
5035  // There should be only one test object in this test case that's
5036  // currently alive.
5037  ASSERT_EQ(1, count());
5038}
5039
5040// Tests the life cycle of test objects.
5041TEST_F(TestLifeCycleTest, Test2) {
5042  // After Test1 is done and Test2 is started, there should still be
5043  // only one live test object, as the object for Test1 should've been
5044  // deleted.
5045  ASSERT_EQ(1, count());
5046}
5047
5048}  // namespace
5049
5050// Tests that the copy constructor works when it is NOT optimized away by
5051// the compiler.
5052TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5053  // Checks that the copy constructor doesn't try to dereference NULL pointers
5054  // in the source object.
5055  AssertionResult r1 = AssertionSuccess();
5056  AssertionResult r2 = r1;
5057  // The following line is added to prevent the compiler from optimizing
5058  // away the constructor call.
5059  r1 << "abc";
5060
5061  AssertionResult r3 = r1;
5062  EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
5063  EXPECT_STREQ("abc", r1.message());
5064}
5065
5066// Tests that AssertionSuccess and AssertionFailure construct
5067// AssertionResult objects as expected.
5068TEST(AssertionResultTest, ConstructionWorks) {
5069  AssertionResult r1 = AssertionSuccess();
5070  EXPECT_TRUE(r1);
5071  EXPECT_STREQ("", r1.message());
5072
5073  AssertionResult r2 = AssertionSuccess() << "abc";
5074  EXPECT_TRUE(r2);
5075  EXPECT_STREQ("abc", r2.message());
5076
5077  AssertionResult r3 = AssertionFailure();
5078  EXPECT_FALSE(r3);
5079  EXPECT_STREQ("", r3.message());
5080
5081  AssertionResult r4 = AssertionFailure() << "def";
5082  EXPECT_FALSE(r4);
5083  EXPECT_STREQ("def", r4.message());
5084
5085  AssertionResult r5 = AssertionFailure(Message() << "ghi");
5086  EXPECT_FALSE(r5);
5087  EXPECT_STREQ("ghi", r5.message());
5088}
5089
5090// Tests that the negation flips the predicate result but keeps the message.
5091TEST(AssertionResultTest, NegationWorks) {
5092  AssertionResult r1 = AssertionSuccess() << "abc";
5093  EXPECT_FALSE(!r1);
5094  EXPECT_STREQ("abc", (!r1).message());
5095
5096  AssertionResult r2 = AssertionFailure() << "def";
5097  EXPECT_TRUE(!r2);
5098  EXPECT_STREQ("def", (!r2).message());
5099}
5100
5101TEST(AssertionResultTest, StreamingWorks) {
5102  AssertionResult r = AssertionSuccess();
5103  r << "abc" << 'd' << 0 << true;
5104  EXPECT_STREQ("abcd0true", r.message());
5105}
5106
5107TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5108  AssertionResult r = AssertionSuccess();
5109  r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5110  EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5111}
5112
5113// The next test uses explicit conversion operators -- a C++11 feature.
5114#if GTEST_LANG_CXX11
5115
5116TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5117  struct ExplicitlyConvertibleToBool {
5118    explicit operator bool() const { return value; }
5119    bool value;
5120  };
5121  ExplicitlyConvertibleToBool v1 = {false};
5122  ExplicitlyConvertibleToBool v2 = {true};
5123  EXPECT_FALSE(v1);
5124  EXPECT_TRUE(v2);
5125}
5126
5127#endif  // GTEST_LANG_CXX11
5128
5129struct ConvertibleToAssertionResult {
5130  operator AssertionResult() const { return AssertionResult(true); }
5131};
5132
5133TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5134  ConvertibleToAssertionResult obj;
5135  EXPECT_TRUE(obj);
5136}
5137
5138// Tests streaming a user type whose definition and operator << are
5139// both in the global namespace.
5140class Base {
5141 public:
5142  explicit Base(int an_x) : x_(an_x) {}
5143  int x() const { return x_; }
5144 private:
5145  int x_;
5146};
5147std::ostream& operator<<(std::ostream& os,
5148                         const Base& val) {
5149  return os << val.x();
5150}
5151std::ostream& operator<<(std::ostream& os,
5152                         const Base* pointer) {
5153  return os << "(" << pointer->x() << ")";
5154}
5155
5156TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5157  Message msg;
5158  Base a(1);
5159
5160  msg << a << &a;  // Uses ::operator<<.
5161  EXPECT_STREQ("1(1)", msg.GetString().c_str());
5162}
5163
5164// Tests streaming a user type whose definition and operator<< are
5165// both in an unnamed namespace.
5166namespace {
5167class MyTypeInUnnamedNameSpace : public Base {
5168 public:
5169  explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
5170};
5171std::ostream& operator<<(std::ostream& os,
5172                         const MyTypeInUnnamedNameSpace& val) {
5173  return os << val.x();
5174}
5175std::ostream& operator<<(std::ostream& os,
5176                         const MyTypeInUnnamedNameSpace* pointer) {
5177  return os << "(" << pointer->x() << ")";
5178}
5179}  // namespace
5180
5181TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5182  Message msg;
5183  MyTypeInUnnamedNameSpace a(1);
5184
5185  msg << a << &a;  // Uses <unnamed_namespace>::operator<<.
5186  EXPECT_STREQ("1(1)", msg.GetString().c_str());
5187}
5188
5189// Tests streaming a user type whose definition and operator<< are
5190// both in a user namespace.
5191namespace namespace1 {
5192class MyTypeInNameSpace1 : public Base {
5193 public:
5194  explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
5195};
5196std::ostream& operator<<(std::ostream& os,
5197                         const MyTypeInNameSpace1& val) {
5198  return os << val.x();
5199}
5200std::ostream& operator<<(std::ostream& os,
5201                         const MyTypeInNameSpace1* pointer) {
5202  return os << "(" << pointer->x() << ")";
5203}
5204}  // namespace namespace1
5205
5206TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5207  Message msg;
5208  namespace1::MyTypeInNameSpace1 a(1);
5209
5210  msg << a << &a;  // Uses namespace1::operator<<.
5211  EXPECT_STREQ("1(1)", msg.GetString().c_str());
5212}
5213
5214// Tests streaming a user type whose definition is in a user namespace
5215// but whose operator<< is in the global namespace.
5216namespace namespace2 {
5217class MyTypeInNameSpace2 : public ::Base {
5218 public:
5219  explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
5220};
5221}  // namespace namespace2
5222std::ostream& operator<<(std::ostream& os,
5223                         const namespace2::MyTypeInNameSpace2& val) {
5224  return os << val.x();
5225}
5226std::ostream& operator<<(std::ostream& os,
5227                         const namespace2::MyTypeInNameSpace2* pointer) {
5228  return os << "(" << pointer->x() << ")";
5229}
5230
5231TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5232  Message msg;
5233  namespace2::MyTypeInNameSpace2 a(1);
5234
5235  msg << a << &a;  // Uses ::operator<<.
5236  EXPECT_STREQ("1(1)", msg.GetString().c_str());
5237}
5238
5239// Tests streaming NULL pointers to testing::Message.
5240TEST(MessageTest, NullPointers) {
5241  Message msg;
5242  char* const p1 = NULL;
5243  unsigned char* const p2 = NULL;
5244  int* p3 = NULL;
5245  double* p4 = NULL;
5246  bool* p5 = NULL;
5247  Message* p6 = NULL;
5248
5249  msg << p1 << p2 << p3 << p4 << p5 << p6;
5250  ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5251               msg.GetString().c_str());
5252}
5253
5254// Tests streaming wide strings to testing::Message.
5255TEST(MessageTest, WideStrings) {
5256  // Streams a NULL of type const wchar_t*.
5257  const wchar_t* const_wstr = NULL;
5258  EXPECT_STREQ("(null)",
5259               (Message() << const_wstr).GetString().c_str());
5260
5261  // Streams a NULL of type wchar_t*.
5262  wchar_t* wstr = NULL;
5263  EXPECT_STREQ("(null)",
5264               (Message() << wstr).GetString().c_str());
5265
5266  // Streams a non-NULL of type const wchar_t*.
5267  const_wstr = L"abc\x8119";
5268  EXPECT_STREQ("abc\xe8\x84\x99",
5269               (Message() << const_wstr).GetString().c_str());
5270
5271  // Streams a non-NULL of type wchar_t*.
5272  wstr = const_cast<wchar_t*>(const_wstr);
5273  EXPECT_STREQ("abc\xe8\x84\x99",
5274               (Message() << wstr).GetString().c_str());
5275}
5276
5277
5278// This line tests that we can define tests in the testing namespace.
5279namespace testing {
5280
5281// Tests the TestInfo class.
5282
5283class TestInfoTest : public Test {
5284 protected:
5285  static const TestInfo* GetTestInfo(const char* test_name) {
5286    const TestCase* const test_case = GetUnitTestImpl()->
5287        GetTestCase("TestInfoTest", "", NULL, NULL);
5288
5289    for (int i = 0; i < test_case->total_test_count(); ++i) {
5290      const TestInfo* const test_info = test_case->GetTestInfo(i);
5291      if (strcmp(test_name, test_info->name()) == 0)
5292        return test_info;
5293    }
5294    return NULL;
5295  }
5296
5297  static const TestResult* GetTestResult(
5298      const TestInfo* test_info) {
5299    return test_info->result();
5300  }
5301};
5302
5303// Tests TestInfo::test_case_name() and TestInfo::name().
5304TEST_F(TestInfoTest, Names) {
5305  const TestInfo* const test_info = GetTestInfo("Names");
5306
5307  ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
5308  ASSERT_STREQ("Names", test_info->name());
5309}
5310
5311// Tests TestInfo::result().
5312TEST_F(TestInfoTest, result) {
5313  const TestInfo* const test_info = GetTestInfo("result");
5314
5315  // Initially, there is no TestPartResult for this test.
5316  ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5317
5318  // After the previous assertion, there is still none.
5319  ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5320}
5321
5322// Tests setting up and tearing down a test case.
5323
5324class SetUpTestCaseTest : public Test {
5325 protected:
5326  // This will be called once before the first test in this test case
5327  // is run.
5328  static void SetUpTestCase() {
5329    printf("Setting up the test case . . .\n");
5330
5331    // Initializes some shared resource.  In this simple example, we
5332    // just create a C string.  More complex stuff can be done if
5333    // desired.
5334    shared_resource_ = "123";
5335
5336    // Increments the number of test cases that have been set up.
5337    counter_++;
5338
5339    // SetUpTestCase() should be called only once.
5340    EXPECT_EQ(1, counter_);
5341  }
5342
5343  // This will be called once after the last test in this test case is
5344  // run.
5345  static void TearDownTestCase() {
5346    printf("Tearing down the test case . . .\n");
5347
5348    // Decrements the number of test cases that have been set up.
5349    counter_--;
5350
5351    // TearDownTestCase() should be called only once.
5352    EXPECT_EQ(0, counter_);
5353
5354    // Cleans up the shared resource.
5355    shared_resource_ = NULL;
5356  }
5357
5358  // This will be called before each test in this test case.
5359  virtual void SetUp() {
5360    // SetUpTestCase() should be called only once, so counter_ should
5361    // always be 1.
5362    EXPECT_EQ(1, counter_);
5363  }
5364
5365  // Number of test cases that have been set up.
5366  static int counter_;
5367
5368  // Some resource to be shared by all tests in this test case.
5369  static const char* shared_resource_;
5370};
5371
5372int SetUpTestCaseTest::counter_ = 0;
5373const char* SetUpTestCaseTest::shared_resource_ = NULL;
5374
5375// A test that uses the shared resource.
5376TEST_F(SetUpTestCaseTest, Test1) {
5377  EXPECT_STRNE(NULL, shared_resource_);
5378}
5379
5380// Another test that uses the shared resource.
5381TEST_F(SetUpTestCaseTest, Test2) {
5382  EXPECT_STREQ("123", shared_resource_);
5383}
5384
5385// The InitGoogleTestTest test case tests testing::InitGoogleTest().
5386
5387// The Flags struct stores a copy of all Google Test flags.
5388struct Flags {
5389  // Constructs a Flags struct where each flag has its default value.
5390  Flags() : also_run_disabled_tests(false),
5391            break_on_failure(false),
5392            catch_exceptions(false),
5393            death_test_use_fork(false),
5394            filter(""),
5395            list_tests(false),
5396            output(""),
5397            print_time(true),
5398            random_seed(0),
5399            repeat(1),
5400            shuffle(false),
5401            stack_trace_depth(kMaxStackTraceDepth),
5402            stream_result_to(""),
5403            throw_on_failure(false) {}
5404
5405  // Factory methods.
5406
5407  // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5408  // the given value.
5409  static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5410    Flags flags;
5411    flags.also_run_disabled_tests = also_run_disabled_tests;
5412    return flags;
5413  }
5414
5415  // Creates a Flags struct where the gtest_break_on_failure flag has
5416  // the given value.
5417  static Flags BreakOnFailure(bool break_on_failure) {
5418    Flags flags;
5419    flags.break_on_failure = break_on_failure;
5420    return flags;
5421  }
5422
5423  // Creates a Flags struct where the gtest_catch_exceptions flag has
5424  // the given value.
5425  static Flags CatchExceptions(bool catch_exceptions) {
5426    Flags flags;
5427    flags.catch_exceptions = catch_exceptions;
5428    return flags;
5429  }
5430
5431  // Creates a Flags struct where the gtest_death_test_use_fork flag has
5432  // the given value.
5433  static Flags DeathTestUseFork(bool death_test_use_fork) {
5434    Flags flags;
5435    flags.death_test_use_fork = death_test_use_fork;
5436    return flags;
5437  }
5438
5439  // Creates a Flags struct where the gtest_filter flag has the given
5440  // value.
5441  static Flags Filter(const char* filter) {
5442    Flags flags;
5443    flags.filter = filter;
5444    return flags;
5445  }
5446
5447  // Creates a Flags struct where the gtest_list_tests flag has the
5448  // given value.
5449  static Flags ListTests(bool list_tests) {
5450    Flags flags;
5451    flags.list_tests = list_tests;
5452    return flags;
5453  }
5454
5455  // Creates a Flags struct where the gtest_output flag has the given
5456  // value.
5457  static Flags Output(const char* output) {
5458    Flags flags;
5459    flags.output = output;
5460    return flags;
5461  }
5462
5463  // Creates a Flags struct where the gtest_print_time flag has the given
5464  // value.
5465  static Flags PrintTime(bool print_time) {
5466    Flags flags;
5467    flags.print_time = print_time;
5468    return flags;
5469  }
5470
5471  // Creates a Flags struct where the gtest_random_seed flag has
5472  // the given value.
5473  static Flags RandomSeed(Int32 random_seed) {
5474    Flags flags;
5475    flags.random_seed = random_seed;
5476    return flags;
5477  }
5478
5479  // Creates a Flags struct where the gtest_repeat flag has the given
5480  // value.
5481  static Flags Repeat(Int32 repeat) {
5482    Flags flags;
5483    flags.repeat = repeat;
5484    return flags;
5485  }
5486
5487  // Creates a Flags struct where the gtest_shuffle flag has
5488  // the given value.
5489  static Flags Shuffle(bool shuffle) {
5490    Flags flags;
5491    flags.shuffle = shuffle;
5492    return flags;
5493  }
5494
5495  // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5496  // the given value.
5497  static Flags StackTraceDepth(Int32 stack_trace_depth) {
5498    Flags flags;
5499    flags.stack_trace_depth = stack_trace_depth;
5500    return flags;
5501  }
5502
5503  // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5504  // the given value.
5505  static Flags StreamResultTo(const char* stream_result_to) {
5506    Flags flags;
5507    flags.stream_result_to = stream_result_to;
5508    return flags;
5509  }
5510
5511  // Creates a Flags struct where the gtest_throw_on_failure flag has
5512  // the given value.
5513  static Flags ThrowOnFailure(bool throw_on_failure) {
5514    Flags flags;
5515    flags.throw_on_failure = throw_on_failure;
5516    return flags;
5517  }
5518
5519  // These fields store the flag values.
5520  bool also_run_disabled_tests;
5521  bool break_on_failure;
5522  bool catch_exceptions;
5523  bool death_test_use_fork;
5524  const char* filter;
5525  bool list_tests;
5526  const char* output;
5527  bool print_time;
5528  Int32 random_seed;
5529  Int32 repeat;
5530  bool shuffle;
5531  Int32 stack_trace_depth;
5532  const char* stream_result_to;
5533  bool throw_on_failure;
5534};
5535
5536// Fixture for testing InitGoogleTest().
5537class InitGoogleTestTest : public Test {
5538 protected:
5539  // Clears the flags before each test.
5540  virtual void SetUp() {
5541    GTEST_FLAG(also_run_disabled_tests) = false;
5542    GTEST_FLAG(break_on_failure) = false;
5543    GTEST_FLAG(catch_exceptions) = false;
5544    GTEST_FLAG(death_test_use_fork) = false;
5545    GTEST_FLAG(filter) = "";
5546    GTEST_FLAG(list_tests) = false;
5547    GTEST_FLAG(output) = "";
5548    GTEST_FLAG(print_time) = true;
5549    GTEST_FLAG(random_seed) = 0;
5550    GTEST_FLAG(repeat) = 1;
5551    GTEST_FLAG(shuffle) = false;
5552    GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
5553    GTEST_FLAG(stream_result_to) = "";
5554    GTEST_FLAG(throw_on_failure) = false;
5555  }
5556
5557  // Asserts that two narrow or wide string arrays are equal.
5558  template <typename CharType>
5559  static void AssertStringArrayEq(size_t size1, CharType** array1,
5560                                  size_t size2, CharType** array2) {
5561    ASSERT_EQ(size1, size2) << " Array sizes different.";
5562
5563    for (size_t i = 0; i != size1; i++) {
5564      ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5565    }
5566  }
5567
5568  // Verifies that the flag values match the expected values.
5569  static void CheckFlags(const Flags& expected) {
5570    EXPECT_EQ(expected.also_run_disabled_tests,
5571              GTEST_FLAG(also_run_disabled_tests));
5572    EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5573    EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
5574    EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
5575    EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5576    EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5577    EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
5578    EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
5579    EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
5580    EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
5581    EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
5582    EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
5583    EXPECT_STREQ(expected.stream_result_to,
5584                 GTEST_FLAG(stream_result_to).c_str());
5585    EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
5586  }
5587
5588  // Parses a command line (specified by argc1 and argv1), then
5589  // verifies that the flag values are expected and that the
5590  // recognized flags are removed from the command line.
5591  template <typename CharType>
5592  static void TestParsingFlags(int argc1, const CharType** argv1,
5593                               int argc2, const CharType** argv2,
5594                               const Flags& expected, bool should_print_help) {
5595    const bool saved_help_flag = ::testing::internal::g_help_flag;
5596    ::testing::internal::g_help_flag = false;
5597
5598#if GTEST_HAS_STREAM_REDIRECTION
5599    CaptureStdout();
5600#endif
5601
5602    // Parses the command line.
5603    internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5604
5605#if GTEST_HAS_STREAM_REDIRECTION
5606    const std::string captured_stdout = GetCapturedStdout();
5607#endif
5608
5609    // Verifies the flag values.
5610    CheckFlags(expected);
5611
5612    // Verifies that the recognized flags are removed from the command
5613    // line.
5614    AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5615
5616    // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5617    // help message for the flags it recognizes.
5618    EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5619
5620#if GTEST_HAS_STREAM_REDIRECTION
5621    const char* const expected_help_fragment =
5622        "This program contains tests written using";
5623    if (should_print_help) {
5624      EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5625    } else {
5626      EXPECT_PRED_FORMAT2(IsNotSubstring,
5627                          expected_help_fragment, captured_stdout);
5628    }
5629#endif  // GTEST_HAS_STREAM_REDIRECTION
5630
5631    ::testing::internal::g_help_flag = saved_help_flag;
5632  }
5633
5634  // This macro wraps TestParsingFlags s.t. the user doesn't need
5635  // to specify the array sizes.
5636
5637#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5638  TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5639                   sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5640                   expected, should_print_help)
5641};
5642
5643// Tests parsing an empty command line.
5644TEST_F(InitGoogleTestTest, Empty) {
5645  const char* argv[] = {
5646    NULL
5647  };
5648
5649  const char* argv2[] = {
5650    NULL
5651  };
5652
5653  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5654}
5655
5656// Tests parsing a command line that has no flag.
5657TEST_F(InitGoogleTestTest, NoFlag) {
5658  const char* argv[] = {
5659    "foo.exe",
5660    NULL
5661  };
5662
5663  const char* argv2[] = {
5664    "foo.exe",
5665    NULL
5666  };
5667
5668  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5669}
5670
5671// Tests parsing a bad --gtest_filter flag.
5672TEST_F(InitGoogleTestTest, FilterBad) {
5673  const char* argv[] = {
5674    "foo.exe",
5675    "--gtest_filter",
5676    NULL
5677  };
5678
5679  const char* argv2[] = {
5680    "foo.exe",
5681    "--gtest_filter",
5682    NULL
5683  };
5684
5685  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
5686}
5687
5688// Tests parsing an empty --gtest_filter flag.
5689TEST_F(InitGoogleTestTest, FilterEmpty) {
5690  const char* argv[] = {
5691    "foo.exe",
5692    "--gtest_filter=",
5693    NULL
5694  };
5695
5696  const char* argv2[] = {
5697    "foo.exe",
5698    NULL
5699  };
5700
5701  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5702}
5703
5704// Tests parsing a non-empty --gtest_filter flag.
5705TEST_F(InitGoogleTestTest, FilterNonEmpty) {
5706  const char* argv[] = {
5707    "foo.exe",
5708    "--gtest_filter=abc",
5709    NULL
5710  };
5711
5712  const char* argv2[] = {
5713    "foo.exe",
5714    NULL
5715  };
5716
5717  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5718}
5719
5720// Tests parsing --gtest_break_on_failure.
5721TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
5722  const char* argv[] = {
5723    "foo.exe",
5724    "--gtest_break_on_failure",
5725    NULL
5726};
5727
5728  const char* argv2[] = {
5729    "foo.exe",
5730    NULL
5731  };
5732
5733  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5734}
5735
5736// Tests parsing --gtest_break_on_failure=0.
5737TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
5738  const char* argv[] = {
5739    "foo.exe",
5740    "--gtest_break_on_failure=0",
5741    NULL
5742  };
5743
5744  const char* argv2[] = {
5745    "foo.exe",
5746    NULL
5747  };
5748
5749  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5750}
5751
5752// Tests parsing --gtest_break_on_failure=f.
5753TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5754  const char* argv[] = {
5755    "foo.exe",
5756    "--gtest_break_on_failure=f",
5757    NULL
5758  };
5759
5760  const char* argv2[] = {
5761    "foo.exe",
5762    NULL
5763  };
5764
5765  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5766}
5767
5768// Tests parsing --gtest_break_on_failure=F.
5769TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5770  const char* argv[] = {
5771    "foo.exe",
5772    "--gtest_break_on_failure=F",
5773    NULL
5774  };
5775
5776  const char* argv2[] = {
5777    "foo.exe",
5778    NULL
5779  };
5780
5781  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5782}
5783
5784// Tests parsing a --gtest_break_on_failure flag that has a "true"
5785// definition.
5786TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5787  const char* argv[] = {
5788    "foo.exe",
5789    "--gtest_break_on_failure=1",
5790    NULL
5791  };
5792
5793  const char* argv2[] = {
5794    "foo.exe",
5795    NULL
5796  };
5797
5798  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5799}
5800
5801// Tests parsing --gtest_catch_exceptions.
5802TEST_F(InitGoogleTestTest, CatchExceptions) {
5803  const char* argv[] = {
5804    "foo.exe",
5805    "--gtest_catch_exceptions",
5806    NULL
5807  };
5808
5809  const char* argv2[] = {
5810    "foo.exe",
5811    NULL
5812  };
5813
5814  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5815}
5816
5817// Tests parsing --gtest_death_test_use_fork.
5818TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5819  const char* argv[] = {
5820    "foo.exe",
5821    "--gtest_death_test_use_fork",
5822    NULL
5823  };
5824
5825  const char* argv2[] = {
5826    "foo.exe",
5827    NULL
5828  };
5829
5830  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5831}
5832
5833// Tests having the same flag twice with different values.  The
5834// expected behavior is that the one coming last takes precedence.
5835TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5836  const char* argv[] = {
5837    "foo.exe",
5838    "--gtest_filter=a",
5839    "--gtest_filter=b",
5840    NULL
5841  };
5842
5843  const char* argv2[] = {
5844    "foo.exe",
5845    NULL
5846  };
5847
5848  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5849}
5850
5851// Tests having an unrecognized flag on the command line.
5852TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5853  const char* argv[] = {
5854    "foo.exe",
5855    "--gtest_break_on_failure",
5856    "bar",  // Unrecognized by Google Test.
5857    "--gtest_filter=b",
5858    NULL
5859  };
5860
5861  const char* argv2[] = {
5862    "foo.exe",
5863    "bar",
5864    NULL
5865  };
5866
5867  Flags flags;
5868  flags.break_on_failure = true;
5869  flags.filter = "b";
5870  GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5871}
5872
5873// Tests having a --gtest_list_tests flag
5874TEST_F(InitGoogleTestTest, ListTestsFlag) {
5875    const char* argv[] = {
5876      "foo.exe",
5877      "--gtest_list_tests",
5878      NULL
5879    };
5880
5881    const char* argv2[] = {
5882      "foo.exe",
5883      NULL
5884    };
5885
5886    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5887}
5888
5889// Tests having a --gtest_list_tests flag with a "true" value
5890TEST_F(InitGoogleTestTest, ListTestsTrue) {
5891    const char* argv[] = {
5892      "foo.exe",
5893      "--gtest_list_tests=1",
5894      NULL
5895    };
5896
5897    const char* argv2[] = {
5898      "foo.exe",
5899      NULL
5900    };
5901
5902    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5903}
5904
5905// Tests having a --gtest_list_tests flag with a "false" value
5906TEST_F(InitGoogleTestTest, ListTestsFalse) {
5907    const char* argv[] = {
5908      "foo.exe",
5909      "--gtest_list_tests=0",
5910      NULL
5911    };
5912
5913    const char* argv2[] = {
5914      "foo.exe",
5915      NULL
5916    };
5917
5918    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5919}
5920
5921// Tests parsing --gtest_list_tests=f.
5922TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5923  const char* argv[] = {
5924    "foo.exe",
5925    "--gtest_list_tests=f",
5926    NULL
5927  };
5928
5929  const char* argv2[] = {
5930    "foo.exe",
5931    NULL
5932  };
5933
5934  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5935}
5936
5937// Tests parsing --gtest_list_tests=F.
5938TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
5939  const char* argv[] = {
5940    "foo.exe",
5941    "--gtest_list_tests=F",
5942    NULL
5943  };
5944
5945  const char* argv2[] = {
5946    "foo.exe",
5947    NULL
5948  };
5949
5950  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5951}
5952
5953// Tests parsing --gtest_output (invalid).
5954TEST_F(InitGoogleTestTest, OutputEmpty) {
5955  const char* argv[] = {
5956    "foo.exe",
5957    "--gtest_output",
5958    NULL
5959  };
5960
5961  const char* argv2[] = {
5962    "foo.exe",
5963    "--gtest_output",
5964    NULL
5965  };
5966
5967  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
5968}
5969
5970// Tests parsing --gtest_output=xml
5971TEST_F(InitGoogleTestTest, OutputXml) {
5972  const char* argv[] = {
5973    "foo.exe",
5974    "--gtest_output=xml",
5975    NULL
5976  };
5977
5978  const char* argv2[] = {
5979    "foo.exe",
5980    NULL
5981  };
5982
5983  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
5984}
5985
5986// Tests parsing --gtest_output=xml:file
5987TEST_F(InitGoogleTestTest, OutputXmlFile) {
5988  const char* argv[] = {
5989    "foo.exe",
5990    "--gtest_output=xml:file",
5991    NULL
5992  };
5993
5994  const char* argv2[] = {
5995    "foo.exe",
5996    NULL
5997  };
5998
5999  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
6000}
6001
6002// Tests parsing --gtest_output=xml:directory/path/
6003TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
6004  const char* argv[] = {
6005    "foo.exe",
6006    "--gtest_output=xml:directory/path/",
6007    NULL
6008  };
6009
6010  const char* argv2[] = {
6011    "foo.exe",
6012    NULL
6013  };
6014
6015  GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6016                            Flags::Output("xml:directory/path/"), false);
6017}
6018
6019// Tests having a --gtest_print_time flag
6020TEST_F(InitGoogleTestTest, PrintTimeFlag) {
6021    const char* argv[] = {
6022      "foo.exe",
6023      "--gtest_print_time",
6024      NULL
6025    };
6026
6027    const char* argv2[] = {
6028      "foo.exe",
6029      NULL
6030    };
6031
6032    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6033}
6034
6035// Tests having a --gtest_print_time flag with a "true" value
6036TEST_F(InitGoogleTestTest, PrintTimeTrue) {
6037    const char* argv[] = {
6038      "foo.exe",
6039      "--gtest_print_time=1",
6040      NULL
6041    };
6042
6043    const char* argv2[] = {
6044      "foo.exe",
6045      NULL
6046    };
6047
6048    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6049}
6050
6051// Tests having a --gtest_print_time flag with a "false" value
6052TEST_F(InitGoogleTestTest, PrintTimeFalse) {
6053    const char* argv[] = {
6054      "foo.exe",
6055      "--gtest_print_time=0",
6056      NULL
6057    };
6058
6059    const char* argv2[] = {
6060      "foo.exe",
6061      NULL
6062    };
6063
6064    GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6065}
6066
6067// Tests parsing --gtest_print_time=f.
6068TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
6069  const char* argv[] = {
6070    "foo.exe",
6071    "--gtest_print_time=f",
6072    NULL
6073  };
6074
6075  const char* argv2[] = {
6076    "foo.exe",
6077    NULL
6078  };
6079
6080  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6081}
6082
6083// Tests parsing --gtest_print_time=F.
6084TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
6085  const char* argv[] = {
6086    "foo.exe",
6087    "--gtest_print_time=F",
6088    NULL
6089  };
6090
6091  const char* argv2[] = {
6092    "foo.exe",
6093    NULL
6094  };
6095
6096  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6097}
6098
6099// Tests parsing --gtest_random_seed=number
6100TEST_F(InitGoogleTestTest, RandomSeed) {
6101  const char* argv[] = {
6102    "foo.exe",
6103    "--gtest_random_seed=1000",
6104    NULL
6105  };
6106
6107  const char* argv2[] = {
6108    "foo.exe",
6109    NULL
6110  };
6111
6112  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6113}
6114
6115// Tests parsing --gtest_repeat=number
6116TEST_F(InitGoogleTestTest, Repeat) {
6117  const char* argv[] = {
6118    "foo.exe",
6119    "--gtest_repeat=1000",
6120    NULL
6121  };
6122
6123  const char* argv2[] = {
6124    "foo.exe",
6125    NULL
6126  };
6127
6128  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
6129}
6130
6131// Tests having a --gtest_also_run_disabled_tests flag
6132TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
6133    const char* argv[] = {
6134      "foo.exe",
6135      "--gtest_also_run_disabled_tests",
6136      NULL
6137    };
6138
6139    const char* argv2[] = {
6140      "foo.exe",
6141      NULL
6142    };
6143
6144    GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6145                              Flags::AlsoRunDisabledTests(true), false);
6146}
6147
6148// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6149TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
6150    const char* argv[] = {
6151      "foo.exe",
6152      "--gtest_also_run_disabled_tests=1",
6153      NULL
6154    };
6155
6156    const char* argv2[] = {
6157      "foo.exe",
6158      NULL
6159    };
6160
6161    GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6162                              Flags::AlsoRunDisabledTests(true), false);
6163}
6164
6165// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6166TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
6167    const char* argv[] = {
6168      "foo.exe",
6169      "--gtest_also_run_disabled_tests=0",
6170      NULL
6171    };
6172
6173    const char* argv2[] = {
6174      "foo.exe",
6175      NULL
6176    };
6177
6178    GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6179                              Flags::AlsoRunDisabledTests(false), false);
6180}
6181
6182// Tests parsing --gtest_shuffle.
6183TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
6184  const char* argv[] = {
6185    "foo.exe",
6186    "--gtest_shuffle",
6187    NULL
6188};
6189
6190  const char* argv2[] = {
6191    "foo.exe",
6192    NULL
6193  };
6194
6195  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6196}
6197
6198// Tests parsing --gtest_shuffle=0.
6199TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
6200  const char* argv[] = {
6201    "foo.exe",
6202    "--gtest_shuffle=0",
6203    NULL
6204  };
6205
6206  const char* argv2[] = {
6207    "foo.exe",
6208    NULL
6209  };
6210
6211  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6212}
6213
6214// Tests parsing a --gtest_shuffle flag that has a "true"
6215// definition.
6216TEST_F(InitGoogleTestTest, ShuffleTrue) {
6217  const char* argv[] = {
6218    "foo.exe",
6219    "--gtest_shuffle=1",
6220    NULL
6221  };
6222
6223  const char* argv2[] = {
6224    "foo.exe",
6225    NULL
6226  };
6227
6228  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6229}
6230
6231// Tests parsing --gtest_stack_trace_depth=number.
6232TEST_F(InitGoogleTestTest, StackTraceDepth) {
6233  const char* argv[] = {
6234    "foo.exe",
6235    "--gtest_stack_trace_depth=5",
6236    NULL
6237  };
6238
6239  const char* argv2[] = {
6240    "foo.exe",
6241    NULL
6242  };
6243
6244  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6245}
6246
6247TEST_F(InitGoogleTestTest, StreamResultTo) {
6248  const char* argv[] = {
6249    "foo.exe",
6250    "--gtest_stream_result_to=lo