media/webrtc/trunk/testing/gtest/test/gtest_unittest.cc

Wed, 31 Dec 2014 13:27:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 13:27:57 +0100
branch
TOR_BUG_3246
changeset 6
8bccb770b82d
permissions
-rw-r--r--

Ignore runtime configuration files generated during quality assurance.

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

mercurial