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