/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 are truncated click here to view the full file
- // Copyright 2005, Google Inc.
- // All rights reserved.
- //
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are
- // met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above
- // copyright notice, this list of conditions and the following disclaimer
- // in the documentation and/or other materials provided with the
- // distribution.
- // * Neither the name of Google Inc. nor the names of its
- // contributors may be used to endorse or promote products derived from
- // this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- // Author: wan@google.com (Zhanyong Wan)
- //
- // Tests for Google Test itself. This verifies that the basic constructs of
- // Google Test work.
- #include <gtest/gtest.h>
- // Verifies that the command line flag variables can be accessed
- // in code once <gtest/gtest.h> has been #included.
- // Do not move it after other #includes.
- TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
- bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
- || testing::GTEST_FLAG(break_on_failure)
- || testing::GTEST_FLAG(catch_exceptions)
- || testing::GTEST_FLAG(color) != "unknown"
- || testing::GTEST_FLAG(filter) != "unknown"
- || testing::GTEST_FLAG(list_tests)
- || testing::GTEST_FLAG(output) != "unknown"
- || testing::GTEST_FLAG(print_time)
- || testing::GTEST_FLAG(random_seed)
- || testing::GTEST_FLAG(repeat) > 0
- || testing::GTEST_FLAG(show_internal_stack_frames)
- || testing::GTEST_FLAG(shuffle)
- || testing::GTEST_FLAG(stack_trace_depth) > 0
- || testing::GTEST_FLAG(throw_on_failure);
- EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
- }
- #include <gtest/gtest-spi.h>
- // Indicates that this translation unit is part of Google Test's
- // implementation. It must come before gtest-internal-inl.h is
- // included, or there will be a compiler error. This trick is to
- // prevent a user from accidentally including gtest-internal-inl.h in
- // his code.
- #define GTEST_IMPLEMENTATION_ 1
- #include "src/gtest-internal-inl.h"
- #undef GTEST_IMPLEMENTATION_
- #include <limits.h> // For INT_MAX.
- #include <stdlib.h>
- #include <time.h>
- #if GTEST_HAS_PTHREAD
- #include <pthread.h>
- #endif // GTEST_HAS_PTHREAD
- #ifdef __BORLANDC__
- #include <map>
- #endif
- namespace testing {
- namespace internal {
- bool ShouldUseColor(bool stdout_is_tty);
- const char* FormatTimeInMillisAsSeconds(TimeInMillis ms);
- bool ParseInt32Flag(const char* str, const char* flag, Int32* value);
- // Provides access to otherwise private parts of the TestEventListeners class
- // that are needed to test it.
- class TestEventListenersAccessor {
- public:
- static TestEventListener* GetRepeater(TestEventListeners* listeners) {
- return listeners->repeater();
- }
- static void SetDefaultResultPrinter(TestEventListeners* listeners,
- TestEventListener* listener) {
- listeners->SetDefaultResultPrinter(listener);
- }
- static void SetDefaultXmlGenerator(TestEventListeners* listeners,
- TestEventListener* listener) {
- listeners->SetDefaultXmlGenerator(listener);
- }
- static bool EventForwardingEnabled(const TestEventListeners& listeners) {
- return listeners.EventForwardingEnabled();
- }
- static void SuppressEventForwarding(TestEventListeners* listeners) {
- listeners->SuppressEventForwarding();
- }
- };
- } // namespace internal
- } // namespace testing
- using testing::AssertionFailure;
- using testing::AssertionResult;
- using testing::AssertionSuccess;
- using testing::DoubleLE;
- using testing::EmptyTestEventListener;
- using testing::FloatLE;
- using testing::GTEST_FLAG(also_run_disabled_tests);
- using testing::GTEST_FLAG(break_on_failure);
- using testing::GTEST_FLAG(catch_exceptions);
- using testing::GTEST_FLAG(color);
- using testing::GTEST_FLAG(death_test_use_fork);
- using testing::GTEST_FLAG(filter);
- using testing::GTEST_FLAG(list_tests);
- using testing::GTEST_FLAG(output);
- using testing::GTEST_FLAG(print_time);
- using testing::GTEST_FLAG(random_seed);
- using testing::GTEST_FLAG(repeat);
- using testing::GTEST_FLAG(show_internal_stack_frames);
- using testing::GTEST_FLAG(shuffle);
- using testing::GTEST_FLAG(stack_trace_depth);
- using testing::GTEST_FLAG(throw_on_failure);
- using testing::IsNotSubstring;
- using testing::IsSubstring;
- using testing::Message;
- using testing::ScopedFakeTestPartResultReporter;
- using testing::StaticAssertTypeEq;
- using testing::Test;
- using testing::TestEventListeners;
- using testing::TestCase;
- using testing::TestPartResult;
- using testing::TestPartResultArray;
- using testing::TestProperty;
- using testing::TestResult;
- using testing::UnitTest;
- using testing::internal::AlwaysFalse;
- using testing::internal::AlwaysTrue;
- using testing::internal::AppendUserMessage;
- using testing::internal::CodePointToUtf8;
- using testing::internal::EqFailure;
- using testing::internal::FloatingPoint;
- using testing::internal::FormatTimeInMillisAsSeconds;
- using testing::internal::GTestFlagSaver;
- using testing::internal::GetCurrentOsStackTraceExceptTop;
- using testing::internal::GetNextRandomSeed;
- using testing::internal::GetRandomSeedFromFlag;
- using testing::internal::GetTestTypeId;
- using testing::internal::GetTypeId;
- using testing::internal::GetUnitTestImpl;
- using testing::internal::Int32;
- using testing::internal::Int32FromEnvOrDie;
- using testing::internal::ParseInt32Flag;
- using testing::internal::ShouldRunTestOnShard;
- using testing::internal::ShouldShard;
- using testing::internal::ShouldUseColor;
- using testing::internal::StreamableToString;
- using testing::internal::String;
- using testing::internal::TestEventListenersAccessor;
- using testing::internal::TestResultAccessor;
- using testing::internal::ThreadLocal;
- using testing::internal::UInt32;
- using testing::internal::Vector;
- using testing::internal::WideStringToUtf8;
- using testing::internal::kMaxRandomSeed;
- using testing::internal::kTestTypeIdInGoogleTest;
- using testing::internal::scoped_ptr;
- class TestingVector : public Vector<int> {
- };
- ::std::ostream& operator<<(::std::ostream& os,
- const TestingVector& vector) {
- os << "{ ";
- for (int i = 0; i < vector.size(); i++) {
- os << vector.GetElement(i) << " ";
- }
- os << "}";
- return os;
- }
- // This line tests that we can define tests in an unnamed namespace.
- namespace {
- TEST(GetRandomSeedFromFlagTest, HandlesZero) {
- const int seed = GetRandomSeedFromFlag(0);
- EXPECT_LE(1, seed);
- EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
- }
- TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
- EXPECT_EQ(1, GetRandomSeedFromFlag(1));
- EXPECT_EQ(2, GetRandomSeedFromFlag(2));
- EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
- EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
- GetRandomSeedFromFlag(kMaxRandomSeed));
- }
- TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
- const int seed1 = GetRandomSeedFromFlag(-1);
- EXPECT_LE(1, seed1);
- EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
- const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
- EXPECT_LE(1, seed2);
- EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
- }
- TEST(GetNextRandomSeedTest, WorksForValidInput) {
- EXPECT_EQ(2, GetNextRandomSeed(1));
- EXPECT_EQ(3, GetNextRandomSeed(2));
- EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
- GetNextRandomSeed(kMaxRandomSeed - 1));
- EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
- // We deliberately don't test GetNextRandomSeed() with invalid
- // inputs, as that requires death tests, which are expensive. This
- // is fine as GetNextRandomSeed() is internal and has a
- // straightforward definition.
- }
- static void ClearCurrentTestPartResults() {
- TestResultAccessor::ClearTestPartResults(
- GetUnitTestImpl()->current_test_result());
- }
- // Tests GetTypeId.
- TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
- EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
- EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
- }
- class SubClassOfTest : public Test {};
- class AnotherSubClassOfTest : public Test {};
- TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
- EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
- EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
- EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
- EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
- EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
- EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
- }
- // Verifies that GetTestTypeId() returns the same value, no matter it
- // is called from inside Google Test or outside of it.
- TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
- EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
- }
- // Tests FormatTimeInMillisAsSeconds().
- TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
- EXPECT_STREQ("0", FormatTimeInMillisAsSeconds(0));
- }
- TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
- EXPECT_STREQ("0.003", FormatTimeInMillisAsSeconds(3));
- EXPECT_STREQ("0.01", FormatTimeInMillisAsSeconds(10));
- EXPECT_STREQ("0.2", FormatTimeInMillisAsSeconds(200));
- EXPECT_STREQ("1.2", FormatTimeInMillisAsSeconds(1200));
- EXPECT_STREQ("3", FormatTimeInMillisAsSeconds(3000));
- }
- TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
- EXPECT_STREQ("-0.003", FormatTimeInMillisAsSeconds(-3));
- EXPECT_STREQ("-0.01", FormatTimeInMillisAsSeconds(-10));
- EXPECT_STREQ("-0.2", FormatTimeInMillisAsSeconds(-200));
- EXPECT_STREQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
- EXPECT_STREQ("-3", FormatTimeInMillisAsSeconds(-3000));
- }
- #if !GTEST_OS_SYMBIAN
- // NULL testing does not work with Symbian compilers.
- #ifdef __BORLANDC__
- // Silences warnings: "Condition is always true", "Unreachable code"
- #pragma option push -w-ccc -w-rch
- #endif
- // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
- // pointer literal.
- TEST(NullLiteralTest, IsTrueForNullLiterals) {
- EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
- EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
- EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
- EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
- EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(false));
- #ifndef __BORLANDC__
- // Some compilers may fail to detect some null pointer literals;
- // as long as users of the framework don't use such literals, this
- // is harmless.
- EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1));
- EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(true && false));
- #endif
- }
- // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
- // pointer literal.
- TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
- EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
- EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
- EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
- EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
- }
- #ifdef __BORLANDC__
- // Restores warnings after previous "#pragma option push" supressed them
- #pragma option pop
- #endif
- #endif // !GTEST_OS_SYMBIAN
- //
- // Tests CodePointToUtf8().
- // Tests that the NUL character L'\0' is encoded correctly.
- TEST(CodePointToUtf8Test, CanEncodeNul) {
- char buffer[32];
- EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer));
- }
- // Tests that ASCII characters are encoded correctly.
- TEST(CodePointToUtf8Test, CanEncodeAscii) {
- char buffer[32];
- EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer));
- EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer));
- EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer));
- EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer));
- }
- // Tests that Unicode code-points that have 8 to 11 bits are encoded
- // as 110xxxxx 10xxxxxx.
- TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
- char buffer[32];
- // 000 1101 0011 => 110-00011 10-010011
- EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer));
- // 101 0111 0110 => 110-10101 10-110110
- EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(L'\x576', buffer));
- }
- // Tests that Unicode code-points that have 12 to 16 bits are encoded
- // as 1110xxxx 10xxxxxx 10xxxxxx.
- TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
- char buffer[32];
- // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
- EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(L'\x8D3', buffer));
- // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
- EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(L'\xC74D', buffer));
- }
- #if !GTEST_WIDE_STRING_USES_UTF16_
- // Tests in this group require a wchar_t to hold > 16 bits, and thus
- // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
- // 16-bit wide. This code may not compile on those systems.
- // Tests that Unicode code-points that have 17 to 21 bits are encoded
- // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
- TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
- char buffer[32];
- // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
- EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer));
- // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
- EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer));
- // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
- EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer));
- }
- // Tests that encoding an invalid code-point generates the expected result.
- TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
- char buffer[32];
- EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
- CodePointToUtf8(L'\x1234ABCD', buffer));
- }
- #endif // !GTEST_WIDE_STRING_USES_UTF16_
- // Tests WideStringToUtf8().
- // Tests that the NUL character L'\0' is encoded correctly.
- TEST(WideStringToUtf8Test, CanEncodeNul) {
- EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
- EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
- }
- // Tests that ASCII strings are encoded correctly.
- TEST(WideStringToUtf8Test, CanEncodeAscii) {
- EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
- EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
- EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
- EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
- }
- // Tests that Unicode code-points that have 8 to 11 bits are encoded
- // as 110xxxxx 10xxxxxx.
- TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
- // 000 1101 0011 => 110-00011 10-010011
- EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
- EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
- // 101 0111 0110 => 110-10101 10-110110
- EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", 1).c_str());
- EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", -1).c_str());
- }
- // Tests that Unicode code-points that have 12 to 16 bits are encoded
- // as 1110xxxx 10xxxxxx 10xxxxxx.
- TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
- // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
- EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", 1).c_str());
- EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", -1).c_str());
- // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
- EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", 1).c_str());
- EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", -1).c_str());
- }
- // Tests that the conversion stops when the function encounters \0 character.
- TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
- EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
- }
- // Tests that the conversion stops when the function reaches the limit
- // specified by the 'length' parameter.
- TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
- EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
- }
- #if !GTEST_WIDE_STRING_USES_UTF16_
- // Tests that Unicode code-points that have 17 to 21 bits are encoded
- // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
- // on the systems using UTF-16 encoding.
- TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
- // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
- EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
- EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
- // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
- EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
- EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
- }
- // Tests that encoding an invalid code-point generates the expected result.
- TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
- EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
- WideStringToUtf8(L"\xABCDFF", -1).c_str());
- }
- #else // !GTEST_WIDE_STRING_USES_UTF16_
- // Tests that surrogate pairs are encoded correctly on the systems using
- // UTF-16 encoding in the wide strings.
- TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
- EXPECT_STREQ("\xF0\x90\x90\x80",
- WideStringToUtf8(L"\xD801\xDC00", -1).c_str());
- }
- // Tests that encoding an invalid UTF-16 surrogate pair
- // generates the expected result.
- TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
- // Leading surrogate is at the end of the string.
- EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(L"\xD800", -1).c_str());
- // Leading surrogate is not followed by the trailing surrogate.
- EXPECT_STREQ("\xED\xA0\x80$", WideStringToUtf8(L"\xD800$", -1).c_str());
- // Trailing surrogate appearas without a leading surrogate.
- EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(L"\xDC00PQR", -1).c_str());
- }
- #endif // !GTEST_WIDE_STRING_USES_UTF16_
- // Tests that codepoint concatenation works correctly.
- #if !GTEST_WIDE_STRING_USES_UTF16_
- TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
- EXPECT_STREQ(
- "\xF4\x88\x98\xB4"
- "\xEC\x9D\x8D"
- "\n"
- "\xD5\xB6"
- "\xE0\xA3\x93"
- "\xF4\x88\x98\xB4",
- WideStringToUtf8(L"\x108634\xC74D\n\x576\x8D3\x108634", -1).c_str());
- }
- #else
- TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
- EXPECT_STREQ(
- "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
- WideStringToUtf8(L"\xC74D\n\x576\x8D3", -1).c_str());
- }
- #endif // !GTEST_WIDE_STRING_USES_UTF16_
- // Tests the Random class.
- TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
- testing::internal::Random random(42);
- EXPECT_DEATH_IF_SUPPORTED(
- random.Generate(0),
- "Cannot generate a number in the range \\[0, 0\\)");
- EXPECT_DEATH_IF_SUPPORTED(
- random.Generate(testing::internal::Random::kMaxRange + 1),
- "Generation of a number in \\[0, 2147483649\\) was requested, "
- "but this can only generate numbers in \\[0, 2147483648\\)");
- }
- TEST(RandomTest, GeneratesNumbersWithinRange) {
- const UInt32 kRange = 10000;
- testing::internal::Random random(12345);
- for (int i = 0; i < 10; i++) {
- EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
- }
- testing::internal::Random random2(testing::internal::Random::kMaxRange);
- for (int i = 0; i < 10; i++) {
- EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
- }
- }
- TEST(RandomTest, RepeatsWhenReseeded) {
- const int kSeed = 123;
- const int kArraySize = 10;
- const UInt32 kRange = 10000;
- UInt32 values[kArraySize];
- testing::internal::Random random(kSeed);
- for (int i = 0; i < kArraySize; i++) {
- values[i] = random.Generate(kRange);
- }
- random.Reseed(kSeed);
- for (int i = 0; i < kArraySize; i++) {
- EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
- }
- }
- // Tests the Vector class template.
- // Tests Vector::Clear().
- TEST(VectorTest, Clear) {
- Vector<int> a;
- a.PushBack(1);
- a.Clear();
- EXPECT_EQ(0, a.size());
- a.PushBack(2);
- a.PushBack(3);
- a.Clear();
- EXPECT_EQ(0, a.size());
- }
- // Tests Vector::PushBack().
- TEST(VectorTest, PushBack) {
- Vector<char> a;
- a.PushBack('a');
- ASSERT_EQ(1, a.size());
- EXPECT_EQ('a', a.GetElement(0));
- a.PushBack('b');
- ASSERT_EQ(2, a.size());
- EXPECT_EQ('a', a.GetElement(0));
- EXPECT_EQ('b', a.GetElement(1));
- }
- // Tests Vector::PushFront().
- TEST(VectorTest, PushFront) {
- Vector<int> a;
- ASSERT_EQ(0, a.size());
- // Calls PushFront() on an empty Vector.
- a.PushFront(1);
- ASSERT_EQ(1, a.size());
- EXPECT_EQ(1, a.GetElement(0));
- // Calls PushFront() on a singleton Vector.
- a.PushFront(2);
- ASSERT_EQ(2, a.size());
- EXPECT_EQ(2, a.GetElement(0));
- EXPECT_EQ(1, a.GetElement(1));
- // Calls PushFront() on a Vector with more than one elements.
- a.PushFront(3);
- ASSERT_EQ(3, a.size());
- EXPECT_EQ(3, a.GetElement(0));
- EXPECT_EQ(2, a.GetElement(1));
- EXPECT_EQ(1, a.GetElement(2));
- }
- // Tests Vector::PopFront().
- TEST(VectorTest, PopFront) {
- Vector<int> a;
- // Popping on an empty Vector should fail.
- EXPECT_FALSE(a.PopFront(NULL));
- // Popping again on an empty Vector should fail, and the result element
- // shouldn't be overwritten.
- int element = 1;
- EXPECT_FALSE(a.PopFront(&element));
- EXPECT_EQ(1, element);
- a.PushFront(2);
- a.PushFront(3);
- // PopFront() should pop the element in the front of the Vector.
- EXPECT_TRUE(a.PopFront(&element));
- EXPECT_EQ(3, element);
- // After popping the last element, the Vector should be empty.
- EXPECT_TRUE(a.PopFront(NULL));
- EXPECT_EQ(0, a.size());
- }
- // Tests inserting at the beginning using Vector::Insert().
- TEST(VectorTest, InsertAtBeginning) {
- Vector<int> a;
- ASSERT_EQ(0, a.size());
- // Inserts into an empty Vector.
- a.Insert(1, 0);
- ASSERT_EQ(1, a.size());
- EXPECT_EQ(1, a.GetElement(0));
- // Inserts at the beginning of a singleton Vector.
- a.Insert(2, 0);
- ASSERT_EQ(2, a.size());
- EXPECT_EQ(2, a.GetElement(0));
- EXPECT_EQ(1, a.GetElement(1));
- // Inserts at the beginning of a Vector with more than one elements.
- a.Insert(3, 0);
- ASSERT_EQ(3, a.size());
- EXPECT_EQ(3, a.GetElement(0));
- EXPECT_EQ(2, a.GetElement(1));
- EXPECT_EQ(1, a.GetElement(2));
- }
- // Tests inserting at a location other than the beginning using
- // Vector::Insert().
- TEST(VectorTest, InsertNotAtBeginning) {
- // Prepares a singleton Vector.
- Vector<int> a;
- a.PushBack(1);
- // Inserts at the end of a singleton Vector.
- a.Insert(2, a.size());
- ASSERT_EQ(2, a.size());
- EXPECT_EQ(1, a.GetElement(0));
- EXPECT_EQ(2, a.GetElement(1));
- // Inserts at the end of a Vector with more than one elements.
- a.Insert(3, a.size());
- ASSERT_EQ(3, a.size());
- EXPECT_EQ(1, a.GetElement(0));
- EXPECT_EQ(2, a.GetElement(1));
- EXPECT_EQ(3, a.GetElement(2));
- // Inserts in the middle of a Vector.
- a.Insert(4, 1);
- ASSERT_EQ(4, a.size());
- EXPECT_EQ(1, a.GetElement(0));
- EXPECT_EQ(4, a.GetElement(1));
- EXPECT_EQ(2, a.GetElement(2));
- EXPECT_EQ(3, a.GetElement(3));
- }
- // Tests Vector::GetElementOr().
- TEST(VectorTest, GetElementOr) {
- Vector<char> a;
- EXPECT_EQ('x', a.GetElementOr(0, 'x'));
- a.PushBack('a');
- a.PushBack('b');
- EXPECT_EQ('a', a.GetElementOr(0, 'x'));
- EXPECT_EQ('b', a.GetElementOr(1, 'x'));
- EXPECT_EQ('x', a.GetElementOr(-2, 'x'));
- EXPECT_EQ('x', a.GetElementOr(2, 'x'));
- }
- TEST(VectorTest, Swap) {
- Vector<int> a;
- a.PushBack(0);
- a.PushBack(1);
- a.PushBack(2);
- // Swaps an element with itself.
- a.Swap(0, 0);
- ASSERT_EQ(0, a.GetElement(0));
- ASSERT_EQ(1, a.GetElement(1));
- ASSERT_EQ(2, a.GetElement(2));
- // Swaps two different elements where the indices go up.
- a.Swap(0, 1);
- ASSERT_EQ(1, a.GetElement(0));
- ASSERT_EQ(0, a.GetElement(1));
- ASSERT_EQ(2, a.GetElement(2));
- // Swaps two different elements where the indices go down.
- a.Swap(2, 0);
- ASSERT_EQ(2, a.GetElement(0));
- ASSERT_EQ(0, a.GetElement(1));
- ASSERT_EQ(1, a.GetElement(2));
- }
- TEST(VectorTest, Clone) {
- // Clones an empty Vector.
- Vector<int> a;
- scoped_ptr<Vector<int> > empty(a.Clone());
- EXPECT_EQ(0, empty->size());
- // Clones a singleton.
- a.PushBack(42);
- scoped_ptr<Vector<int> > singleton(a.Clone());
- ASSERT_EQ(1, singleton->size());
- EXPECT_EQ(42, singleton->GetElement(0));
- // Clones a Vector with more elements.
- a.PushBack(43);
- a.PushBack(44);
- scoped_ptr<Vector<int> > big(a.Clone());
- ASSERT_EQ(3, big->size());
- EXPECT_EQ(42, big->GetElement(0));
- EXPECT_EQ(43, big->GetElement(1));
- EXPECT_EQ(44, big->GetElement(2));
- }
- // Tests Vector::Erase().
- TEST(VectorDeathTest, Erase) {
- Vector<int> a;
- // Tests erasing from an empty vector.
- EXPECT_DEATH_IF_SUPPORTED(
- a.Erase(0),
- "Invalid Vector index 0: must be in range \\[0, -1\\]\\.");
- // Tests erasing from a singleton vector.
- a.PushBack(0);
- a.Erase(0);
- EXPECT_EQ(0, a.size());
- // Tests Erase parameters beyond the bounds of the vector.
- Vector<int> a1;
- a1.PushBack(0);
- a1.PushBack(1);
- a1.PushBack(2);
- EXPECT_DEATH_IF_SUPPORTED(
- a1.Erase(3),
- "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
- EXPECT_DEATH_IF_SUPPORTED(
- a1.Erase(-1),
- "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
- // Tests erasing at the end of the vector.
- Vector<int> a2;
- a2.PushBack(0);
- a2.PushBack(1);
- a2.PushBack(2);
- a2.Erase(2);
- ASSERT_EQ(2, a2.size());
- EXPECT_EQ(0, a2.GetElement(0));
- EXPECT_EQ(1, a2.GetElement(1));
- // Tests erasing in the middle of the vector.
- Vector<int> a3;
- a3.PushBack(0);
- a3.PushBack(1);
- a3.PushBack(2);
- a3.Erase(1);
- ASSERT_EQ(2, a3.size());
- EXPECT_EQ(0, a3.GetElement(0));
- EXPECT_EQ(2, a3.GetElement(1));
- // Tests erasing at the beginning of the vector.
- Vector<int> a4;
- a4.PushBack(0);
- a4.PushBack(1);
- a4.PushBack(2);
- a4.Erase(0);
- ASSERT_EQ(2, a4.size());
- EXPECT_EQ(1, a4.GetElement(0));
- EXPECT_EQ(2, a4.GetElement(1));
- }
- // Tests the GetElement accessor.
- TEST(VectorDeathTest, GetElement) {
- Vector<int> a;
- a.PushBack(0);
- a.PushBack(1);
- a.PushBack(2);
- const Vector<int>& b = a;
- EXPECT_EQ(0, b.GetElement(0));
- EXPECT_EQ(1, b.GetElement(1));
- EXPECT_EQ(2, b.GetElement(2));
- EXPECT_DEATH_IF_SUPPORTED(
- b.GetElement(3),
- "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
- EXPECT_DEATH_IF_SUPPORTED(
- b.GetElement(-1),
- "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
- }
- // Tests the GetMutableElement accessor.
- TEST(VectorDeathTest, GetMutableElement) {
- Vector<int> a;
- a.PushBack(0);
- a.PushBack(1);
- a.PushBack(2);
- EXPECT_EQ(0, a.GetMutableElement(0));
- EXPECT_EQ(1, a.GetMutableElement(1));
- EXPECT_EQ(2, a.GetMutableElement(2));
- a.GetMutableElement(0) = 42;
- EXPECT_EQ(42, a.GetMutableElement(0));
- EXPECT_EQ(1, a.GetMutableElement(1));
- EXPECT_EQ(2, a.GetMutableElement(2));
- EXPECT_DEATH_IF_SUPPORTED(
- a.GetMutableElement(3),
- "Invalid Vector index 3: must be in range \\[0, 2\\]\\.");
- EXPECT_DEATH_IF_SUPPORTED(
- a.GetMutableElement(-1),
- "Invalid Vector index -1: must be in range \\[0, 2\\]\\.");
- }
- TEST(VectorDeathTest, Swap) {
- Vector<int> a;
- a.PushBack(0);
- a.PushBack(1);
- a.PushBack(2);
- EXPECT_DEATH_IF_SUPPORTED(
- a.Swap(-1, 1),
- "Invalid first swap element -1: must be in range \\[0, 2\\]");
- EXPECT_DEATH_IF_SUPPORTED(
- a.Swap(3, 1),
- "Invalid first swap element 3: must be in range \\[0, 2\\]");
- EXPECT_DEATH_IF_SUPPORTED(
- a.Swap(1, -1),
- "Invalid second swap element -1: must be in range \\[0, 2\\]");
- EXPECT_DEATH_IF_SUPPORTED(
- a.Swap(1, 3),
- "Invalid second swap element 3: must be in range \\[0, 2\\]");
- }
- TEST(VectorDeathTest, ShuffleRange) {
- Vector<int> a;
- a.PushBack(0);
- a.PushBack(1);
- a.PushBack(2);
- testing::internal::Random random(1);
- EXPECT_DEATH_IF_SUPPORTED(
- a.ShuffleRange(&random, -1, 1),
- "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
- EXPECT_DEATH_IF_SUPPORTED(
- a.ShuffleRange(&random, 4, 4),
- "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
- EXPECT_DEATH_IF_SUPPORTED(
- a.ShuffleRange(&random, 3, 2),
- "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
- EXPECT_DEATH_IF_SUPPORTED(
- a.ShuffleRange(&random, 3, 4),
- "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
- }
- class VectorShuffleTest : public Test {
- protected:
- static const int kVectorSize = 20;
- VectorShuffleTest() : random_(1) {
- for (int i = 0; i < kVectorSize; i++) {
- vector_.PushBack(i);
- }
- }
- static bool VectorIsCorrupt(const TestingVector& vector) {
- if (kVectorSize != vector.size()) {
- return true;
- }
- bool found_in_vector[kVectorSize] = { false };
- for (int i = 0; i < vector.size(); i++) {
- const int e = vector.GetElement(i);
- if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
- return true;
- }
- found_in_vector[e] = true;
- }
- // Vector size is correct, elements' range is correct, no
- // duplicate elements. Therefore no corruption has occurred.
- return false;
- }
- static bool VectorIsNotCorrupt(const TestingVector& vector) {
- return !VectorIsCorrupt(vector);
- }
- static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
- for (int i = begin; i < end; i++) {
- if (i != vector.GetElement(i)) {
- return true;
- }
- }
- return false;
- }
- static bool RangeIsUnshuffled(
- const TestingVector& vector, int begin, int end) {
- return !RangeIsShuffled(vector, begin, end);
- }
- static bool VectorIsShuffled(const TestingVector& vector) {
- return RangeIsShuffled(vector, 0, vector.size());
- }
- static bool VectorIsUnshuffled(const TestingVector& vector) {
- return !VectorIsShuffled(vector);
- }
- testing::internal::Random random_;
- TestingVector vector_;
- }; // class VectorShuffleTest
- const int VectorShuffleTest::kVectorSize;
- TEST_F(VectorShuffleTest, HandlesEmptyRange) {
- // Tests an empty range at the beginning...
- vector_.ShuffleRange(&random_, 0, 0);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- ASSERT_PRED1(VectorIsUnshuffled, vector_);
- // ...in the middle...
- vector_.ShuffleRange(&random_, kVectorSize/2, kVectorSize/2);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- ASSERT_PRED1(VectorIsUnshuffled, vector_);
- // ...at the end...
- vector_.ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- ASSERT_PRED1(VectorIsUnshuffled, vector_);
- // ...and past the end.
- vector_.ShuffleRange(&random_, kVectorSize, kVectorSize);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- ASSERT_PRED1(VectorIsUnshuffled, vector_);
- }
- TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
- // Tests a size one range at the beginning...
- vector_.ShuffleRange(&random_, 0, 1);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- ASSERT_PRED1(VectorIsUnshuffled, vector_);
- // ...in the middle...
- vector_.ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- ASSERT_PRED1(VectorIsUnshuffled, vector_);
- // ...and at the end.
- vector_.ShuffleRange(&random_, kVectorSize - 1, kVectorSize);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- ASSERT_PRED1(VectorIsUnshuffled, vector_);
- }
- // Because we use our own random number generator and a fixed seed,
- // we can guarantee that the following "random" tests will succeed.
- TEST_F(VectorShuffleTest, ShufflesEntireVector) {
- vector_.Shuffle(&random_);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
- // Tests the first and last elements in particular to ensure that
- // there are no off-by-one problems in our shuffle algorithm.
- EXPECT_NE(0, vector_.GetElement(0));
- EXPECT_NE(kVectorSize - 1, vector_.GetElement(kVectorSize - 1));
- }
- TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
- const int kRangeSize = kVectorSize/2;
- vector_.ShuffleRange(&random_, 0, kRangeSize);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
- EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
- }
- TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
- const int kRangeSize = kVectorSize / 2;
- vector_.ShuffleRange(&random_, kRangeSize, kVectorSize);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
- EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
- }
- TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
- int kRangeSize = kVectorSize/3;
- vector_.ShuffleRange(&random_, kRangeSize, 2*kRangeSize);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
- EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
- EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
- }
- TEST_F(VectorShuffleTest, ShufflesRepeatably) {
- TestingVector vector2;
- for (int i = 0; i < kVectorSize; i++) {
- vector2.PushBack(i);
- }
- random_.Reseed(1234);
- vector_.Shuffle(&random_);
- random_.Reseed(1234);
- vector2.Shuffle(&random_);
- ASSERT_PRED1(VectorIsNotCorrupt, vector_);
- ASSERT_PRED1(VectorIsNotCorrupt, vector2);
- for (int i = 0; i < kVectorSize; i++) {
- EXPECT_EQ(vector_.GetElement(i), vector2.GetElement(i))
- << " where i is " << i;
- }
- }
- // Tests the size of the AssertHelper class.
- TEST(AssertHelperTest, AssertHelperIsSmall) {
- // To avoid breaking clients that use lots of assertions in one
- // function, we cannot grow the size of AssertHelper.
- EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
- }
- // Tests the String class.
- // Tests String's constructors.
- TEST(StringTest, Constructors) {
- // Default ctor.
- String s1;
- // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
- // pointers with NULL isn't supported on all platforms.
- EXPECT_EQ(0U, s1.length());
- EXPECT_TRUE(NULL == s1.c_str());
- // Implicitly constructs from a C-string.
- String s2 = "Hi";
- EXPECT_EQ(2U, s2.length());
- EXPECT_STREQ("Hi", s2.c_str());
- // Constructs from a C-string and a length.
- String s3("hello", 3);
- EXPECT_EQ(3U, s3.length());
- EXPECT_STREQ("hel", s3.c_str());
- // The empty String should be created when String is constructed with
- // a NULL pointer and length 0.
- EXPECT_EQ(0U, String(NULL, 0).length());
- EXPECT_FALSE(String(NULL, 0).c_str() == NULL);
- // Constructs a String that contains '\0'.
- String s4("a\0bcd", 4);
- EXPECT_EQ(4U, s4.length());
- EXPECT_EQ('a', s4.c_str()[0]);
- EXPECT_EQ('\0', s4.c_str()[1]);
- EXPECT_EQ('b', s4.c_str()[2]);
- EXPECT_EQ('c', s4.c_str()[3]);
- // Copy ctor where the source is NULL.
- const String null_str;
- String s5 = null_str;
- EXPECT_TRUE(s5.c_str() == NULL);
- // Copy ctor where the source isn't NULL.
- String s6 = s3;
- EXPECT_EQ(3U, s6.length());
- EXPECT_STREQ("hel", s6.c_str());
- // Copy ctor where the source contains '\0'.
- String s7 = s4;
- EXPECT_EQ(4U, s7.length());
- EXPECT_EQ('a', s7.c_str()[0]);
- EXPECT_EQ('\0', s7.c_str()[1]);
- EXPECT_EQ('b', s7.c_str()[2]);
- EXPECT_EQ('c', s7.c_str()[3]);
- }
- #if GTEST_HAS_STD_STRING
- TEST(StringTest, ConvertsFromStdString) {
- // An empty std::string.
- const std::string src1("");
- const String dest1 = src1;
- EXPECT_EQ(0U, dest1.length());
- EXPECT_STREQ("", dest1.c_str());
- // A normal std::string.
- const std::string src2("Hi");
- const String dest2 = src2;
- EXPECT_EQ(2U, dest2.length());
- EXPECT_STREQ("Hi", dest2.c_str());
- // An std::string with an embedded NUL character.
- const char src3[] = "a\0b";
- const String dest3 = std::string(src3, sizeof(src3));
- EXPECT_EQ(sizeof(src3), dest3.length());
- EXPECT_EQ('a', dest3.c_str()[0]);
- EXPECT_EQ('\0', dest3.c_str()[1]);
- EXPECT_EQ('b', dest3.c_str()[2]);
- }
- TEST(StringTest, ConvertsToStdString) {
- // An empty String.
- const String src1("");
- const std::string dest1 = src1;
- EXPECT_EQ("", dest1);
- // A normal String.
- const String src2("Hi");
- const std::string dest2 = src2;
- EXPECT_EQ("Hi", dest2);
- // A String containing a '\0'.
- const String src3("x\0y", 3);
- const std::string dest3 = src3;
- EXPECT_EQ(std::string("x\0y", 3), dest3);
- }
- #endif // GTEST_HAS_STD_STRING
- #if GTEST_HAS_GLOBAL_STRING
- TEST(StringTest, ConvertsFromGlobalString) {
- // An empty ::string.
- const ::string src1("");
- const String dest1 = src1;
- EXPECT_EQ(0U, dest1.length());
- EXPECT_STREQ("", dest1.c_str());
- // A normal ::string.
- const ::string src2("Hi");
- const String dest2 = src2;
- EXPECT_EQ(2U, dest2.length());
- EXPECT_STREQ("Hi", dest2.c_str());
- // An ::string with an embedded NUL character.
- const char src3[] = "x\0y";
- const String dest3 = ::string(src3, sizeof(src3));
- EXPECT_EQ(sizeof(src3), dest3.length());
- EXPECT_EQ('x', dest3.c_str()[0]);
- EXPECT_EQ('\0', dest3.c_str()[1]);
- EXPECT_EQ('y', dest3.c_str()[2]);
- }
- TEST(StringTest, ConvertsToGlobalString) {
- // An empty String.
- const String src1("");
- const ::string dest1 = src1;
- EXPECT_EQ("", dest1);
- // A normal String.
- const String src2("Hi");
- const ::string dest2 = src2;
- EXPECT_EQ("Hi", dest2);
- const String src3("x\0y", 3);
- const ::string dest3 = src3;
- EXPECT_EQ(::string("x\0y", 3), dest3);
- }
- #endif // GTEST_HAS_GLOBAL_STRING
- // Tests String::ShowCStringQuoted().
- TEST(StringTest, ShowCStringQuoted) {
- EXPECT_STREQ("(null)",
- String::ShowCStringQuoted(NULL).c_str());
- EXPECT_STREQ("\"\"",
- String::ShowCStringQuoted("").c_str());
- EXPECT_STREQ("\"foo\"",
- String::ShowCStringQuoted("foo").c_str());
- }
- // Tests String::empty().
- TEST(StringTest, Empty) {
- EXPECT_TRUE(String("").empty());
- EXPECT_FALSE(String().empty());
- EXPECT_FALSE(String(NULL).empty());
- EXPECT_FALSE(String("a").empty());
- EXPECT_FALSE(String("\0", 1).empty());
- }
- // Tests String::Compare().
- TEST(StringTest, Compare) {
- // NULL vs NULL.
- EXPECT_EQ(0, String().Compare(String()));
- // NULL vs non-NULL.
- EXPECT_EQ(-1, String().Compare(String("")));
- // Non-NULL vs NULL.
- EXPECT_EQ(1, String("").Compare(String()));
- // The following covers non-NULL vs non-NULL.
- // "" vs "".
- EXPECT_EQ(0, String("").Compare(String("")));
- // "" vs non-"".
- EXPECT_EQ(-1, String("").Compare(String("\0", 1)));
- EXPECT_EQ(-1, String("").Compare(" "));
- // Non-"" vs "".
- EXPECT_EQ(1, String("a").Compare(String("")));
- // The following covers non-"" vs non-"".
- // Same length and equal.
- EXPECT_EQ(0, String("a").Compare(String("a")));
- // Same length and different.
- EXPECT_EQ(-1, String("a\0b", 3).Compare(String("a\0c", 3)));
- EXPECT_EQ(1, String("b").Compare(String("a")));
- // Different lengths.
- EXPECT_EQ(-1, String("a").Compare(String("ab")));
- EXPECT_EQ(-1, String("a").Compare(String("a\0", 2)));
- EXPECT_EQ(1, String("abc").Compare(String("aacd")));
- }
- // Tests String::operator==().
- TEST(StringTest, Equals) {
- const String null(NULL);
- EXPECT_TRUE(null == NULL); // NOLINT
- EXPECT_FALSE(null == ""); // NOLINT
- EXPECT_FALSE(null == "bar"); // NOLINT
- const String empty("");
- EXPECT_FALSE(empty == NULL); // NOLINT
- EXPECT_TRUE(empty == ""); // NOLINT
- EXPECT_FALSE(empty == "bar"); // NOLINT
- const String foo("foo");
- EXPECT_FALSE(foo == NULL); // NOLINT
- EXPECT_FALSE(foo == ""); // NOLINT
- EXPECT_FALSE(foo == "bar"); // NOLINT
- EXPECT_TRUE(foo == "foo"); // NOLINT
- const String bar("x\0y", 3);
- EXPECT_FALSE(bar == "x");
- }
- // Tests String::operator!=().
- TEST(StringTest, NotEquals) {
- const String null(NULL);
- EXPECT_FALSE(null != NULL); // NOLINT
- EXPECT_TRUE(null != ""); // NOLINT
- EXPECT_TRUE(null != "bar"); // NOLINT
- const String empty("");
- EXPECT_TRUE(empty != NULL); // NOLINT
- EXPECT_FALSE(empty != ""); // NOLINT
- EXPECT_TRUE(empty != "bar"); // NOLINT
- const String foo("foo");
- EXPECT_TRUE(foo != NULL); // NOLINT
- EXPECT_TRUE(foo != ""); // NOLINT
- EXPECT_TRUE(foo != "bar"); // NOLINT
- EXPECT_FALSE(foo != "foo"); // NOLINT
- const String bar("x\0y", 3);
- EXPECT_TRUE(bar != "x");
- }
- // Tests String::length().
- TEST(StringTest, Length) {
- EXPECT_EQ(0U, String().length());
- EXPECT_EQ(0U, String("").length());
- EXPECT_EQ(2U, String("ab").length());
- EXPECT_EQ(3U, String("a\0b", 3).length());
- }
- // Tests String::EndsWith().
- TEST(StringTest, EndsWith) {
- EXPECT_TRUE(String("foobar").EndsWith("bar"));
- EXPECT_TRUE(String("foobar").EndsWith(""));
- EXPECT_TRUE(String("").EndsWith(""));
- EXPECT_FALSE(String("foobar").EndsWith("foo"));
- EXPECT_FALSE(String("").EndsWith("foo"));
- }
- // Tests String::EndsWithCaseInsensitive().
- TEST(StringTest, EndsWithCaseInsensitive) {
- EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
- EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
- EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
- EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
- EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
- EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
- EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
- }
- // C++Builder's preprocessor is buggy; it fails to expand macros that
- // appear in macro parameters after wide char literals. Provide an alias
- // for NULL as a workaround.
- static const wchar_t* const kNull = NULL;
- // Tests String::CaseInsensitiveWideCStringEquals
- TEST(StringTest, CaseInsensitiveWideCStringEquals) {
- EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
- EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
- EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
- EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
- EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
- EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
- EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
- EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
- }
- // Tests that NULL can be assigned to a String.
- TEST(StringTest, CanBeAssignedNULL) {
- const String src(NULL);
- String dest;
- dest = src;
- EXPECT_STREQ(NULL, dest.c_str());
- }
- // Tests that the empty string "" can be assigned to a String.
- TEST(StringTest, CanBeAssignedEmpty) {
- const String src("");
- String dest;
- dest = src;
- EXPECT_STREQ("", dest.c_str());
- }
- // Tests that a non-empty string can be assigned to a String.
- TEST(StringTest, CanBeAssignedNonEmpty) {
- const String src("hello");
- String dest;
- dest = src;
- EXPECT_EQ(5U, dest.length());
- EXPECT_STREQ("hello", dest.c_str());
- const String src2("x\0y", 3);
- String dest2;
- dest2 = src2;
- EXPECT_EQ(3U, dest2.length());
- EXPECT_EQ('x', dest2.c_str()[0]);
- EXPECT_EQ('\0', dest2.c_str()[1]);
- EXPECT_EQ('y', dest2.c_str()[2]);
- }
- // Tests that a String can be assigned to itself.
- TEST(StringTest, CanBeAssignedSelf) {
- String dest("hello");
- dest = dest;
- EXPECT_STREQ("hello", dest.c_str());
- }
- // Tests streaming a String.
- TEST(StringTest, Streams) {
- EXPECT_EQ(StreamableToString(String()), "(null)");
- EXPECT_EQ(StreamableToString(String("")), "");
- EXPECT_EQ(StreamableToString(String("a\0b", 3)), "a\\0b");
- }
- // Tests that String::Format() works.
- TEST(StringTest, FormatWorks) {
- // Normal case: the format spec is valid, the arguments match the
- // spec, and the result is < 4095 characters.
- EXPECT_STREQ("Hello, 42", String::Format("%s, %d", "Hello", 42).c_str());
- // Edge case: the result is 4095 characters.
- char buffer[4096];
- const size_t kSize = sizeof(buffer);
- memset(buffer, 'a', kSize - 1);
- buffer[kSize - 1] = '\0';
- EXPECT_STREQ(buffer, String::Format("%s", buffer).c_str());
- // The result needs to be 4096 characters, exceeding Format()'s limit.
- EXPECT_STREQ("<formatting error or buffer exceeded>",
- String::Format("x%s", buffer).c_str());
- #if GTEST_OS_LINUX
- // On Linux, invalid format spec should lead to an error message.
- // In other environment (e.g. MSVC on Windows), String::Format() may
- // simply ignore a bad format spec, so this assertion is run on
- // Linux only.
- EXPECT_STREQ("<formatting error or buffer exceeded>",
- String::Format("%").c_str());
- #endif
- }
- #if GTEST_OS_WINDOWS
- // Tests String::ShowWideCString().
- TEST(StringTest, ShowWideCString) {
- EXPECT_STREQ("(null)",
- String::ShowWideCString(NULL).c_str());
- EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
- EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
- }
- // Tests String::ShowWideCStringQuoted().
- TEST(StringTest, ShowWideCStringQuoted) {
- EXPECT_STREQ("(null)",
- String::ShowWideCStringQuoted(NULL).c_str());
- EXPECT_STREQ("L\"\"",
- String::ShowWideCStringQuoted(L"").c_str());
- EXPECT_STREQ("L\"foo\"",
- String::ShowWideCStringQuoted(L"foo").c_str());
- }
- #if GTEST_OS_WINDOWS_MOBILE
- TEST(StringTest, AnsiAndUtf16Null) {
- EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
- EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
- }
- TEST(StringTest, AnsiAndUtf16ConvertBasic) {
- const char* ansi = String::Utf16ToAnsi(L"str");
- EXPECT_STREQ("str", ansi);
- delete [] ansi;
- const WCHAR* utf16 = String::AnsiToUtf16("str");
- EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
- delete [] utf16;
- }
- TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
- const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
- EXPECT_STREQ(".:\\ \"*?", ansi);
- delete [] ansi;
- const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
- EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
- delete [] utf16;
- }
- #endif // GTEST_OS_WINDOWS_MOBILE
- #endif // GTEST_OS_WINDOWS
- // Tests TestProperty construction.
- TEST(TestPropertyTest, StringValue) {
- TestProperty property("key", "1");
- EXPECT_STREQ("key", property.key());
- EXPECT_STREQ("1", property.value());
- }
- // Tests TestProperty replacing a value.
- TEST(TestPropertyTest, ReplaceStringValue) {
- TestProperty property("key", "1");
- EXPECT_STREQ("1", property.value());
- property.SetValue("2");
- EXPECT_STREQ("2", property.value());
- }
- // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
- // functions (i.e. their definitions cannot be inlined at the call
- // sites), or C++Builder won't compile the code.
- static void AddFatalFailure() {
- FAIL() << "Expected fatal failure.";
- }
- static void AddNonfatalFailure() {
- ADD_FAILURE() << "Expected non-fatal failure.";
- }
- class ScopedFakeTestPartResultReporterTest : public Test {
- public: // Must be public and not protected due to a bug in g++ 3.4.2.
- enum FailureMode {
- FATAL_FAILURE,
- NONFATAL_FAILURE
- };
- static void AddFailure(FailureMode failure) {
- if (failure == FATAL_FAILURE) {
- AddFatalFailure();
- } else {
- AddNonfatalFailure();
- }
- }
- };
- // Tests that ScopedFakeTestPartResultReporter intercepts test
- // failures.
- TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
- TestPartResultArray results;
- {
- ScopedFakeTestPartResultReporter reporter(
- ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
- &results);
- AddFailure(NONFATAL_FAILURE);
- AddFailure(FATAL_FAILURE);
- }
- EXPECT_EQ(2, results.size());
- EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
- EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
- }
- TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
- TestPartResultArray results;
- {
- // Tests, that the deprecated constructor still works.
- ScopedFakeTestPartResultReporter reporter(&results);
- AddFailure(NONFATAL_FAILURE);
- }
- EXPECT_EQ(1, results.size());
- }
- #if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
- class ScopedFakeTestPartResultReporterWithThreadsTest
- : public ScopedFakeTestPartResultReporterTest {
- protected:
- static void AddFailureInOtherThread(FailureMode failure) {
- pthread_t tid;
- pthread_create(&tid,
- NULL,
- ScopedFakeTestPartResultReporterWithThreadsTest::
- FailureThread,
- &failure);
- pthread_join(tid, NULL);
- }
- private:
- static void* FailureThread(void* attr) {
- FailureMode* failure = static_cast<FailureMode*>(attr);
- AddFailure(*failure);
- return NULL;
- }
- };
- TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
- InterceptsTestFailuresInAllThreads) {
- TestPartResultArray results;
- {
- ScopedFakeTestPartResultReporter reporter(
- ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
- AddFailure(NONFATAL_FAILURE);
- AddFailure(FATAL_FAILURE);
- AddFailureInOtherThread(NONFATAL_FAILURE);
- AddFailureInOtherThread(FATAL_FAILURE);
- }
- EXPECT_EQ(4, results.size());
- EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
- EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
- EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
- EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
- }
- #endif // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
- // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
- // work even if the failure is generated in a called function rather than
- // the current context.
- typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
- TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
- EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
- }…