PageRenderTime 148ms CodeModel.GetById 16ms app.highlight 101ms RepoModel.GetById 1ms app.codeStats 3ms

/Unittests/googletest/test/gtest_unittest.cc

http://unladen-swallow.googlecode.com/
C++ | 6847 lines | 4654 code | 1137 blank | 1056 comment | 131 complexity | b6a02433d48364d6827f18b52c29a5cb MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   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

Large files files are truncated, but you can click here to view the full file