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