1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: wan@google.com (Zhanyong Wan)
32 // Tests for Google Test itself. This verifies that the basic constructs of
35 #include <gtest/gtest.h>
38 // Verifies that the command line flag variables can be accessed
39 // in code once <gtest/gtest.h> has been #included.
40 // Do not move it after other #includes.
41 TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
42 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
43 || testing::GTEST_FLAG(break_on_failure)
44 || testing::GTEST_FLAG(catch_exceptions)
45 || testing::GTEST_FLAG(color) != "unknown"
46 || testing::GTEST_FLAG(filter) != "unknown"
47 || testing::GTEST_FLAG(list_tests)
48 || testing::GTEST_FLAG(output) != "unknown"
49 || testing::GTEST_FLAG(print_time)
50 || testing::GTEST_FLAG(random_seed)
51 || testing::GTEST_FLAG(repeat) > 0
52 || testing::GTEST_FLAG(show_internal_stack_frames)
53 || testing::GTEST_FLAG(shuffle)
54 || testing::GTEST_FLAG(stack_trace_depth) > 0
55 || testing::GTEST_FLAG(throw_on_failure);
56 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
59 #include <gtest/gtest-spi.h>
61 // Indicates that this translation unit is part of Google Test's
62 // implementation. It must come before gtest-internal-inl.h is
63 // included, or there will be a compiler error. This trick is to
64 // prevent a user from accidentally including gtest-internal-inl.h in
66 #define GTEST_IMPLEMENTATION_ 1
67 #include "src/gtest-internal-inl.h"
68 #undef GTEST_IMPLEMENTATION_
70 #include <limits.h> // For INT_MAX.
79 // Provides access to otherwise private parts of the TestEventListeners class
80 // that are needed to test it.
81 class TestEventListenersAccessor {
83 static TestEventListener* GetRepeater(TestEventListeners* listeners) {
84 return listeners->repeater();
87 static void SetDefaultResultPrinter(TestEventListeners* listeners,
88 TestEventListener* listener) {
89 listeners->SetDefaultResultPrinter(listener);
91 static void SetDefaultXmlGenerator(TestEventListeners* listeners,
92 TestEventListener* listener) {
93 listeners->SetDefaultXmlGenerator(listener);
96 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
97 return listeners.EventForwardingEnabled();
100 static void SuppressEventForwarding(TestEventListeners* listeners) {
101 listeners->SuppressEventForwarding();
105 } // namespace internal
106 } // namespace testing
108 using testing::AssertionFailure;
109 using testing::AssertionResult;
110 using testing::AssertionSuccess;
111 using testing::DoubleLE;
112 using testing::EmptyTestEventListener;
113 using testing::FloatLE;
114 using testing::GTEST_FLAG(also_run_disabled_tests);
115 using testing::GTEST_FLAG(break_on_failure);
116 using testing::GTEST_FLAG(catch_exceptions);
117 using testing::GTEST_FLAG(color);
118 using testing::GTEST_FLAG(death_test_use_fork);
119 using testing::GTEST_FLAG(filter);
120 using testing::GTEST_FLAG(list_tests);
121 using testing::GTEST_FLAG(output);
122 using testing::GTEST_FLAG(print_time);
123 using testing::GTEST_FLAG(random_seed);
124 using testing::GTEST_FLAG(repeat);
125 using testing::GTEST_FLAG(show_internal_stack_frames);
126 using testing::GTEST_FLAG(shuffle);
127 using testing::GTEST_FLAG(stack_trace_depth);
128 using testing::GTEST_FLAG(throw_on_failure);
129 using testing::IsNotSubstring;
130 using testing::IsSubstring;
131 using testing::Message;
132 using testing::ScopedFakeTestPartResultReporter;
133 using testing::StaticAssertTypeEq;
135 using testing::TestEventListeners;
136 using testing::TestCase;
137 using testing::TestPartResult;
138 using testing::TestPartResultArray;
139 using testing::TestProperty;
140 using testing::TestResult;
141 using testing::UnitTest;
142 using testing::kMaxStackTraceDepth;
143 using testing::internal::AlwaysFalse;
144 using testing::internal::AlwaysTrue;
145 using testing::internal::AppendUserMessage;
146 using testing::internal::CodePointToUtf8;
147 using testing::internal::CountIf;
148 using testing::internal::EqFailure;
149 using testing::internal::FloatingPoint;
150 using testing::internal::FormatTimeInMillisAsSeconds;
151 using testing::internal::ForEach;
152 using testing::internal::GTestFlagSaver;
153 using testing::internal::GetCurrentOsStackTraceExceptTop;
154 using testing::internal::GetElementOr;
155 using testing::internal::GetNextRandomSeed;
156 using testing::internal::GetRandomSeedFromFlag;
157 using testing::internal::GetTestTypeId;
158 using testing::internal::GetTypeId;
159 using testing::internal::GetUnitTestImpl;
160 using testing::internal::Int32;
161 using testing::internal::Int32FromEnvOrDie;
162 using testing::internal::ParseInt32Flag;
163 using testing::internal::ShouldRunTestOnShard;
164 using testing::internal::ShouldShard;
165 using testing::internal::ShouldUseColor;
166 using testing::internal::Shuffle;
167 using testing::internal::ShuffleRange;
168 using testing::internal::StreamableToString;
169 using testing::internal::String;
170 using testing::internal::TestEventListenersAccessor;
171 using testing::internal::TestResultAccessor;
172 using testing::internal::UInt32;
173 using testing::internal::WideStringToUtf8;
174 using testing::internal::kMaxRandomSeed;
175 using testing::internal::kTestTypeIdInGoogleTest;
176 using testing::internal::scoped_ptr;
178 #if GTEST_HAS_STREAM_REDIRECTION_
179 using testing::internal::CaptureStdout;
180 using testing::internal::GetCapturedStdout;
181 #endif // GTEST_HAS_STREAM_REDIRECTION_
183 #if GTEST_IS_THREADSAFE
184 using testing::internal::ThreadWithParam;
187 class TestingVector : public std::vector<int> {
190 ::std::ostream& operator<<(::std::ostream& os,
191 const TestingVector& vector) {
193 for (size_t i = 0; i < vector.size(); i++) {
194 os << vector[i] << " ";
200 // This line tests that we can define tests in an unnamed namespace.
203 TEST(GetRandomSeedFromFlagTest, HandlesZero) {
204 const int seed = GetRandomSeedFromFlag(0);
206 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
209 TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
210 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
211 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
212 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
213 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
214 GetRandomSeedFromFlag(kMaxRandomSeed));
217 TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
218 const int seed1 = GetRandomSeedFromFlag(-1);
220 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
222 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
224 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
227 TEST(GetNextRandomSeedTest, WorksForValidInput) {
228 EXPECT_EQ(2, GetNextRandomSeed(1));
229 EXPECT_EQ(3, GetNextRandomSeed(2));
230 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
231 GetNextRandomSeed(kMaxRandomSeed - 1));
232 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
234 // We deliberately don't test GetNextRandomSeed() with invalid
235 // inputs, as that requires death tests, which are expensive. This
236 // is fine as GetNextRandomSeed() is internal and has a
237 // straightforward definition.
240 static void ClearCurrentTestPartResults() {
241 TestResultAccessor::ClearTestPartResults(
242 GetUnitTestImpl()->current_test_result());
247 TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
248 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
249 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
252 class SubClassOfTest : public Test {};
253 class AnotherSubClassOfTest : public Test {};
255 TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
256 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
257 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
258 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
259 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
260 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
261 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
264 // Verifies that GetTestTypeId() returns the same value, no matter it
265 // is called from inside Google Test or outside of it.
266 TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
267 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
270 // Tests FormatTimeInMillisAsSeconds().
272 TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
273 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
276 TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
277 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
278 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
279 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
280 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
281 EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
284 TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
285 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
286 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
287 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
288 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
289 EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
292 #if GTEST_CAN_COMPARE_NULL
295 // Silences warnings: "Condition is always true", "Unreachable code"
296 #pragma option push -w-ccc -w-rch
299 // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
301 TEST(NullLiteralTest, IsTrueForNullLiterals) {
302 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
303 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
304 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
305 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
306 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(false));
308 // Some compilers may fail to detect some null pointer literals;
309 // as long as users of the framework don't use such literals, this
311 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1));
312 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(true && false));
316 // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
318 TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
319 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
320 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
321 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
322 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
326 // Restores warnings after previous "#pragma option push" suppressed them.
330 #endif // GTEST_CAN_COMPARE_NULL
332 // Tests CodePointToUtf8().
334 // Tests that the NUL character L'\0' is encoded correctly.
335 TEST(CodePointToUtf8Test, CanEncodeNul) {
337 EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer));
340 // Tests that ASCII characters are encoded correctly.
341 TEST(CodePointToUtf8Test, CanEncodeAscii) {
343 EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer));
344 EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer));
345 EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer));
346 EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer));
349 // Tests that Unicode code-points that have 8 to 11 bits are encoded
350 // as 110xxxxx 10xxxxxx.
351 TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
353 // 000 1101 0011 => 110-00011 10-010011
354 EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer));
356 // 101 0111 0110 => 110-10101 10-110110
357 EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(L'\x576', buffer));
360 // Tests that Unicode code-points that have 12 to 16 bits are encoded
361 // as 1110xxxx 10xxxxxx 10xxxxxx.
362 TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
364 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
365 EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(L'\x8D3', buffer));
367 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
368 EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(L'\xC74D', buffer));
371 #if !GTEST_WIDE_STRING_USES_UTF16_
372 // Tests in this group require a wchar_t to hold > 16 bits, and thus
373 // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
374 // 16-bit wide. This code may not compile on those systems.
376 // Tests that Unicode code-points that have 17 to 21 bits are encoded
377 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
378 TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
380 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
381 EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer));
383 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
384 EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer));
386 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
387 EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer));
390 // Tests that encoding an invalid code-point generates the expected result.
391 TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
393 EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
394 CodePointToUtf8(L'\x1234ABCD', buffer));
397 #endif // !GTEST_WIDE_STRING_USES_UTF16_
399 // Tests WideStringToUtf8().
401 // Tests that the NUL character L'\0' is encoded correctly.
402 TEST(WideStringToUtf8Test, CanEncodeNul) {
403 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
404 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
407 // Tests that ASCII strings are encoded correctly.
408 TEST(WideStringToUtf8Test, CanEncodeAscii) {
409 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
410 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
411 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
412 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
415 // Tests that Unicode code-points that have 8 to 11 bits are encoded
416 // as 110xxxxx 10xxxxxx.
417 TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
418 // 000 1101 0011 => 110-00011 10-010011
419 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
420 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
422 // 101 0111 0110 => 110-10101 10-110110
423 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", 1).c_str());
424 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", -1).c_str());
427 // Tests that Unicode code-points that have 12 to 16 bits are encoded
428 // as 1110xxxx 10xxxxxx 10xxxxxx.
429 TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
430 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
431 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", 1).c_str());
432 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", -1).c_str());
434 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
435 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", 1).c_str());
436 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", -1).c_str());
439 // Tests that the conversion stops when the function encounters \0 character.
440 TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
441 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
444 // Tests that the conversion stops when the function reaches the limit
445 // specified by the 'length' parameter.
446 TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
447 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
451 #if !GTEST_WIDE_STRING_USES_UTF16_
452 // Tests that Unicode code-points that have 17 to 21 bits are encoded
453 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
454 // on the systems using UTF-16 encoding.
455 TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
456 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
457 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
458 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
460 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
461 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
462 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
465 // Tests that encoding an invalid code-point generates the expected result.
466 TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
467 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
468 WideStringToUtf8(L"\xABCDFF", -1).c_str());
470 #else // !GTEST_WIDE_STRING_USES_UTF16_
471 // Tests that surrogate pairs are encoded correctly on the systems using
472 // UTF-16 encoding in the wide strings.
473 TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
474 EXPECT_STREQ("\xF0\x90\x90\x80",
475 WideStringToUtf8(L"\xD801\xDC00", -1).c_str());
478 // Tests that encoding an invalid UTF-16 surrogate pair
479 // generates the expected result.
480 TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
481 // Leading surrogate is at the end of the string.
482 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(L"\xD800", -1).c_str());
483 // Leading surrogate is not followed by the trailing surrogate.
484 EXPECT_STREQ("\xED\xA0\x80$", WideStringToUtf8(L"\xD800$", -1).c_str());
485 // Trailing surrogate appearas without a leading surrogate.
486 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(L"\xDC00PQR", -1).c_str());
488 #endif // !GTEST_WIDE_STRING_USES_UTF16_
490 // Tests that codepoint concatenation works correctly.
491 #if !GTEST_WIDE_STRING_USES_UTF16_
492 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
500 WideStringToUtf8(L"\x108634\xC74D\n\x576\x8D3\x108634", -1).c_str());
503 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
505 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
506 WideStringToUtf8(L"\xC74D\n\x576\x8D3", -1).c_str());
508 #endif // !GTEST_WIDE_STRING_USES_UTF16_
510 // Tests the Random class.
512 TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
513 testing::internal::Random random(42);
514 EXPECT_DEATH_IF_SUPPORTED(
516 "Cannot generate a number in the range \\[0, 0\\)");
517 EXPECT_DEATH_IF_SUPPORTED(
518 random.Generate(testing::internal::Random::kMaxRange + 1),
519 "Generation of a number in \\[0, 2147483649\\) was requested, "
520 "but this can only generate numbers in \\[0, 2147483648\\)");
523 TEST(RandomTest, GeneratesNumbersWithinRange) {
524 const UInt32 kRange = 10000;
525 testing::internal::Random random(12345);
526 for (int i = 0; i < 10; i++) {
527 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
530 testing::internal::Random random2(testing::internal::Random::kMaxRange);
531 for (int i = 0; i < 10; i++) {
532 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
536 TEST(RandomTest, RepeatsWhenReseeded) {
537 const int kSeed = 123;
538 const int kArraySize = 10;
539 const UInt32 kRange = 10000;
540 UInt32 values[kArraySize];
542 testing::internal::Random random(kSeed);
543 for (int i = 0; i < kArraySize; i++) {
544 values[i] = random.Generate(kRange);
547 random.Reseed(kSeed);
548 for (int i = 0; i < kArraySize; i++) {
549 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
553 // Tests STL container utilities.
557 static bool IsPositive(int n) { return n > 0; }
559 TEST(ContainerUtilityTest, CountIf) {
561 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
565 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
570 EXPECT_EQ(2, CountIf(v, IsPositive));
575 static int g_sum = 0;
576 static void Accumulate(int n) { g_sum += n; }
578 TEST(ContainerUtilityTest, ForEach) {
581 ForEach(v, Accumulate);
582 EXPECT_EQ(0, g_sum); // Works for an empty container;
586 ForEach(v, Accumulate);
587 EXPECT_EQ(1, g_sum); // Works for a container with one element.
592 ForEach(v, Accumulate);
593 EXPECT_EQ(321, g_sum);
596 // Tests GetElementOr().
597 TEST(ContainerUtilityTest, GetElementOr) {
599 EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
603 EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
604 EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
605 EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
606 EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
609 TEST(ContainerUtilityDeathTest, ShuffleRange) {
614 testing::internal::Random random(1);
616 EXPECT_DEATH_IF_SUPPORTED(
617 ShuffleRange(&random, -1, 1, &a),
618 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
619 EXPECT_DEATH_IF_SUPPORTED(
620 ShuffleRange(&random, 4, 4, &a),
621 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
622 EXPECT_DEATH_IF_SUPPORTED(
623 ShuffleRange(&random, 3, 2, &a),
624 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
625 EXPECT_DEATH_IF_SUPPORTED(
626 ShuffleRange(&random, 3, 4, &a),
627 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
630 class VectorShuffleTest : public Test {
632 static const int kVectorSize = 20;
634 VectorShuffleTest() : random_(1) {
635 for (int i = 0; i < kVectorSize; i++) {
636 vector_.push_back(i);
640 static bool VectorIsCorrupt(const TestingVector& vector) {
641 if (kVectorSize != static_cast<int>(vector.size())) {
645 bool found_in_vector[kVectorSize] = { false };
646 for (size_t i = 0; i < vector.size(); i++) {
647 const int e = vector[i];
648 if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
651 found_in_vector[e] = true;
654 // Vector size is correct, elements' range is correct, no
655 // duplicate elements. Therefore no corruption has occurred.
659 static bool VectorIsNotCorrupt(const TestingVector& vector) {
660 return !VectorIsCorrupt(vector);
663 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
664 for (int i = begin; i < end; i++) {
665 if (i != vector[i]) {
672 static bool RangeIsUnshuffled(
673 const TestingVector& vector, int begin, int end) {
674 return !RangeIsShuffled(vector, begin, end);
677 static bool VectorIsShuffled(const TestingVector& vector) {
678 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
681 static bool VectorIsUnshuffled(const TestingVector& vector) {
682 return !VectorIsShuffled(vector);
685 testing::internal::Random random_;
686 TestingVector vector_;
687 }; // class VectorShuffleTest
689 const int VectorShuffleTest::kVectorSize;
691 TEST_F(VectorShuffleTest, HandlesEmptyRange) {
692 // Tests an empty range at the beginning...
693 ShuffleRange(&random_, 0, 0, &vector_);
694 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
695 ASSERT_PRED1(VectorIsUnshuffled, vector_);
697 // ...in the middle...
698 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
699 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
700 ASSERT_PRED1(VectorIsUnshuffled, vector_);
703 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
704 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
705 ASSERT_PRED1(VectorIsUnshuffled, vector_);
707 // ...and past the end.
708 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
709 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
710 ASSERT_PRED1(VectorIsUnshuffled, vector_);
713 TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
714 // Tests a size one range at the beginning...
715 ShuffleRange(&random_, 0, 1, &vector_);
716 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
717 ASSERT_PRED1(VectorIsUnshuffled, vector_);
719 // ...in the middle...
720 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
721 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
722 ASSERT_PRED1(VectorIsUnshuffled, vector_);
724 // ...and at the end.
725 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
726 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
727 ASSERT_PRED1(VectorIsUnshuffled, vector_);
730 // Because we use our own random number generator and a fixed seed,
731 // we can guarantee that the following "random" tests will succeed.
733 TEST_F(VectorShuffleTest, ShufflesEntireVector) {
734 Shuffle(&random_, &vector_);
735 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
736 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
738 // Tests the first and last elements in particular to ensure that
739 // there are no off-by-one problems in our shuffle algorithm.
740 EXPECT_NE(0, vector_[0]);
741 EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
744 TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
745 const int kRangeSize = kVectorSize/2;
747 ShuffleRange(&random_, 0, kRangeSize, &vector_);
749 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
750 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
751 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
754 TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
755 const int kRangeSize = kVectorSize / 2;
756 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
758 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
759 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
760 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
763 TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
764 int kRangeSize = kVectorSize/3;
765 ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
767 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
768 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
769 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
770 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
773 TEST_F(VectorShuffleTest, ShufflesRepeatably) {
774 TestingVector vector2;
775 for (int i = 0; i < kVectorSize; i++) {
776 vector2.push_back(i);
779 random_.Reseed(1234);
780 Shuffle(&random_, &vector_);
781 random_.Reseed(1234);
782 Shuffle(&random_, &vector2);
784 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
785 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
787 for (int i = 0; i < kVectorSize; i++) {
788 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
792 // Tests the size of the AssertHelper class.
794 TEST(AssertHelperTest, AssertHelperIsSmall) {
795 // To avoid breaking clients that use lots of assertions in one
796 // function, we cannot grow the size of AssertHelper.
797 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
800 // Tests the String class.
802 // Tests String's constructors.
803 TEST(StringTest, Constructors) {
806 // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
807 // pointers with NULL isn't supported on all platforms.
808 EXPECT_EQ(0U, s1.length());
809 EXPECT_TRUE(NULL == s1.c_str());
811 // Implicitly constructs from a C-string.
813 EXPECT_EQ(2U, s2.length());
814 EXPECT_STREQ("Hi", s2.c_str());
816 // Constructs from a C-string and a length.
817 String s3("hello", 3);
818 EXPECT_EQ(3U, s3.length());
819 EXPECT_STREQ("hel", s3.c_str());
821 // The empty String should be created when String is constructed with
822 // a NULL pointer and length 0.
823 EXPECT_EQ(0U, String(NULL, 0).length());
824 EXPECT_FALSE(String(NULL, 0).c_str() == NULL);
826 // Constructs a String that contains '\0'.
827 String s4("a\0bcd", 4);
828 EXPECT_EQ(4U, s4.length());
829 EXPECT_EQ('a', s4.c_str()[0]);
830 EXPECT_EQ('\0', s4.c_str()[1]);
831 EXPECT_EQ('b', s4.c_str()[2]);
832 EXPECT_EQ('c', s4.c_str()[3]);
834 // Copy ctor where the source is NULL.
835 const String null_str;
836 String s5 = null_str;
837 EXPECT_TRUE(s5.c_str() == NULL);
839 // Copy ctor where the source isn't NULL.
841 EXPECT_EQ(3U, s6.length());
842 EXPECT_STREQ("hel", s6.c_str());
844 // Copy ctor where the source contains '\0'.
846 EXPECT_EQ(4U, s7.length());
847 EXPECT_EQ('a', s7.c_str()[0]);
848 EXPECT_EQ('\0', s7.c_str()[1]);
849 EXPECT_EQ('b', s7.c_str()[2]);
850 EXPECT_EQ('c', s7.c_str()[3]);
853 TEST(StringTest, ConvertsFromStdString) {
854 // An empty std::string.
855 const std::string src1("");
856 const String dest1 = src1;
857 EXPECT_EQ(0U, dest1.length());
858 EXPECT_STREQ("", dest1.c_str());
860 // A normal std::string.
861 const std::string src2("Hi");
862 const String dest2 = src2;
863 EXPECT_EQ(2U, dest2.length());
864 EXPECT_STREQ("Hi", dest2.c_str());
866 // An std::string with an embedded NUL character.
867 const char src3[] = "a\0b";
868 const String dest3 = std::string(src3, sizeof(src3));
869 EXPECT_EQ(sizeof(src3), dest3.length());
870 EXPECT_EQ('a', dest3.c_str()[0]);
871 EXPECT_EQ('\0', dest3.c_str()[1]);
872 EXPECT_EQ('b', dest3.c_str()[2]);
875 TEST(StringTest, ConvertsToStdString) {
877 const String src1("");
878 const std::string dest1 = src1;
879 EXPECT_EQ("", dest1);
882 const String src2("Hi");
883 const std::string dest2 = src2;
884 EXPECT_EQ("Hi", dest2);
886 // A String containing a '\0'.
887 const String src3("x\0y", 3);
888 const std::string dest3 = src3;
889 EXPECT_EQ(std::string("x\0y", 3), dest3);
892 #if GTEST_HAS_GLOBAL_STRING
894 TEST(StringTest, ConvertsFromGlobalString) {
895 // An empty ::string.
896 const ::string src1("");
897 const String dest1 = src1;
898 EXPECT_EQ(0U, dest1.length());
899 EXPECT_STREQ("", dest1.c_str());
901 // A normal ::string.
902 const ::string src2("Hi");
903 const String dest2 = src2;
904 EXPECT_EQ(2U, dest2.length());
905 EXPECT_STREQ("Hi", dest2.c_str());
907 // An ::string with an embedded NUL character.
908 const char src3[] = "x\0y";
909 const String dest3 = ::string(src3, sizeof(src3));
910 EXPECT_EQ(sizeof(src3), dest3.length());
911 EXPECT_EQ('x', dest3.c_str()[0]);
912 EXPECT_EQ('\0', dest3.c_str()[1]);
913 EXPECT_EQ('y', dest3.c_str()[2]);
916 TEST(StringTest, ConvertsToGlobalString) {
918 const String src1("");
919 const ::string dest1 = src1;
920 EXPECT_EQ("", dest1);
923 const String src2("Hi");
924 const ::string dest2 = src2;
925 EXPECT_EQ("Hi", dest2);
927 const String src3("x\0y", 3);
928 const ::string dest3 = src3;
929 EXPECT_EQ(::string("x\0y", 3), dest3);
932 #endif // GTEST_HAS_GLOBAL_STRING
934 // Tests String::ShowCStringQuoted().
935 TEST(StringTest, ShowCStringQuoted) {
936 EXPECT_STREQ("(null)",
937 String::ShowCStringQuoted(NULL).c_str());
939 String::ShowCStringQuoted("").c_str());
940 EXPECT_STREQ("\"foo\"",
941 String::ShowCStringQuoted("foo").c_str());
944 // Tests String::empty().
945 TEST(StringTest, Empty) {
946 EXPECT_TRUE(String("").empty());
947 EXPECT_FALSE(String().empty());
948 EXPECT_FALSE(String(NULL).empty());
949 EXPECT_FALSE(String("a").empty());
950 EXPECT_FALSE(String("\0", 1).empty());
953 // Tests String::Compare().
954 TEST(StringTest, Compare) {
956 EXPECT_EQ(0, String().Compare(String()));
959 EXPECT_EQ(-1, String().Compare(String("")));
962 EXPECT_EQ(1, String("").Compare(String()));
964 // The following covers non-NULL vs non-NULL.
967 EXPECT_EQ(0, String("").Compare(String("")));
970 EXPECT_EQ(-1, String("").Compare(String("\0", 1)));
971 EXPECT_EQ(-1, String("").Compare(" "));
974 EXPECT_EQ(1, String("a").Compare(String("")));
976 // The following covers non-"" vs non-"".
978 // Same length and equal.
979 EXPECT_EQ(0, String("a").Compare(String("a")));
981 // Same length and different.
982 EXPECT_EQ(-1, String("a\0b", 3).Compare(String("a\0c", 3)));
983 EXPECT_EQ(1, String("b").Compare(String("a")));
985 // Different lengths.
986 EXPECT_EQ(-1, String("a").Compare(String("ab")));
987 EXPECT_EQ(-1, String("a").Compare(String("a\0", 2)));
988 EXPECT_EQ(1, String("abc").Compare(String("aacd")));
991 // Tests String::operator==().
992 TEST(StringTest, Equals) {
993 const String null(NULL);
994 EXPECT_TRUE(null == NULL); // NOLINT
995 EXPECT_FALSE(null == ""); // NOLINT
996 EXPECT_FALSE(null == "bar"); // NOLINT
998 const String empty("");
999 EXPECT_FALSE(empty == NULL); // NOLINT
1000 EXPECT_TRUE(empty == ""); // NOLINT
1001 EXPECT_FALSE(empty == "bar"); // NOLINT
1003 const String foo("foo");
1004 EXPECT_FALSE(foo == NULL); // NOLINT
1005 EXPECT_FALSE(foo == ""); // NOLINT
1006 EXPECT_FALSE(foo == "bar"); // NOLINT
1007 EXPECT_TRUE(foo == "foo"); // NOLINT
1009 const String bar("x\0y", 3);
1010 EXPECT_FALSE(bar == "x");
1013 // Tests String::operator!=().
1014 TEST(StringTest, NotEquals) {
1015 const String null(NULL);
1016 EXPECT_FALSE(null != NULL); // NOLINT
1017 EXPECT_TRUE(null != ""); // NOLINT
1018 EXPECT_TRUE(null != "bar"); // NOLINT
1020 const String empty("");
1021 EXPECT_TRUE(empty != NULL); // NOLINT
1022 EXPECT_FALSE(empty != ""); // NOLINT
1023 EXPECT_TRUE(empty != "bar"); // NOLINT
1025 const String foo("foo");
1026 EXPECT_TRUE(foo != NULL); // NOLINT
1027 EXPECT_TRUE(foo != ""); // NOLINT
1028 EXPECT_TRUE(foo != "bar"); // NOLINT
1029 EXPECT_FALSE(foo != "foo"); // NOLINT
1031 const String bar("x\0y", 3);
1032 EXPECT_TRUE(bar != "x");
1035 // Tests String::length().
1036 TEST(StringTest, Length) {
1037 EXPECT_EQ(0U, String().length());
1038 EXPECT_EQ(0U, String("").length());
1039 EXPECT_EQ(2U, String("ab").length());
1040 EXPECT_EQ(3U, String("a\0b", 3).length());
1043 // Tests String::EndsWith().
1044 TEST(StringTest, EndsWith) {
1045 EXPECT_TRUE(String("foobar").EndsWith("bar"));
1046 EXPECT_TRUE(String("foobar").EndsWith(""));
1047 EXPECT_TRUE(String("").EndsWith(""));
1049 EXPECT_FALSE(String("foobar").EndsWith("foo"));
1050 EXPECT_FALSE(String("").EndsWith("foo"));
1053 // Tests String::EndsWithCaseInsensitive().
1054 TEST(StringTest, EndsWithCaseInsensitive) {
1055 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
1056 EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
1057 EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
1058 EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
1060 EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
1061 EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
1062 EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
1065 // C++Builder's preprocessor is buggy; it fails to expand macros that
1066 // appear in macro parameters after wide char literals. Provide an alias
1067 // for NULL as a workaround.
1068 static const wchar_t* const kNull = NULL;
1070 // Tests String::CaseInsensitiveWideCStringEquals
1071 TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1072 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
1073 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1074 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1075 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1076 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
1077 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1078 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1079 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1082 // Tests that NULL can be assigned to a String.
1083 TEST(StringTest, CanBeAssignedNULL) {
1084 const String src(NULL);
1088 EXPECT_STREQ(NULL, dest.c_str());
1091 // Tests that the empty string "" can be assigned to a String.
1092 TEST(StringTest, CanBeAssignedEmpty) {
1093 const String src("");
1097 EXPECT_STREQ("", dest.c_str());
1100 // Tests that a non-empty string can be assigned to a String.
1101 TEST(StringTest, CanBeAssignedNonEmpty) {
1102 const String src("hello");
1105 EXPECT_EQ(5U, dest.length());
1106 EXPECT_STREQ("hello", dest.c_str());
1108 const String src2("x\0y", 3);
1111 EXPECT_EQ(3U, dest2.length());
1112 EXPECT_EQ('x', dest2.c_str()[0]);
1113 EXPECT_EQ('\0', dest2.c_str()[1]);
1114 EXPECT_EQ('y', dest2.c_str()[2]);
1117 // Tests that a String can be assigned to itself.
1118 TEST(StringTest, CanBeAssignedSelf) {
1119 String dest("hello");
1122 EXPECT_STREQ("hello", dest.c_str());
1125 // Sun Studio < 12 incorrectly rejects this code due to an overloading
1127 #if !(defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
1128 // Tests streaming a String.
1129 TEST(StringTest, Streams) {
1130 EXPECT_EQ(StreamableToString(String()), "(null)");
1131 EXPECT_EQ(StreamableToString(String("")), "");
1132 EXPECT_EQ(StreamableToString(String("a\0b", 3)), "a\\0b");
1136 // Tests that String::Format() works.
1137 TEST(StringTest, FormatWorks) {
1138 // Normal case: the format spec is valid, the arguments match the
1139 // spec, and the result is < 4095 characters.
1140 EXPECT_STREQ("Hello, 42", String::Format("%s, %d", "Hello", 42).c_str());
1142 // Edge case: the result is 4095 characters.
1144 const size_t kSize = sizeof(buffer);
1145 memset(buffer, 'a', kSize - 1);
1146 buffer[kSize - 1] = '\0';
1147 EXPECT_STREQ(buffer, String::Format("%s", buffer).c_str());
1149 // The result needs to be 4096 characters, exceeding Format()'s limit.
1150 EXPECT_STREQ("<formatting error or buffer exceeded>",
1151 String::Format("x%s", buffer).c_str());
1154 // On Linux, invalid format spec should lead to an error message.
1155 // In other environment (e.g. MSVC on Windows), String::Format() may
1156 // simply ignore a bad format spec, so this assertion is run on
1158 EXPECT_STREQ("<formatting error or buffer exceeded>",
1159 String::Format("%").c_str());
1163 #if GTEST_OS_WINDOWS
1165 // Tests String::ShowWideCString().
1166 TEST(StringTest, ShowWideCString) {
1167 EXPECT_STREQ("(null)",
1168 String::ShowWideCString(NULL).c_str());
1169 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1170 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1173 // Tests String::ShowWideCStringQuoted().
1174 TEST(StringTest, ShowWideCStringQuoted) {
1175 EXPECT_STREQ("(null)",
1176 String::ShowWideCStringQuoted(NULL).c_str());
1177 EXPECT_STREQ("L\"\"",
1178 String::ShowWideCStringQuoted(L"").c_str());
1179 EXPECT_STREQ("L\"foo\"",
1180 String::ShowWideCStringQuoted(L"foo").c_str());
1183 #if GTEST_OS_WINDOWS_MOBILE
1184 TEST(StringTest, AnsiAndUtf16Null) {
1185 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1186 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1189 TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1190 const char* ansi = String::Utf16ToAnsi(L"str");
1191 EXPECT_STREQ("str", ansi);
1193 const WCHAR* utf16 = String::AnsiToUtf16("str");
1194 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
1198 TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1199 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1200 EXPECT_STREQ(".:\\ \"*?", ansi);
1202 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
1203 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
1206 #endif // GTEST_OS_WINDOWS_MOBILE
1208 #endif // GTEST_OS_WINDOWS
1210 // Tests TestProperty construction.
1211 TEST(TestPropertyTest, StringValue) {
1212 TestProperty property("key", "1");
1213 EXPECT_STREQ("key", property.key());
1214 EXPECT_STREQ("1", property.value());
1217 // Tests TestProperty replacing a value.
1218 TEST(TestPropertyTest, ReplaceStringValue) {
1219 TestProperty property("key", "1");
1220 EXPECT_STREQ("1", property.value());
1221 property.SetValue("2");
1222 EXPECT_STREQ("2", property.value());
1225 // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1226 // functions (i.e. their definitions cannot be inlined at the call
1227 // sites), or C++Builder won't compile the code.
1228 static void AddFatalFailure() {
1229 FAIL() << "Expected fatal failure.";
1232 static void AddNonfatalFailure() {
1233 ADD_FAILURE() << "Expected non-fatal failure.";
1236 class ScopedFakeTestPartResultReporterTest : public Test {
1237 public: // Must be public and not protected due to a bug in g++ 3.4.2.
1242 static void AddFailure(FailureMode failure) {
1243 if (failure == FATAL_FAILURE) {
1246 AddNonfatalFailure();
1251 // Tests that ScopedFakeTestPartResultReporter intercepts test
1253 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
1254 TestPartResultArray results;
1256 ScopedFakeTestPartResultReporter reporter(
1257 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1259 AddFailure(NONFATAL_FAILURE);
1260 AddFailure(FATAL_FAILURE);
1263 EXPECT_EQ(2, results.size());
1264 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1265 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1268 TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1269 TestPartResultArray results;
1271 // Tests, that the deprecated constructor still works.
1272 ScopedFakeTestPartResultReporter reporter(&results);
1273 AddFailure(NONFATAL_FAILURE);
1275 EXPECT_EQ(1, results.size());
1278 #if GTEST_IS_THREADSAFE
1280 class ScopedFakeTestPartResultReporterWithThreadsTest
1281 : public ScopedFakeTestPartResultReporterTest {
1283 static void AddFailureInOtherThread(FailureMode failure) {
1284 ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
1289 TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1290 InterceptsTestFailuresInAllThreads) {
1291 TestPartResultArray results;
1293 ScopedFakeTestPartResultReporter reporter(
1294 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1295 AddFailure(NONFATAL_FAILURE);
1296 AddFailure(FATAL_FAILURE);
1297 AddFailureInOtherThread(NONFATAL_FAILURE);
1298 AddFailureInOtherThread(FATAL_FAILURE);
1301 EXPECT_EQ(4, results.size());
1302 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1303 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1304 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1305 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1308 #endif // GTEST_IS_THREADSAFE
1310 // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1311 // work even if the failure is generated in a called function rather than
1312 // the current context.
1314 typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
1316 TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1317 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
1320 TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1321 // We have another test below to verify that the macro catches fatal
1322 // failures generated on another thread.
1323 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
1324 "Expected fatal failure.");
1328 // Silences warnings: "Condition is always true"
1329 #pragma option push -w-ccc
1332 // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1333 // function even when the statement in it contains ASSERT_*.
1335 int NonVoidFunction() {
1336 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1337 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1341 TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1345 // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1346 // current function even though 'statement' generates a fatal failure.
1348 void DoesNotAbortHelper(bool* aborted) {
1349 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1350 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1356 // Restores warnings after previous "#pragma option push" suppressed them.
1360 TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1361 bool aborted = true;
1362 DoesNotAbortHelper(&aborted);
1363 EXPECT_FALSE(aborted);
1366 // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1367 // statement that contains a macro which expands to code containing an
1368 // unprotected comma.
1370 static int global_var = 0;
1371 #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1373 TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1374 #if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600
1375 // ICE's in C++Builder 2007.
1376 EXPECT_FATAL_FAILURE({
1377 GTEST_USE_UNPROTECTED_COMMA_;
1382 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1383 GTEST_USE_UNPROTECTED_COMMA_;
1388 // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1390 typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1392 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1393 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1394 "Expected non-fatal failure.");
1397 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1398 // We have another test below to verify that the macro catches
1399 // non-fatal failures generated on another thread.
1400 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
1401 "Expected non-fatal failure.");
1404 // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1405 // statement that contains a macro which expands to code containing an
1406 // unprotected comma.
1407 TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1408 EXPECT_NONFATAL_FAILURE({
1409 GTEST_USE_UNPROTECTED_COMMA_;
1410 AddNonfatalFailure();
1413 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1414 GTEST_USE_UNPROTECTED_COMMA_;
1415 AddNonfatalFailure();
1419 #if GTEST_IS_THREADSAFE
1421 typedef ScopedFakeTestPartResultReporterWithThreadsTest
1422 ExpectFailureWithThreadsTest;
1424 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1425 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1426 "Expected fatal failure.");
1429 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1430 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1431 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1434 #endif // GTEST_IS_THREADSAFE
1436 // Tests the TestProperty class.
1438 TEST(TestPropertyTest, ConstructorWorks) {
1439 const TestProperty property("key", "value");
1440 EXPECT_STREQ("key", property.key());
1441 EXPECT_STREQ("value", property.value());
1444 TEST(TestPropertyTest, SetValue) {
1445 TestProperty property("key", "value_1");
1446 EXPECT_STREQ("key", property.key());
1447 property.SetValue("value_2");
1448 EXPECT_STREQ("key", property.key());
1449 EXPECT_STREQ("value_2", property.value());
1452 // Tests the TestResult class
1454 // The test fixture for testing TestResult.
1455 class TestResultTest : public Test {
1457 typedef std::vector<TestPartResult> TPRVector;
1459 // We make use of 2 TestPartResult objects,
1460 TestPartResult * pr1, * pr2;
1462 // ... and 3 TestResult objects.
1463 TestResult * r0, * r1, * r2;
1465 virtual void SetUp() {
1466 // pr1 is for success.
1467 pr1 = new TestPartResult(TestPartResult::kSuccess,
1472 // pr2 is for fatal failure.
1473 pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1475 -1, // This line number means "unknown"
1478 // Creates the TestResult objects.
1479 r0 = new TestResult();
1480 r1 = new TestResult();
1481 r2 = new TestResult();
1483 // In order to test TestResult, we need to modify its internal
1484 // state, in particular the TestPartResult vector it holds.
1485 // test_part_results() returns a const reference to this vector.
1486 // We cast it to a non-const object s.t. it can be modified (yes,
1488 TPRVector* results1 = const_cast<TPRVector*>(
1489 &TestResultAccessor::test_part_results(*r1));
1490 TPRVector* results2 = const_cast<TPRVector*>(
1491 &TestResultAccessor::test_part_results(*r2));
1493 // r0 is an empty TestResult.
1495 // r1 contains a single SUCCESS TestPartResult.
1496 results1->push_back(*pr1);
1498 // r2 contains a SUCCESS, and a FAILURE.
1499 results2->push_back(*pr1);
1500 results2->push_back(*pr2);
1503 virtual void TearDown() {
1512 // Helper that compares two two TestPartResults.
1513 static void CompareTestPartResult(const TestPartResult& expected,
1514 const TestPartResult& actual) {
1515 EXPECT_EQ(expected.type(), actual.type());
1516 EXPECT_STREQ(expected.file_name(), actual.file_name());
1517 EXPECT_EQ(expected.line_number(), actual.line_number());
1518 EXPECT_STREQ(expected.summary(), actual.summary());
1519 EXPECT_STREQ(expected.message(), actual.message());
1520 EXPECT_EQ(expected.passed(), actual.passed());
1521 EXPECT_EQ(expected.failed(), actual.failed());
1522 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1523 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
1527 // Tests TestResult::total_part_count().
1528 TEST_F(TestResultTest, total_part_count) {
1529 ASSERT_EQ(0, r0->total_part_count());
1530 ASSERT_EQ(1, r1->total_part_count());
1531 ASSERT_EQ(2, r2->total_part_count());
1534 // Tests TestResult::Passed().
1535 TEST_F(TestResultTest, Passed) {
1536 ASSERT_TRUE(r0->Passed());
1537 ASSERT_TRUE(r1->Passed());
1538 ASSERT_FALSE(r2->Passed());
1541 // Tests TestResult::Failed().
1542 TEST_F(TestResultTest, Failed) {
1543 ASSERT_FALSE(r0->Failed());
1544 ASSERT_FALSE(r1->Failed());
1545 ASSERT_TRUE(r2->Failed());
1548 // Tests TestResult::GetTestPartResult().
1550 typedef TestResultTest TestResultDeathTest;
1552 TEST_F(TestResultDeathTest, GetTestPartResult) {
1553 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1554 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1555 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1556 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
1559 // Tests TestResult has no properties when none are added.
1560 TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1561 TestResult test_result;
1562 ASSERT_EQ(0, test_result.test_property_count());
1565 // Tests TestResult has the expected property when added.
1566 TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1567 TestResult test_result;
1568 TestProperty property("key_1", "1");
1569 TestResultAccessor::RecordProperty(&test_result, property);
1570 ASSERT_EQ(1, test_result.test_property_count());
1571 const TestProperty& actual_property = test_result.GetTestProperty(0);
1572 EXPECT_STREQ("key_1", actual_property.key());
1573 EXPECT_STREQ("1", actual_property.value());
1576 // Tests TestResult has multiple properties when added.
1577 TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1578 TestResult test_result;
1579 TestProperty property_1("key_1", "1");
1580 TestProperty property_2("key_2", "2");
1581 TestResultAccessor::RecordProperty(&test_result, property_1);
1582 TestResultAccessor::RecordProperty(&test_result, property_2);
1583 ASSERT_EQ(2, test_result.test_property_count());
1584 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1585 EXPECT_STREQ("key_1", actual_property_1.key());
1586 EXPECT_STREQ("1", actual_property_1.value());
1588 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1589 EXPECT_STREQ("key_2", actual_property_2.key());
1590 EXPECT_STREQ("2", actual_property_2.value());
1593 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
1594 TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1595 TestResult test_result;
1596 TestProperty property_1_1("key_1", "1");
1597 TestProperty property_2_1("key_2", "2");
1598 TestProperty property_1_2("key_1", "12");
1599 TestProperty property_2_2("key_2", "22");
1600 TestResultAccessor::RecordProperty(&test_result, property_1_1);
1601 TestResultAccessor::RecordProperty(&test_result, property_2_1);
1602 TestResultAccessor::RecordProperty(&test_result, property_1_2);
1603 TestResultAccessor::RecordProperty(&test_result, property_2_2);
1605 ASSERT_EQ(2, test_result.test_property_count());
1606 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1607 EXPECT_STREQ("key_1", actual_property_1.key());
1608 EXPECT_STREQ("12", actual_property_1.value());
1610 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1611 EXPECT_STREQ("key_2", actual_property_2.key());
1612 EXPECT_STREQ("22", actual_property_2.value());
1615 // Tests TestResult::GetTestProperty().
1616 TEST(TestResultPropertyDeathTest, GetTestProperty) {
1617 TestResult test_result;
1618 TestProperty property_1("key_1", "1");
1619 TestProperty property_2("key_2", "2");
1620 TestProperty property_3("key_3", "3");
1621 TestResultAccessor::RecordProperty(&test_result, property_1);
1622 TestResultAccessor::RecordProperty(&test_result, property_2);
1623 TestResultAccessor::RecordProperty(&test_result, property_3);
1625 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1626 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1627 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
1629 EXPECT_STREQ("key_1", fetched_property_1.key());
1630 EXPECT_STREQ("1", fetched_property_1.value());
1632 EXPECT_STREQ("key_2", fetched_property_2.key());
1633 EXPECT_STREQ("2", fetched_property_2.value());
1635 EXPECT_STREQ("key_3", fetched_property_3.key());
1636 EXPECT_STREQ("3", fetched_property_3.value());
1638 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1639 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
1642 // When a property using a reserved key is supplied to this function, it tests
1643 // that a non-fatal failure is added, a fatal failure is not added, and that the
1644 // property is not recorded.
1645 void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) {
1646 TestResult test_result;
1647 TestProperty property(key, "1");
1648 EXPECT_NONFATAL_FAILURE(
1649 TestResultAccessor::RecordProperty(&test_result, property),
1651 ASSERT_EQ(0, test_result.test_property_count()) << "Not recorded";
1654 // Attempting to recording a property with the Reserved literal "name"
1655 // should add a non-fatal failure and the property should not be recorded.
1656 TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) {
1657 ExpectNonFatalFailureRecordingPropertyWithReservedKey("name");
1660 // Attempting to recording a property with the Reserved literal "status"
1661 // should add a non-fatal failure and the property should not be recorded.
1662 TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) {
1663 ExpectNonFatalFailureRecordingPropertyWithReservedKey("status");
1666 // Attempting to recording a property with the Reserved literal "time"
1667 // should add a non-fatal failure and the property should not be recorded.
1668 TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) {
1669 ExpectNonFatalFailureRecordingPropertyWithReservedKey("time");
1672 // Attempting to recording a property with the Reserved literal "classname"
1673 // should add a non-fatal failure and the property should not be recorded.
1674 TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) {
1675 ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname");
1678 // Tests that GTestFlagSaver works on Windows and Mac.
1680 class GTestFlagSaverTest : public Test {
1682 // Saves the Google Test flags such that we can restore them later, and
1683 // then sets them to their default values. This will be called
1684 // before the first test in this test case is run.
1685 static void SetUpTestCase() {
1686 saver_ = new GTestFlagSaver;
1688 GTEST_FLAG(also_run_disabled_tests) = false;
1689 GTEST_FLAG(break_on_failure) = false;
1690 GTEST_FLAG(catch_exceptions) = false;
1691 GTEST_FLAG(death_test_use_fork) = false;
1692 GTEST_FLAG(color) = "auto";
1693 GTEST_FLAG(filter) = "";
1694 GTEST_FLAG(list_tests) = false;
1695 GTEST_FLAG(output) = "";
1696 GTEST_FLAG(print_time) = true;
1697 GTEST_FLAG(random_seed) = 0;
1698 GTEST_FLAG(repeat) = 1;
1699 GTEST_FLAG(shuffle) = false;
1700 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
1701 GTEST_FLAG(throw_on_failure) = false;
1704 // Restores the Google Test flags that the tests have modified. This will
1705 // be called after the last test in this test case is run.
1706 static void TearDownTestCase() {
1711 // Verifies that the Google Test flags have their default values, and then
1712 // modifies each of them.
1713 void VerifyAndModifyFlags() {
1714 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
1715 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1716 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1717 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
1718 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
1719 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1720 EXPECT_FALSE(GTEST_FLAG(list_tests));
1721 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
1722 EXPECT_TRUE(GTEST_FLAG(print_time));
1723 EXPECT_EQ(0, GTEST_FLAG(random_seed));
1724 EXPECT_EQ(1, GTEST_FLAG(repeat));
1725 EXPECT_FALSE(GTEST_FLAG(shuffle));
1726 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
1727 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
1729 GTEST_FLAG(also_run_disabled_tests) = true;
1730 GTEST_FLAG(break_on_failure) = true;
1731 GTEST_FLAG(catch_exceptions) = true;
1732 GTEST_FLAG(color) = "no";
1733 GTEST_FLAG(death_test_use_fork) = true;
1734 GTEST_FLAG(filter) = "abc";
1735 GTEST_FLAG(list_tests) = true;
1736 GTEST_FLAG(output) = "xml:foo.xml";
1737 GTEST_FLAG(print_time) = false;
1738 GTEST_FLAG(random_seed) = 1;
1739 GTEST_FLAG(repeat) = 100;
1740 GTEST_FLAG(shuffle) = true;
1741 GTEST_FLAG(stack_trace_depth) = 1;
1742 GTEST_FLAG(throw_on_failure) = true;
1745 // For saving Google Test flags during this test case.
1746 static GTestFlagSaver* saver_;
1749 GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
1751 // Google Test doesn't guarantee the order of tests. The following two
1752 // tests are designed to work regardless of their order.
1754 // Modifies the Google Test flags in the test body.
1755 TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1756 VerifyAndModifyFlags();
1759 // Verifies that the Google Test flags in the body of the previous test were
1760 // restored to their original values.
1761 TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1762 VerifyAndModifyFlags();
1765 // Sets an environment variable with the given name to the given
1766 // value. If the value argument is "", unsets the environment
1767 // variable. The caller must ensure that both arguments are not NULL.
1768 static void SetEnv(const char* name, const char* value) {
1769 #if GTEST_OS_WINDOWS_MOBILE
1770 // Environment variables are not supported on Windows CE.
1772 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1773 // C++Builder's putenv only stores a pointer to its parameter; we have to
1774 // ensure that the string remains valid as long as it might be needed.
1775 // We use an std::map to do so.
1776 static std::map<String, String*> added_env;
1778 // Because putenv stores a pointer to the string buffer, we can't delete the
1779 // previous string (if present) until after it's replaced.
1780 String *prev_env = NULL;
1781 if (added_env.find(name) != added_env.end()) {
1782 prev_env = added_env[name];
1784 added_env[name] = new String((Message() << name << "=" << value).GetString());
1786 // The standard signature of putenv accepts a 'char*' argument. Other
1787 // implementations, like C++Builder's, accept a 'const char*'.
1788 // We cast away the 'const' since that would work for both variants.
1789 putenv(const_cast<char*>(added_env[name]->c_str()));
1791 #elif GTEST_OS_WINDOWS // If we are on Windows proper.
1792 _putenv((Message() << name << "=" << value).GetString().c_str());
1794 if (*value == '\0') {
1797 setenv(name, value, 1);
1799 #endif // GTEST_OS_WINDOWS_MOBILE
1802 #if !GTEST_OS_WINDOWS_MOBILE
1803 // Environment variables are not supported on Windows CE.
1805 using testing::internal::Int32FromGTestEnv;
1807 // Tests Int32FromGTestEnv().
1809 // Tests that Int32FromGTestEnv() returns the default value when the
1810 // environment variable is not set.
1811 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1812 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1813 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1816 // Tests that Int32FromGTestEnv() returns the default value when the
1817 // environment variable overflows as an Int32.
1818 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1819 printf("(expecting 2 warnings)\n");
1821 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1822 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1824 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1825 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1828 // Tests that Int32FromGTestEnv() returns the default value when the
1829 // environment variable does not represent a valid decimal integer.
1830 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1831 printf("(expecting 2 warnings)\n");
1833 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1834 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1836 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1837 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1840 // Tests that Int32FromGTestEnv() parses and returns the value of the
1841 // environment variable when it represents a valid decimal integer in
1842 // the range of an Int32.
1843 TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1844 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1845 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1847 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1848 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1850 #endif // !GTEST_OS_WINDOWS_MOBILE
1852 // Tests ParseInt32Flag().
1854 // Tests that ParseInt32Flag() returns false and doesn't change the
1855 // output value when the flag has wrong format
1856 TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1858 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1859 EXPECT_EQ(123, value);
1861 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1862 EXPECT_EQ(123, value);
1865 // Tests that ParseInt32Flag() returns false and doesn't change the
1866 // output value when the flag overflows as an Int32.
1867 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1868 printf("(expecting 2 warnings)\n");
1871 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1872 EXPECT_EQ(123, value);
1874 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1875 EXPECT_EQ(123, value);
1878 // Tests that ParseInt32Flag() returns false and doesn't change the
1879 // output value when the flag does not represent a valid decimal
1881 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1882 printf("(expecting 2 warnings)\n");
1885 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1886 EXPECT_EQ(123, value);
1888 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1889 EXPECT_EQ(123, value);
1892 // Tests that ParseInt32Flag() parses the value of the flag and
1893 // returns true when the flag represents a valid decimal integer in
1894 // the range of an Int32.
1895 TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1897 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1898 EXPECT_EQ(456, value);
1900 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1902 EXPECT_EQ(-789, value);
1905 // Tests that Int32FromEnvOrDie() parses the value of the var or
1906 // returns the correct default.
1907 // Environment variables are not supported on Windows CE.
1908 #if !GTEST_OS_WINDOWS_MOBILE
1909 TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1910 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1911 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1912 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1913 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1914 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1916 #endif // !GTEST_OS_WINDOWS_MOBILE
1918 // Tests that Int32FromEnvOrDie() aborts with an error message
1919 // if the variable is not an Int32.
1920 TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1921 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1922 EXPECT_DEATH_IF_SUPPORTED(
1923 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1927 // Tests that Int32FromEnvOrDie() aborts with an error message
1928 // if the variable cannot be represnted by an Int32.
1929 TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1930 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1931 EXPECT_DEATH_IF_SUPPORTED(
1932 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1936 // Tests that ShouldRunTestOnShard() selects all tests
1937 // where there is 1 shard.
1938 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1939 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1940 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1941 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1942 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1943 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1946 class ShouldShardTest : public testing::Test {
1948 virtual void SetUp() {
1949 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1950 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1953 virtual void TearDown() {
1954 SetEnv(index_var_, "");
1955 SetEnv(total_var_, "");
1958 const char* index_var_;
1959 const char* total_var_;
1962 // Tests that sharding is disabled if neither of the environment variables
1964 TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1965 SetEnv(index_var_, "");
1966 SetEnv(total_var_, "");
1968 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1969 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1972 // Tests that sharding is not enabled if total_shards == 1.
1973 TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1974 SetEnv(index_var_, "0");
1975 SetEnv(total_var_, "1");
1976 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1977 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1980 // Tests that sharding is enabled if total_shards > 1 and
1981 // we are not in a death test subprocess.
1982 // Environment variables are not supported on Windows CE.
1983 #if !GTEST_OS_WINDOWS_MOBILE
1984 TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1985 SetEnv(index_var_, "4");
1986 SetEnv(total_var_, "22");
1987 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1988 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1990 SetEnv(index_var_, "8");
1991 SetEnv(total_var_, "9");
1992 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1993 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1995 SetEnv(index_var_, "0");
1996 SetEnv(total_var_, "9");
1997 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1998 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
2000 #endif // !GTEST_OS_WINDOWS_MOBILE
2002 // Tests that we exit in error if the sharding values are not valid.
2004 typedef ShouldShardTest ShouldShardDeathTest;
2006 TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
2007 SetEnv(index_var_, "4");
2008 SetEnv(total_var_, "4");
2009 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
2011 SetEnv(index_var_, "4");
2012 SetEnv(total_var_, "-2");
2013 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
2015 SetEnv(index_var_, "5");
2016 SetEnv(total_var_, "");
2017 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
2019 SetEnv(index_var_, "");
2020 SetEnv(total_var_, "5");
2021 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
2024 // Tests that ShouldRunTestOnShard is a partition when 5
2026 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
2027 // Choose an arbitrary number of tests and shards.
2028 const int num_tests = 17;
2029 const int num_shards = 5;
2031 // Check partitioning: each test should be on exactly 1 shard.
2032 for (int test_id = 0; test_id < num_tests; test_id++) {
2033 int prev_selected_shard_index = -1;
2034 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
2035 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
2036 if (prev_selected_shard_index < 0) {
2037 prev_selected_shard_index = shard_index;
2039 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
2040 << shard_index << " are both selected to run test " << test_id;
2046 // Check balance: This is not required by the sharding protocol, but is a
2047 // desirable property for performance.
2048 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
2049 int num_tests_on_shard = 0;
2050 for (int test_id = 0; test_id < num_tests; test_id++) {
2051 num_tests_on_shard +=
2052 ShouldRunTestOnShard(num_shards, shard_index, test_id);
2054 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
2058 // For the same reason we are not explicitly testing everything in the
2059 // Test class, there are no separate tests for the following classes
2060 // (except for some trivial cases):
2062 // TestCase, UnitTest, UnitTestResultPrinter.
2064 // Similarly, there are no separate tests for the following macros:
2066 // TEST, TEST_F, RUN_ALL_TESTS
2068 TEST(UnitTestTest, CanGetOriginalWorkingDir) {
2069 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
2070 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
2073 // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2074 // of various arities. They do not attempt to be exhaustive. Rather,
2075 // view them as smoke tests that can be easily reviewed and verified.
2076 // A more complete set of tests for predicate assertions can be found
2077 // in gtest_pred_impl_unittest.cc.
2079 // First, some predicates and predicate-formatters needed by the tests.
2081 // Returns true iff the argument is an even number.
2082 bool IsEven(int n) {
2083 return (n % 2) == 0;
2086 // A functor that returns true iff the argument is an even number.
2087 struct IsEvenFunctor {
2088 bool operator()(int n) { return IsEven(n); }
2091 // A predicate-formatter function that asserts the argument is an even
2093 AssertionResult AssertIsEven(const char* expr, int n) {
2095 return AssertionSuccess();
2099 msg << expr << " evaluates to " << n << ", which is not even.";
2100 return AssertionFailure(msg);
2103 // A predicate function that returns AssertionResult for use in
2104 // EXPECT/ASSERT_TRUE/FALSE.
2105 AssertionResult ResultIsEven(int n) {
2107 return AssertionSuccess() << n << " is even";
2109 return AssertionFailure() << n << " is odd";
2112 // A predicate function that returns AssertionResult but gives no
2113 // explanation why it succeeds. Needed for testing that
2114 // EXPECT/ASSERT_FALSE handles such functions correctly.
2115 AssertionResult ResultIsEvenNoExplanation(int n) {
2117 return AssertionSuccess();
2119 return AssertionFailure() << n << " is odd";
2122 // A predicate-formatter functor that asserts the argument is an even
2124 struct AssertIsEvenFunctor {
2125 AssertionResult operator()(const char* expr, int n) {
2126 return AssertIsEven(expr, n);
2130 // Returns true iff the sum of the arguments is an even number.
2131 bool SumIsEven2(int n1, int n2) {
2132 return IsEven(n1 + n2);
2135 // A functor that returns true iff the sum of the arguments is an even
2137 struct SumIsEven3Functor {
2138 bool operator()(int n1, int n2, int n3) {
2139 return IsEven(n1 + n2 + n3);
2143 // A predicate-formatter function that asserts the sum of the
2144 // arguments is an even number.
2145 AssertionResult AssertSumIsEven4(
2146 const char* e1, const char* e2, const char* e3, const char* e4,
2147 int n1, int n2, int n3, int n4) {
2148 const int sum = n1 + n2 + n3 + n4;
2150 return AssertionSuccess();
2154 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2155 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2156 << ") evaluates to " << sum << ", which is not even.";
2157 return AssertionFailure(msg);
2160 // A predicate-formatter functor that asserts the sum of the arguments
2161 // is an even number.
2162 struct AssertSumIsEven5Functor {
2163 AssertionResult operator()(
2164 const char* e1, const char* e2, const char* e3, const char* e4,
2165 const char* e5, int n1, int n2, int n3, int n4, int n5) {
2166 const int sum = n1 + n2 + n3 + n4 + n5;
2168 return AssertionSuccess();
2172 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2174 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2175 << ") evaluates to " << sum << ", which is not even.";
2176 return AssertionFailure(msg);
2181 // Tests unary predicate assertions.
2183 // Tests unary predicate assertions that don't use a custom formatter.
2184 TEST(Pred1Test, WithoutFormat) {
2186 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2187 ASSERT_PRED1(IsEven, 4);
2190 EXPECT_NONFATAL_FAILURE({ // NOLINT
2191 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2192 }, "This failure is expected.");
2193 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2194 "evaluates to false");
2197 // Tests unary predicate assertions that use a custom formatter.
2198 TEST(Pred1Test, WithFormat) {
2200 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2201 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2202 << "This failure is UNEXPECTED!";
2206 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2207 "n evaluates to 5, which is not even.");
2208 EXPECT_FATAL_FAILURE({ // NOLINT
2209 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2210 }, "This failure is expected.");
2213 // Tests that unary predicate assertions evaluates their arguments
2215 TEST(Pred1Test, SingleEvaluationOnFailure) {
2218 EXPECT_PRED1(IsEven, n++);
2219 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2222 EXPECT_FATAL_FAILURE({ // NOLINT
2223 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2224 << "This failure is expected.";
2225 }, "This failure is expected.");
2226 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2230 // Tests predicate assertions whose arity is >= 2.
2232 // Tests predicate assertions that don't use a custom formatter.
2233 TEST(PredTest, WithoutFormat) {
2235 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2236 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2241 EXPECT_NONFATAL_FAILURE({ // NOLINT
2242 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2243 }, "This failure is expected.");
2244 EXPECT_FATAL_FAILURE({ // NOLINT
2245 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2246 }, "evaluates to false");
2249 // Tests predicate assertions that use a custom formatter.
2250 TEST(PredTest, WithFormat) {
2252 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2253 "This failure is UNEXPECTED!";
2254 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2261 EXPECT_NONFATAL_FAILURE({ // NOLINT
2262 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2263 }, "evaluates to 13, which is not even.");
2264 EXPECT_FATAL_FAILURE({ // NOLINT
2265 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2266 << "This failure is expected.";
2267 }, "This failure is expected.");
2270 // Tests that predicate assertions evaluates their arguments
2272 TEST(PredTest, SingleEvaluationOnFailure) {
2276 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2277 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2278 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2280 // Another success case.
2285 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2286 n1++, n2++, n3++, n4++, n5++)
2287 << "This failure is UNEXPECTED!";
2288 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2289 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2290 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2291 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2292 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2296 EXPECT_NONFATAL_FAILURE({ // NOLINT
2297 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2298 << "This failure is expected.";
2299 }, "This failure is expected.");
2300 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2301 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2302 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2304 // Another failure case.
2305 n1 = n2 = n3 = n4 = 0;
2306 EXPECT_NONFATAL_FAILURE({ // NOLINT
2307 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2308 }, "evaluates to 1, which is not even.");
2309 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2310 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2311 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2312 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2316 // Some helper functions for testing using overloaded/template
2317 // functions with ASSERT_PREDn and EXPECT_PREDn.
2319 bool IsPositive(double x) {
2323 template <typename T>
2324 bool IsNegative(T x) {
2328 template <typename T1, typename T2>
2329 bool GreaterThan(T1 x1, T2 x2) {
2333 // Tests that overloaded functions can be used in *_PRED* as long as
2334 // their types are explicitly specified.
2335 TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2336 // C++Builder requires C-style casts rather than static_cast.
2337 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2338 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
2341 // Tests that template functions can be used in *_PRED* as long as
2342 // their types are explicitly specified.
2343 TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2344 EXPECT_PRED1(IsNegative<int>, -5);
2345 // Makes sure that we can handle templates with more than one
2347 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2351 // Some helper functions for testing using overloaded/template
2352 // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2354 AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2355 return n > 0 ? AssertionSuccess() :
2356 AssertionFailure(Message() << "Failure");
2359 AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2360 return x > 0 ? AssertionSuccess() :
2361 AssertionFailure(Message() << "Failure");
2364 template <typename T>
2365 AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2366 return x < 0 ? AssertionSuccess() :
2367 AssertionFailure(Message() << "Failure");
2370 template <typename T1, typename T2>
2371 AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2372 const T1& x1, const T2& x2) {
2373 return x1 == x2 ? AssertionSuccess() :
2374 AssertionFailure(Message() << "Failure");
2377 // Tests that overloaded functions can be used in *_PRED_FORMAT*
2378 // without explicitly specifying their types.
2379 TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2380 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2381 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2384 // Tests that template functions can be used in *_PRED_FORMAT* without
2385 // explicitly specifying their types.
2386 TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2387 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2388 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2392 // Tests string assertions.
2394 // Tests ASSERT_STREQ with non-NULL arguments.
2395 TEST(StringAssertionTest, ASSERT_STREQ) {
2396 const char * const p1 = "good";
2397 ASSERT_STREQ(p1, p1);
2399 // Let p2 have the same content as p1, but be at a different address.
2400 const char p2[] = "good";
2401 ASSERT_STREQ(p1, p2);
2403 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2404 "Expected: \"bad\"");
2407 // Tests ASSERT_STREQ with NULL arguments.
2408 TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2409 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2410 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2414 // Tests ASSERT_STREQ with NULL arguments.
2415 TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2416 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2420 // Tests ASSERT_STRNE.
2421 TEST(StringAssertionTest, ASSERT_STRNE) {
2422 ASSERT_STRNE("hi", "Hi");
2423 ASSERT_STRNE("Hi", NULL);
2424 ASSERT_STRNE(NULL, "Hi");
2425 ASSERT_STRNE("", NULL);
2426 ASSERT_STRNE(NULL, "");
2427 ASSERT_STRNE("", "Hi");
2428 ASSERT_STRNE("Hi", "");
2429 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2430 "\"Hi\" vs \"Hi\"");
2433 // Tests ASSERT_STRCASEEQ.
2434 TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2435 ASSERT_STRCASEEQ("hi", "Hi");
2436 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2438 ASSERT_STRCASEEQ("", "");
2439 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2443 // Tests ASSERT_STRCASENE.
2444 TEST(StringAssertionTest, ASSERT_STRCASENE) {
2445 ASSERT_STRCASENE("hi1", "Hi2");
2446 ASSERT_STRCASENE("Hi", NULL);
2447 ASSERT_STRCASENE(NULL, "Hi");
2448 ASSERT_STRCASENE("", NULL);
2449 ASSERT_STRCASENE(NULL, "");
2450 ASSERT_STRCASENE("", "Hi");
2451 ASSERT_STRCASENE("Hi", "");
2452 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2456 // Tests *_STREQ on wide strings.
2457 TEST(StringAssertionTest, STREQ_Wide) {
2459 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2462 ASSERT_STREQ(L"", L"");
2464 // Non-null vs NULL.
2465 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2469 EXPECT_STREQ(L"Hi", L"Hi");
2472 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2475 // Strings containing wide characters.
2476 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2480 // Tests *_STRNE on wide strings.
2481 TEST(StringAssertionTest, STRNE_Wide) {
2483 EXPECT_NONFATAL_FAILURE({ // NOLINT
2484 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2488 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2491 // Non-null vs NULL.
2492 ASSERT_STRNE(L"non-null", NULL);
2495 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2499 EXPECT_STRNE(L"abc", L"Abc");
2501 // Strings containing wide characters.
2502 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2506 // Tests for ::testing::IsSubstring().
2508 // Tests that IsSubstring() returns the correct result when the input
2509 // argument type is const char*.
2510 TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2511 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2512 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2513 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2515 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2516 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2519 // Tests that IsSubstring() returns the correct result when the input
2520 // argument type is const wchar_t*.
2521 TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2522 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2523 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
2524 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2526 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2527 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2530 // Tests that IsSubstring() generates the correct message when the input
2531 // argument type is const char*.
2532 TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2533 EXPECT_STREQ("Value of: needle_expr\n"
2534 " Actual: \"needle\"\n"
2535 "Expected: a substring of haystack_expr\n"
2536 "Which is: \"haystack\"",
2537 IsSubstring("needle_expr", "haystack_expr",
2538 "needle", "haystack").failure_message());
2541 // Tests that IsSubstring returns the correct result when the input
2542 // argument type is ::std::string.
2543 TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2544 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2545 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2548 #if GTEST_HAS_STD_WSTRING
2549 // Tests that IsSubstring returns the correct result when the input
2550 // argument type is ::std::wstring.
2551 TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2552 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2553 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2556 // Tests that IsSubstring() generates the correct message when the input
2557 // argument type is ::std::wstring.
2558 TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2559 EXPECT_STREQ("Value of: needle_expr\n"
2560 " Actual: L\"needle\"\n"
2561 "Expected: a substring of haystack_expr\n"
2562 "Which is: L\"haystack\"",
2564 "needle_expr", "haystack_expr",
2565 ::std::wstring(L"needle"), L"haystack").failure_message());
2568 #endif // GTEST_HAS_STD_WSTRING
2570 // Tests for ::testing::IsNotSubstring().
2572 // Tests that IsNotSubstring() returns the correct result when the input
2573 // argument type is const char*.
2574 TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2575 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2576 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2579 // Tests that IsNotSubstring() returns the correct result when the input
2580 // argument type is const wchar_t*.
2581 TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2582 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2583 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2586 // Tests that IsNotSubstring() generates the correct message when the input
2587 // argument type is const wchar_t*.
2588 TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2589 EXPECT_STREQ("Value of: needle_expr\n"
2590 " Actual: L\"needle\"\n"
2591 "Expected: not a substring of haystack_expr\n"
2592 "Which is: L\"two needles\"",
2594 "needle_expr", "haystack_expr",
2595 L"needle", L"two needles").failure_message());
2598 // Tests that IsNotSubstring returns the correct result when the input
2599 // argument type is ::std::string.
2600 TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2601 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2602 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2605 // Tests that IsNotSubstring() generates the correct message when the input
2606 // argument type is ::std::string.
2607 TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2608 EXPECT_STREQ("Value of: needle_expr\n"
2609 " Actual: \"needle\"\n"
2610 "Expected: not a substring of haystack_expr\n"
2611 "Which is: \"two needles\"",
2613 "needle_expr", "haystack_expr",
2614 ::std::string("needle"), "two needles").failure_message());
2617 #if GTEST_HAS_STD_WSTRING
2619 // Tests that IsNotSubstring returns the correct result when the input
2620 // argument type is ::std::wstring.
2621 TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2623 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2624 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2627 #endif // GTEST_HAS_STD_WSTRING
2629 // Tests floating-point assertions.
2631 template <typename RawType>
2632 class FloatingPointTest : public Test {
2635 // Pre-calculated numbers to be used by the tests.
2637 RawType close_to_positive_zero;
2638 RawType close_to_negative_zero;
2639 RawType further_from_negative_zero;
2641 RawType close_to_one;
2642 RawType further_from_one;
2645 RawType close_to_infinity;
2646 RawType further_from_infinity;
2652 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2653 typedef typename Floating::Bits Bits;
2655 virtual void SetUp() {
2656 const size_t max_ulps = Floating::kMaxUlps;
2658 // The bits that represent 0.0.
2659 const Bits zero_bits = Floating(0).bits();
2661 // Makes some numbers close to 0.0.
2662 values_.close_to_positive_zero = Floating::ReinterpretBits(
2663 zero_bits + max_ulps/2);
2664 values_.close_to_negative_zero = -Floating::ReinterpretBits(
2665 zero_bits + max_ulps - max_ulps/2);
2666 values_.further_from_negative_zero = -Floating::ReinterpretBits(
2667 zero_bits + max_ulps + 1 - max_ulps/2);
2669 // The bits that represent 1.0.
2670 const Bits one_bits = Floating(1).bits();
2672 // Makes some numbers close to 1.0.
2673 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2674 values_.further_from_one = Floating::ReinterpretBits(
2675 one_bits + max_ulps + 1);
2678 values_.infinity = Floating::Infinity();
2680 // The bits that represent +infinity.
2681 const Bits infinity_bits = Floating(values_.infinity).bits();
2683 // Makes some numbers close to infinity.
2684 values_.close_to_infinity = Floating::ReinterpretBits(
2685 infinity_bits - max_ulps);
2686 values_.further_from_infinity = Floating::ReinterpretBits(
2687 infinity_bits - max_ulps - 1);
2689 // Makes some NAN's. Sets the most significant bit of the fraction so that
2690 // our NaN's are quiet; trying to process a signaling NaN would raise an
2691 // exception if our environment enables floating point exceptions.
2692 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2693 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2694 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2695 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
2699 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2702 static TestValues values_;
2705 template <typename RawType>
2706 typename FloatingPointTest<RawType>::TestValues
2707 FloatingPointTest<RawType>::values_;
2709 // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2710 typedef FloatingPointTest<float> FloatTest;
2712 // Tests that the size of Float::Bits matches the size of float.
2713 TEST_F(FloatTest, Size) {
2717 // Tests comparing with +0 and -0.
2718 TEST_F(FloatTest, Zeros) {
2719 EXPECT_FLOAT_EQ(0.0, -0.0);
2720 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2722 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2726 // Tests comparing numbers close to 0.
2728 // This ensures that *_FLOAT_EQ handles the sign correctly and no
2729 // overflow occurs when comparing numbers whose absolute value is very
2731 TEST_F(FloatTest, AlmostZeros) {
2732 // In C++Builder, names within local classes (such as used by
2733 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2734 // scoping class. Use a static local alias as a workaround.
2735 // We use the assignment syntax since some compilers, like Sun Studio,
2736 // don't allow initializing references using construction syntax
2738 static const FloatTest::TestValues& v = this->values_;
2740 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2741 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2742 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2744 EXPECT_FATAL_FAILURE({ // NOLINT
2745 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2746 v.further_from_negative_zero);
2747 }, "v.further_from_negative_zero");
2750 // Tests comparing numbers close to each other.
2751 TEST_F(FloatTest, SmallDiff) {
2752 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2753 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2754 "values_.further_from_one");
2757 // Tests comparing numbers far apart.
2758 TEST_F(FloatTest, LargeDiff) {
2759 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2763 // Tests comparing with infinity.
2765 // This ensures that no overflow occurs when comparing numbers whose
2766 // absolute value is very large.
2767 TEST_F(FloatTest, Infinity) {
2768 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2769 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
2770 #if !GTEST_OS_SYMBIAN
2771 // Nokia's STLport crashes if we try to output infinity or NaN.
2772 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2773 "-values_.infinity");
2775 // This is interesting as the representations of infinity and nan1
2776 // are only 1 DLP apart.
2777 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2779 #endif // !GTEST_OS_SYMBIAN
2782 // Tests that comparing with NAN always returns false.
2783 TEST_F(FloatTest, NaN) {
2784 #if !GTEST_OS_SYMBIAN
2785 // Nokia's STLport crashes if we try to output infinity or NaN.
2787 // In C++Builder, names within local classes (such as used by
2788 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2789 // scoping class. Use a static local alias as a workaround.
2790 // We use the assignment syntax since some compilers, like Sun Studio,
2791 // don't allow initializing references using construction syntax
2793 static const FloatTest::TestValues& v = this->values_;
2795 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2797 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2799 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2802 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2804 #endif // !GTEST_OS_SYMBIAN
2807 // Tests that *_FLOAT_EQ are reflexive.
2808 TEST_F(FloatTest, Reflexive) {
2809 EXPECT_FLOAT_EQ(0.0, 0.0);
2810 EXPECT_FLOAT_EQ(1.0, 1.0);
2811 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
2814 // Tests that *_FLOAT_EQ are commutative.
2815 TEST_F(FloatTest, Commutative) {
2816 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2817 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2819 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2820 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2824 // Tests EXPECT_NEAR.
2825 TEST_F(FloatTest, EXPECT_NEAR) {
2826 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2827 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2828 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2829 "The difference between 1.0f and 1.5f is 0.5, "
2830 "which exceeds 0.25f");
2831 // To work around a bug in gcc 2.95.0, there is intentionally no
2832 // space after the first comma in the previous line.
2835 // Tests ASSERT_NEAR.
2836 TEST_F(FloatTest, ASSERT_NEAR) {
2837 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2838 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2839 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2840 "The difference between 1.0f and 1.5f is 0.5, "
2841 "which exceeds 0.25f");
2842 // To work around a bug in gcc 2.95.0, there is intentionally no
2843 // space after the first comma in the previous line.
2846 // Tests the cases where FloatLE() should succeed.
2847 TEST_F(FloatTest, FloatLESucceeds) {
2848 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2849 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
2851 // or when val1 is greater than, but almost equals to, val2.
2852 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2855 // Tests the cases where FloatLE() should fail.
2856 TEST_F(FloatTest, FloatLEFails) {
2857 // When val1 is greater than val2 by a large margin,
2858 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2859 "(2.0f) <= (1.0f)");
2861 // or by a small yet non-negligible margin,
2862 EXPECT_NONFATAL_FAILURE({ // NOLINT
2863 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2864 }, "(values_.further_from_one) <= (1.0f)");
2866 #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2867 // Nokia's STLport crashes if we try to output infinity or NaN.
2868 // C++Builder gives bad results for ordered comparisons involving NaNs
2869 // due to compiler bugs.
2870 EXPECT_NONFATAL_FAILURE({ // NOLINT
2871 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2872 }, "(values_.nan1) <= (values_.infinity)");
2873 EXPECT_NONFATAL_FAILURE({ // NOLINT
2874 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2875 }, "(-values_.infinity) <= (values_.nan1)");
2876 EXPECT_FATAL_FAILURE({ // NOLINT
2877 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2878 }, "(values_.nan1) <= (values_.nan1)");
2879 #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2882 // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2883 typedef FloatingPointTest<double> DoubleTest;
2885 // Tests that the size of Double::Bits matches the size of double.
2886 TEST_F(DoubleTest, Size) {
2890 // Tests comparing with +0 and -0.
2891 TEST_F(DoubleTest, Zeros) {
2892 EXPECT_DOUBLE_EQ(0.0, -0.0);
2893 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2895 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2899 // Tests comparing numbers close to 0.
2901 // This ensures that *_DOUBLE_EQ handles the sign correctly and no
2902 // overflow occurs when comparing numbers whose absolute value is very
2904 TEST_F(DoubleTest, AlmostZeros) {
2905 // In C++Builder, names within local classes (such as used by
2906 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2907 // scoping class. Use a static local alias as a workaround.
2908 // We use the assignment syntax since some compilers, like Sun Studio,
2909 // don't allow initializing references using construction syntax
2911 static const DoubleTest::TestValues& v = this->values_;
2913 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2914 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2915 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2917 EXPECT_FATAL_FAILURE({ // NOLINT
2918 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2919 v.further_from_negative_zero);
2920 }, "v.further_from_negative_zero");
2923 // Tests comparing numbers close to each other.
2924 TEST_F(DoubleTest, SmallDiff) {
2925 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2926 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2927 "values_.further_from_one");
2930 // Tests comparing numbers far apart.
2931 TEST_F(DoubleTest, LargeDiff) {
2932 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2936 // Tests comparing with infinity.
2938 // This ensures that no overflow occurs when comparing numbers whose
2939 // absolute value is very large.
2940 TEST_F(DoubleTest, Infinity) {
2941 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
2942 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
2943 #if !GTEST_OS_SYMBIAN
2944 // Nokia's STLport crashes if we try to output infinity or NaN.
2945 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
2946 "-values_.infinity");
2948 // This is interesting as the representations of infinity_ and nan1_
2949 // are only 1 DLP apart.
2950 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
2952 #endif // !GTEST_OS_SYMBIAN
2955 // Tests that comparing with NAN always returns false.
2956 TEST_F(DoubleTest, NaN) {
2957 #if !GTEST_OS_SYMBIAN
2958 // In C++Builder, names within local classes (such as used by
2959 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2960 // scoping class. Use a static local alias as a workaround.
2961 // We use the assignment syntax since some compilers, like Sun Studio,
2962 // don't allow initializing references using construction syntax
2964 static const DoubleTest::TestValues& v = this->values_;
2966 // Nokia's STLport crashes if we try to output infinity or NaN.
2967 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
2969 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
2970 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
2971 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
2973 #endif // !GTEST_OS_SYMBIAN
2976 // Tests that *_DOUBLE_EQ are reflexive.
2977 TEST_F(DoubleTest, Reflexive) {
2978 EXPECT_DOUBLE_EQ(0.0, 0.0);
2979 EXPECT_DOUBLE_EQ(1.0, 1.0);
2980 #if !GTEST_OS_SYMBIAN
2981 // Nokia's STLport crashes if we try to output infinity or NaN.
2982 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
2983 #endif // !GTEST_OS_SYMBIAN
2986 // Tests that *_DOUBLE_EQ are commutative.
2987 TEST_F(DoubleTest, Commutative) {
2988 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
2989 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
2991 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
2992 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
2996 // Tests EXPECT_NEAR.
2997 TEST_F(DoubleTest, EXPECT_NEAR) {
2998 EXPECT_NEAR(-1.0, -1.1, 0.2);
2999 EXPECT_NEAR(2.0, 3.0, 1.0);
3000 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3001 "The difference between 1.0 and 1.5 is 0.5, "
3002 "which exceeds 0.25");
3003 // To work around a bug in gcc 2.95.0, there is intentionally no
3004 // space after the first comma in the previous statement.
3007 // Tests ASSERT_NEAR.
3008 TEST_F(DoubleTest, ASSERT_NEAR) {
3009 ASSERT_NEAR(-1.0, -1.1, 0.2);
3010 ASSERT_NEAR(2.0, 3.0, 1.0);
3011 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3012 "The difference between 1.0 and 1.5 is 0.5, "
3013 "which exceeds 0.25");
3014 // To work around a bug in gcc 2.95.0, there is intentionally no
3015 // space after the first comma in the previous statement.
3018 // Tests the cases where DoubleLE() should succeed.
3019 TEST_F(DoubleTest, DoubleLESucceeds) {
3020 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3021 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
3023 // or when val1 is greater than, but almost equals to, val2.
3024 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3027 // Tests the cases where DoubleLE() should fail.
3028 TEST_F(DoubleTest, DoubleLEFails) {
3029 // When val1 is greater than val2 by a large margin,
3030 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
3033 // or by a small yet non-negligible margin,
3034 EXPECT_NONFATAL_FAILURE({ // NOLINT
3035 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3036 }, "(values_.further_from_one) <= (1.0)");
3038 #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3039 // Nokia's STLport crashes if we try to output infinity or NaN.
3040 // C++Builder gives bad results for ordered comparisons involving NaNs
3041 // due to compiler bugs.
3042 EXPECT_NONFATAL_FAILURE({ // NOLINT
3043 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3044 }, "(values_.nan1) <= (values_.infinity)");
3045 EXPECT_NONFATAL_FAILURE({ // NOLINT
3046 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3047 }, " (-values_.infinity) <= (values_.nan1)");
3048 EXPECT_FATAL_FAILURE({ // NOLINT
3049 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3050 }, "(values_.nan1) <= (values_.nan1)");
3051 #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3055 // Verifies that a test or test case whose name starts with DISABLED_ is
3058 // A test whose name starts with DISABLED_.
3060 TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3061 FAIL() << "Unexpected failure: Disabled test should not be run.";
3064 // A test whose name does not start with DISABLED_.
3066 TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3070 // A test case whose name starts with DISABLED_.
3072 TEST(DISABLED_TestCase, TestShouldNotRun) {
3073 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3076 // A test case and test whose names start with DISABLED_.
3078 TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
3079 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3082 // Check that when all tests in a test case are disabled, SetupTestCase() and
3083 // TearDownTestCase() are not called.
3084 class DisabledTestsTest : public Test {
3086 static void SetUpTestCase() {
3087 FAIL() << "Unexpected failure: All tests disabled in test case. "
3088 "SetupTestCase() should not be called.";
3091 static void TearDownTestCase() {
3092 FAIL() << "Unexpected failure: All tests disabled in test case. "
3093 "TearDownTestCase() should not be called.";
3097 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3098 FAIL() << "Unexpected failure: Disabled test should not be run.";
3101 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3102 FAIL() << "Unexpected failure: Disabled test should not be run.";
3105 // Tests that disabled typed tests aren't run.
3107 #if GTEST_HAS_TYPED_TEST
3109 template <typename T>
3110 class TypedTest : public Test {
3113 typedef testing::Types<int, double> NumericTypes;
3114 TYPED_TEST_CASE(TypedTest, NumericTypes);
3116 TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3117 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3120 template <typename T>
3121 class DISABLED_TypedTest : public Test {
3124 TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
3126 TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3127 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3130 #endif // GTEST_HAS_TYPED_TEST
3132 // Tests that disabled type-parameterized tests aren't run.
3134 #if GTEST_HAS_TYPED_TEST_P
3136 template <typename T>
3137 class TypedTestP : public Test {
3140 TYPED_TEST_CASE_P(TypedTestP);
3142 TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3143 FAIL() << "Unexpected failure: "
3144 << "Disabled type-parameterized test should not run.";
3147 REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
3149 INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
3151 template <typename T>
3152 class DISABLED_TypedTestP : public Test {
3155 TYPED_TEST_CASE_P(DISABLED_TypedTestP);
3157 TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3158 FAIL() << "Unexpected failure: "
3159 << "Disabled type-parameterized test should not run.";
3162 REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
3164 INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
3166 #endif // GTEST_HAS_TYPED_TEST_P
3168 // Tests that assertion macros evaluate their arguments exactly once.
3170 class SingleEvaluationTest : public Test {
3171 public: // Must be public and not protected due to a bug in g++ 3.4.2.
3172 // This helper function is needed by the FailedASSERT_STREQ test
3173 // below. It's public to work around C++Builder's bug with scoping local
3175 static void CompareAndIncrementCharPtrs() {
3176 ASSERT_STREQ(p1_++, p2_++);
3179 // This helper function is needed by the FailedASSERT_NE test below. It's
3180 // public to work around C++Builder's bug with scoping local classes.
3181 static void CompareAndIncrementInts() {
3182 ASSERT_NE(a_++, b_++);
3186 SingleEvaluationTest() {
3193 static const char* const s1_;
3194 static const char* const s2_;
3195 static const char* p1_;
3196 static const char* p2_;
3202 const char* const SingleEvaluationTest::s1_ = "01234";
3203 const char* const SingleEvaluationTest::s2_ = "abcde";
3204 const char* SingleEvaluationTest::p1_;
3205 const char* SingleEvaluationTest::p2_;
3206 int SingleEvaluationTest::a_;
3207 int SingleEvaluationTest::b_;
3209 // Tests that when ASSERT_STREQ fails, it evaluates its arguments
3211 TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3212 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3214 EXPECT_EQ(s1_ + 1, p1_);
3215 EXPECT_EQ(s2_ + 1, p2_);
3218 // Tests that string assertion arguments are evaluated exactly once.
3219 TEST_F(SingleEvaluationTest, ASSERT_STR) {
3220 // successful EXPECT_STRNE
3221 EXPECT_STRNE(p1_++, p2_++);
3222 EXPECT_EQ(s1_ + 1, p1_);
3223 EXPECT_EQ(s2_ + 1, p2_);
3225 // failed EXPECT_STRCASEEQ
3226 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3228 EXPECT_EQ(s1_ + 2, p1_);
3229 EXPECT_EQ(s2_ + 2, p2_);
3232 // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3234 TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3235 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3236 "(a_++) != (b_++)");
3241 // Tests that assertion arguments are evaluated exactly once.
3242 TEST_F(SingleEvaluationTest, OtherCases) {
3243 // successful EXPECT_TRUE
3244 EXPECT_TRUE(0 == a_++); // NOLINT
3247 // failed EXPECT_TRUE
3248 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3251 // successful EXPECT_GT
3252 EXPECT_GT(a_++, b_++);
3257 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3261 // successful ASSERT_TRUE
3262 ASSERT_TRUE(0 < a_++); // NOLINT
3265 // successful ASSERT_GT
3266 ASSERT_GT(a_++, b_++);
3271 #if GTEST_HAS_EXCEPTIONS
3273 void ThrowAnInteger() {
3277 // Tests that assertion arguments are evaluated exactly once.
3278 TEST_F(SingleEvaluationTest, ExceptionTests) {
3279 // successful EXPECT_THROW
3280 EXPECT_THROW({ // NOLINT
3286 // failed EXPECT_THROW, throws different
3287 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3290 }, bool), "throws a different type");
3293 // failed EXPECT_THROW, throws nothing
3294 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3297 // successful EXPECT_NO_THROW
3298 EXPECT_NO_THROW(a_++);
3301 // failed EXPECT_NO_THROW
3302 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3308 // successful EXPECT_ANY_THROW
3309 EXPECT_ANY_THROW({ // NOLINT
3315 // failed EXPECT_ANY_THROW
3316 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3320 #endif // GTEST_HAS_EXCEPTIONS
3322 // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3323 class NoFatalFailureTest : public Test {
3326 void FailsNonFatal() {
3327 ADD_FAILURE() << "some non-fatal failure";
3330 FAIL() << "some fatal failure";
3333 void DoAssertNoFatalFailureOnFails() {
3334 ASSERT_NO_FATAL_FAILURE(Fails());
3335 ADD_FAILURE() << "shold not reach here.";
3338 void DoExpectNoFatalFailureOnFails() {
3339 EXPECT_NO_FATAL_FAILURE(Fails());
3340 ADD_FAILURE() << "other failure";
3344 TEST_F(NoFatalFailureTest, NoFailure) {
3345 EXPECT_NO_FATAL_FAILURE(Succeeds());
3346 ASSERT_NO_FATAL_FAILURE(Succeeds());
3349 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3350 EXPECT_NONFATAL_FAILURE(
3351 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3352 "some non-fatal failure");
3353 EXPECT_NONFATAL_FAILURE(
3354 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3355 "some non-fatal failure");
3358 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3359 TestPartResultArray gtest_failures;
3361 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3362 DoAssertNoFatalFailureOnFails();
3364 ASSERT_EQ(2, gtest_failures.size());
3365 EXPECT_EQ(TestPartResult::kFatalFailure,
3366 gtest_failures.GetTestPartResult(0).type());
3367 EXPECT_EQ(TestPartResult::kFatalFailure,
3368 gtest_failures.GetTestPartResult(1).type());
3369 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3370 gtest_failures.GetTestPartResult(0).message());
3371 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3372 gtest_failures.GetTestPartResult(1).message());
3375 TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3376 TestPartResultArray gtest_failures;
3378 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3379 DoExpectNoFatalFailureOnFails();
3381 ASSERT_EQ(3, gtest_failures.size());
3382 EXPECT_EQ(TestPartResult::kFatalFailure,
3383 gtest_failures.GetTestPartResult(0).type());
3384 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3385 gtest_failures.GetTestPartResult(1).type());
3386 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3387 gtest_failures.GetTestPartResult(2).type());
3388 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3389 gtest_failures.GetTestPartResult(0).message());
3390 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3391 gtest_failures.GetTestPartResult(1).message());
3392 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3393 gtest_failures.GetTestPartResult(2).message());
3396 TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3397 TestPartResultArray gtest_failures;
3399 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3400 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3402 ASSERT_EQ(2, gtest_failures.size());
3403 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3404 gtest_failures.GetTestPartResult(0).type());
3405 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3406 gtest_failures.GetTestPartResult(1).type());
3407 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3408 gtest_failures.GetTestPartResult(0).message());
3409 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3410 gtest_failures.GetTestPartResult(1).message());
3413 // Tests non-string assertions.
3415 // Tests EqFailure(), used for implementing *EQ* assertions.
3416 TEST(AssertionTest, EqFailure) {
3417 const String foo_val("5"), bar_val("6");
3419 EqFailure("foo", "bar", foo_val, bar_val, false)
3420 .failure_message());
3429 EqFailure("foo", "6", foo_val, bar_val, false)
3430 .failure_message());
3438 EqFailure("5", "bar", foo_val, bar_val, false)
3439 .failure_message());
3447 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3454 EqFailure("foo", "bar",
3455 String("\"x\""), String("\"y\""),
3456 true).failure_message());
3460 "Expected: foo (ignoring case)\n"
3465 // Tests AppendUserMessage(), used for implementing the *EQ* macros.
3466 TEST(AssertionTest, AppendUserMessage) {
3467 const String foo("foo");
3471 AppendUserMessage(foo, msg).c_str());
3474 EXPECT_STREQ("foo\nbar",
3475 AppendUserMessage(foo, msg).c_str());
3479 // Silences warnings: "Condition is always true", "Unreachable code"
3480 #pragma option push -w-ccc -w-rch
3483 // Tests ASSERT_TRUE.
3484 TEST(AssertionTest, ASSERT_TRUE) {
3485 ASSERT_TRUE(2 > 1); // NOLINT
3486 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3490 // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3491 TEST(AssertionTest, AssertTrueWithAssertionResult) {
3492 ASSERT_TRUE(ResultIsEven(2));
3493 #if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600
3494 // ICE's in C++Builder 2007.
3495 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3496 "Value of: ResultIsEven(3)\n"
3497 " Actual: false (3 is odd)\n"
3500 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3501 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3502 "Value of: ResultIsEvenNoExplanation(3)\n"
3503 " Actual: false (3 is odd)\n"
3507 // Tests ASSERT_FALSE.
3508 TEST(AssertionTest, ASSERT_FALSE) {
3509 ASSERT_FALSE(2 < 1); // NOLINT
3510 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3516 // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3517 TEST(AssertionTest, AssertFalseWithAssertionResult) {
3518 ASSERT_FALSE(ResultIsEven(3));
3519 #if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600
3520 // ICE's in C++Builder 2007.
3521 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3522 "Value of: ResultIsEven(2)\n"
3523 " Actual: true (2 is even)\n"
3526 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3527 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3528 "Value of: ResultIsEvenNoExplanation(2)\n"
3534 // Restores warnings after previous "#pragma option push" supressed them
3538 // Tests using ASSERT_EQ on double values. The purpose is to make
3539 // sure that the specialization we did for integer and anonymous enums
3540 // isn't used for double arguments.
3541 TEST(ExpectTest, ASSERT_EQ_Double) {
3543 ASSERT_EQ(5.6, 5.6);
3546 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3551 TEST(AssertionTest, ASSERT_EQ) {
3552 ASSERT_EQ(5, 2 + 3);
3553 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3559 // Tests ASSERT_EQ(NULL, pointer).
3560 #if GTEST_CAN_COMPARE_NULL
3561 TEST(AssertionTest, ASSERT_EQ_NULL) {
3563 const char* p = NULL;
3564 // Some older GCC versions may issue a spurious waring in this or the next
3565 // assertion statement. This warning should not be suppressed with
3566 // static_cast since the test verifies the ability to use bare NULL as the
3567 // expected parameter to the macro.
3572 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3575 #endif // GTEST_CAN_COMPARE_NULL
3577 // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3578 // treated as a null pointer by the compiler, we need to make sure
3579 // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3580 // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3581 TEST(ExpectTest, ASSERT_EQ_0) {
3588 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3593 TEST(AssertionTest, ASSERT_NE) {
3595 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3596 "Expected: ('a') != ('a'), "
3597 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3601 TEST(AssertionTest, ASSERT_LE) {
3604 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3605 "Expected: (2) <= (0), actual: 2 vs 0");
3609 TEST(AssertionTest, ASSERT_LT) {
3611 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3612 "Expected: (2) < (2), actual: 2 vs 2");
3616 TEST(AssertionTest, ASSERT_GE) {
3619 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3620 "Expected: (2) >= (3), actual: 2 vs 3");
3624 TEST(AssertionTest, ASSERT_GT) {
3626 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3627 "Expected: (2) > (2), actual: 2 vs 2");
3630 #if GTEST_HAS_EXCEPTIONS
3632 void ThrowNothing() {}
3634 // Tests ASSERT_THROW.
3635 TEST(AssertionTest, ASSERT_THROW) {
3636 ASSERT_THROW(ThrowAnInteger(), int);
3638 #ifndef __BORLANDC__
3639 // ICE's in C++Builder 2007 and 2009.
3640 EXPECT_FATAL_FAILURE(
3641 ASSERT_THROW(ThrowAnInteger(), bool),
3642 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3643 " Actual: it throws a different type.");
3646 EXPECT_FATAL_FAILURE(
3647 ASSERT_THROW(ThrowNothing(), bool),
3648 "Expected: ThrowNothing() throws an exception of type bool.\n"
3649 " Actual: it throws nothing.");
3652 // Tests ASSERT_NO_THROW.
3653 TEST(AssertionTest, ASSERT_NO_THROW) {
3654 ASSERT_NO_THROW(ThrowNothing());
3655 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3656 "Expected: ThrowAnInteger() doesn't throw an exception."
3657 "\n Actual: it throws.");
3660 // Tests ASSERT_ANY_THROW.
3661 TEST(AssertionTest, ASSERT_ANY_THROW) {
3662 ASSERT_ANY_THROW(ThrowAnInteger());
3663 EXPECT_FATAL_FAILURE(
3664 ASSERT_ANY_THROW(ThrowNothing()),
3665 "Expected: ThrowNothing() throws an exception.\n"
3666 " Actual: it doesn't.");
3669 #endif // GTEST_HAS_EXCEPTIONS
3671 // Makes sure we deal with the precedence of <<. This test should
3673 TEST(AssertionTest, AssertPrecedence) {
3674 ASSERT_EQ(1 < 2, true);
3675 ASSERT_EQ(true && false, false);
3678 // A subroutine used by the following test.
3679 void TestEq1(int x) {
3683 // Tests calling a test subroutine that's not part of a fixture.
3684 TEST(AssertionTest, NonFixtureSubroutine) {
3685 EXPECT_FATAL_FAILURE(TestEq1(2),
3689 // An uncopyable class.
3692 explicit Uncopyable(int a_value) : value_(a_value) {}
3694 int value() const { return value_; }
3695 bool operator==(const Uncopyable& rhs) const {
3696 return value() == rhs.value();
3699 // This constructor deliberately has no implementation, as we don't
3700 // want this class to be copyable.
3701 Uncopyable(const Uncopyable&); // NOLINT
3706 ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3707 return os << value.value();
3711 bool IsPositiveUncopyable(const Uncopyable& x) {
3712 return x.value() > 0;
3715 // A subroutine used by the following test.
3716 void TestAssertNonPositive() {
3718 ASSERT_PRED1(IsPositiveUncopyable, y);
3720 // A subroutine used by the following test.
3721 void TestAssertEqualsUncopyable() {
3727 // Tests that uncopyable objects can be used in assertions.
3728 TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3730 ASSERT_PRED1(IsPositiveUncopyable, x);
3732 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3733 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3734 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3735 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3738 // Tests that uncopyable objects can be used in expects.
3739 TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3741 EXPECT_PRED1(IsPositiveUncopyable, x);
3743 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3744 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3746 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3747 "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
3751 // The version of gcc used in XCode 2.2 has a bug and doesn't allow
3752 // anonymous enums in assertions. Therefore the following test is not
3754 // Sun Studio also rejects this code.
3755 #if !GTEST_OS_MAC && !defined(__SUNPRO_CC)
3757 // Tests using assertions with anonymous enums.
3761 // We want to test the case where the size of the anonymous enum is
3762 // larger than sizeof(int), to make sure our implementation of the
3763 // assertions doesn't truncate the enums. However, MSVC
3764 // (incorrectly) doesn't allow an enum value to exceed the range of
3765 // an int, so this has to be conditionally compiled.
3767 // On Linux, CASE_B and CASE_A have the same value when truncated to
3768 // int size. We want to test whether this will confuse the
3770 CASE_B = testing::internal::kMaxBiggestInt,
3773 #endif // GTEST_OS_LINUX
3776 TEST(AssertionTest, AnonymousEnum) {
3778 EXPECT_EQ(static_cast<int>(CASE_A), static_cast<int>(CASE_B));
3779 #endif // GTEST_OS_LINUX
3781 EXPECT_EQ(CASE_A, CASE_A);
3782 EXPECT_NE(CASE_A, CASE_B);
3783 EXPECT_LT(CASE_A, CASE_B);
3784 EXPECT_LE(CASE_A, CASE_B);
3785 EXPECT_GT(CASE_B, CASE_A);
3786 EXPECT_GE(CASE_A, CASE_A);
3787 EXPECT_NONFATAL_FAILURE(EXPECT_GE(CASE_A, CASE_B),
3788 "(CASE_A) >= (CASE_B)");
3790 ASSERT_EQ(CASE_A, CASE_A);
3791 ASSERT_NE(CASE_A, CASE_B);
3792 ASSERT_LT(CASE_A, CASE_B);
3793 ASSERT_LE(CASE_A, CASE_B);
3794 ASSERT_GT(CASE_B, CASE_A);
3795 ASSERT_GE(CASE_A, CASE_A);
3796 EXPECT_FATAL_FAILURE(ASSERT_EQ(CASE_A, CASE_B),
3797 "Value of: CASE_B");
3800 #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
3802 #if GTEST_OS_WINDOWS
3804 static HRESULT UnexpectedHRESULTFailure() {
3805 return E_UNEXPECTED;
3808 static HRESULT OkHRESULTSuccess() {
3812 static HRESULT FalseHRESULTSuccess() {
3816 // HRESULT assertion tests test both zero and non-zero
3817 // success codes as well as failure message for each.
3819 // Windows CE doesn't support message texts.
3820 TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3821 EXPECT_HRESULT_SUCCEEDED(S_OK);
3822 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3824 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3825 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3826 " Actual: 0x8000FFFF");
3829 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3830 ASSERT_HRESULT_SUCCEEDED(S_OK);
3831 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3833 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3834 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3835 " Actual: 0x8000FFFF");
3838 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
3839 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
3841 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
3842 "Expected: (OkHRESULTSuccess()) fails.\n"
3843 " Actual: 0x00000000");
3844 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
3845 "Expected: (FalseHRESULTSuccess()) fails.\n"
3846 " Actual: 0x00000001");
3849 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
3850 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
3852 #ifndef __BORLANDC__
3853 // ICE's in C++Builder 2007 and 2009.
3854 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
3855 "Expected: (OkHRESULTSuccess()) fails.\n"
3856 " Actual: 0x00000000");
3858 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
3859 "Expected: (FalseHRESULTSuccess()) fails.\n"
3860 " Actual: 0x00000001");
3863 // Tests that streaming to the HRESULT macros works.
3864 TEST(HRESULTAssertionTest, Streaming) {
3865 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3866 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
3867 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3868 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
3870 EXPECT_NONFATAL_FAILURE(
3871 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3872 "expected failure");
3874 #ifndef __BORLANDC__
3875 // ICE's in C++Builder 2007 and 2009.
3876 EXPECT_FATAL_FAILURE(
3877 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
3878 "expected failure");
3881 EXPECT_NONFATAL_FAILURE(
3882 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
3883 "expected failure");
3885 EXPECT_FATAL_FAILURE(
3886 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
3887 "expected failure");
3890 #endif // GTEST_OS_WINDOWS
3893 // Silences warnings: "Condition is always true", "Unreachable code"
3894 #pragma option push -w-ccc -w-rch
3897 // Tests that the assertion macros behave like single statements.
3898 TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
3900 ASSERT_TRUE(false) << "This should never be executed; "
3901 "It's a compilation test only.";
3904 EXPECT_FALSE(false);
3914 EXPECT_GT(3, 2) << "";
3917 #if GTEST_HAS_EXCEPTIONS
3918 // Tests that the compiler will not complain about unreachable code in the
3919 // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
3920 TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
3923 EXPECT_THROW(throw 1, int);
3924 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
3925 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
3926 EXPECT_NO_THROW(n++);
3927 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
3928 EXPECT_ANY_THROW(throw 1);
3929 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
3932 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
3934 EXPECT_THROW(ThrowNothing(), bool);
3937 EXPECT_THROW(ThrowAnInteger(), int);
3942 EXPECT_NO_THROW(ThrowAnInteger());
3945 EXPECT_NO_THROW(ThrowNothing());
3950 EXPECT_ANY_THROW(ThrowNothing());
3953 EXPECT_ANY_THROW(ThrowAnInteger());
3957 #endif // GTEST_HAS_EXCEPTIONS
3959 TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
3961 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
3962 << "It's a compilation test only.";
3967 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
3972 EXPECT_NO_FATAL_FAILURE(SUCCEED());
3979 ASSERT_NO_FATAL_FAILURE(SUCCEED());
3982 // Tests that the assertion macros work well with switch statements.
3983 TEST(AssertionSyntaxTest, WorksWithSwitch) {
3993 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
3995 // Binary assertions are implemented using a different code path
3996 // than the Boolean assertions. Hence we test them separately.
4000 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4008 #if GTEST_HAS_EXCEPTIONS
4010 void ThrowAString() {
4014 // Test that the exception assertion macros compile and work with const
4016 TEST(AssertionSyntaxTest, WorksWithConst) {
4017 ASSERT_THROW(ThrowAString(), const char*);
4019 EXPECT_THROW(ThrowAString(), const char*);
4022 #endif // GTEST_HAS_EXCEPTIONS
4028 // Tests that Google Test tracks SUCCEED*.
4029 TEST(SuccessfulAssertionTest, SUCCEED) {
4032 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4035 // Tests that Google Test doesn't track successful EXPECT_*.
4036 TEST(SuccessfulAssertionTest, EXPECT) {
4038 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4041 // Tests that Google Test doesn't track successful EXPECT_STR*.
4042 TEST(SuccessfulAssertionTest, EXPECT_STR) {
4043 EXPECT_STREQ("", "");
4044 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4047 // Tests that Google Test doesn't track successful ASSERT_*.
4048 TEST(SuccessfulAssertionTest, ASSERT) {
4050 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4053 // Tests that Google Test doesn't track successful ASSERT_STR*.
4054 TEST(SuccessfulAssertionTest, ASSERT_STR) {
4055 ASSERT_STREQ("", "");
4056 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4059 } // namespace testing
4063 // Tests EXPECT_TRUE.
4064 TEST(ExpectTest, EXPECT_TRUE) {
4065 EXPECT_TRUE(2 > 1); // NOLINT
4066 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4070 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4074 // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4075 TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4076 EXPECT_TRUE(ResultIsEven(2));
4077 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4078 "Value of: ResultIsEven(3)\n"
4079 " Actual: false (3 is odd)\n"
4081 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4082 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4083 "Value of: ResultIsEvenNoExplanation(3)\n"
4084 " Actual: false (3 is odd)\n"
4088 // Tests EXPECT_FALSE.
4089 TEST(ExpectTest, EXPECT_FALSE) {
4090 EXPECT_FALSE(2 < 1); // NOLINT
4091 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4095 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4099 // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4100 TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4101 EXPECT_FALSE(ResultIsEven(3));
4102 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4103 "Value of: ResultIsEven(2)\n"
4104 " Actual: true (2 is even)\n"
4106 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4107 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4108 "Value of: ResultIsEvenNoExplanation(2)\n"
4114 // Restores warnings after previous "#pragma option push" supressed them
4119 TEST(ExpectTest, EXPECT_EQ) {
4120 EXPECT_EQ(5, 2 + 3);
4121 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4125 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4129 // Tests using EXPECT_EQ on double values. The purpose is to make
4130 // sure that the specialization we did for integer and anonymous enums
4131 // isn't used for double arguments.
4132 TEST(ExpectTest, EXPECT_EQ_Double) {
4134 EXPECT_EQ(5.6, 5.6);
4137 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4141 #if GTEST_CAN_COMPARE_NULL
4142 // Tests EXPECT_EQ(NULL, pointer).
4143 TEST(ExpectTest, EXPECT_EQ_NULL) {
4145 const char* p = NULL;
4146 // Some older GCC versions may issue a spurious waring in this or the next
4147 // assertion statement. This warning should not be suppressed with
4148 // static_cast since the test verifies the ability to use bare NULL as the
4149 // expected parameter to the macro.
4154 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
4157 #endif // GTEST_CAN_COMPARE_NULL
4159 // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4160 // treated as a null pointer by the compiler, we need to make sure
4161 // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4162 // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4163 TEST(ExpectTest, EXPECT_EQ_0) {
4170 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4175 TEST(ExpectTest, EXPECT_NE) {
4178 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4179 "Expected: ('a') != ('a'), "
4180 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4181 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4183 char* const p0 = NULL;
4184 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4186 // Only way to get the Nokia compiler to compile the cast
4187 // is to have a separate void* variable first. Putting
4188 // the two casts on the same line doesn't work, neither does
4189 // a direct C-style to char*.
4190 void* pv1 = (void*)0x1234; // NOLINT
4191 char* const p1 = reinterpret_cast<char*>(pv1);
4192 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4197 TEST(ExpectTest, EXPECT_LE) {
4200 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4201 "Expected: (2) <= (0), actual: 2 vs 0");
4202 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4207 TEST(ExpectTest, EXPECT_LT) {
4209 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4210 "Expected: (2) < (2), actual: 2 vs 2");
4211 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4216 TEST(ExpectTest, EXPECT_GE) {
4219 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4220 "Expected: (2) >= (3), actual: 2 vs 3");
4221 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4226 TEST(ExpectTest, EXPECT_GT) {
4228 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4229 "Expected: (2) > (2), actual: 2 vs 2");
4230 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4234 #if GTEST_HAS_EXCEPTIONS
4236 // Tests EXPECT_THROW.
4237 TEST(ExpectTest, EXPECT_THROW) {
4238 EXPECT_THROW(ThrowAnInteger(), int);
4239 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4240 "Expected: ThrowAnInteger() throws an exception of "
4241 "type bool.\n Actual: it throws a different type.");
4242 EXPECT_NONFATAL_FAILURE(
4243 EXPECT_THROW(ThrowNothing(), bool),
4244 "Expected: ThrowNothing() throws an exception of type bool.\n"
4245 " Actual: it throws nothing.");
4248 // Tests EXPECT_NO_THROW.
4249 TEST(ExpectTest, EXPECT_NO_THROW) {
4250 EXPECT_NO_THROW(ThrowNothing());
4251 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4252 "Expected: ThrowAnInteger() doesn't throw an "
4253 "exception.\n Actual: it throws.");
4256 // Tests EXPECT_ANY_THROW.
4257 TEST(ExpectTest, EXPECT_ANY_THROW) {
4258 EXPECT_ANY_THROW(ThrowAnInteger());
4259 EXPECT_NONFATAL_FAILURE(
4260 EXPECT_ANY_THROW(ThrowNothing()),
4261 "Expected: ThrowNothing() throws an exception.\n"
4262 " Actual: it doesn't.");
4265 #endif // GTEST_HAS_EXCEPTIONS
4267 // Make sure we deal with the precedence of <<.
4268 TEST(ExpectTest, ExpectPrecedence) {
4269 EXPECT_EQ(1 < 2, true);
4270 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4271 "Value of: true && false");
4275 // Tests the StreamableToString() function.
4277 // Tests using StreamableToString() on a scalar.
4278 TEST(StreamableToStringTest, Scalar) {
4279 EXPECT_STREQ("5", StreamableToString(5).c_str());
4282 // Tests using StreamableToString() on a non-char pointer.
4283 TEST(StreamableToStringTest, Pointer) {
4286 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4289 // Tests using StreamableToString() on a NULL non-char pointer.
4290 TEST(StreamableToStringTest, NullPointer) {
4292 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4295 // Tests using StreamableToString() on a C string.
4296 TEST(StreamableToStringTest, CString) {
4297 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4300 // Tests using StreamableToString() on a NULL C string.
4301 TEST(StreamableToStringTest, NullCString) {
4303 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4306 // Tests using streamable values as assertion messages.
4308 // Tests using std::string as an assertion message.
4309 TEST(StreamableTest, string) {
4310 static const std::string str(
4311 "This failure message is a std::string, and is expected.");
4312 EXPECT_FATAL_FAILURE(FAIL() << str,
4316 // Tests that we can output strings containing embedded NULs.
4317 // Limited to Linux because we can only do this with std::string's.
4318 TEST(StreamableTest, stringWithEmbeddedNUL) {
4319 static const char char_array_with_nul[] =
4320 "Here's a NUL\0 and some more string";
4321 static const std::string string_with_nul(char_array_with_nul,
4322 sizeof(char_array_with_nul)
4323 - 1); // drops the trailing NUL
4324 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4325 "Here's a NUL\\0 and some more string");
4328 // Tests that we can output a NUL char.
4329 TEST(StreamableTest, NULChar) {
4330 EXPECT_FATAL_FAILURE({ // NOLINT
4331 FAIL() << "A NUL" << '\0' << " and some more string";
4332 }, "A NUL\\0 and some more string");
4335 // Tests using int as an assertion message.
4336 TEST(StreamableTest, int) {
4337 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4341 // Tests using NULL char pointer as an assertion message.
4343 // In MSVC, streaming a NULL char * causes access violation. Google Test
4344 // implemented a workaround (substituting "(null)" for NULL). This
4345 // tests whether the workaround works.
4346 TEST(StreamableTest, NullCharPtr) {
4347 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4351 // Tests that basic IO manipulators (endl, ends, and flush) can be
4352 // streamed to testing::Message.
4353 TEST(StreamableTest, BasicIoManip) {
4354 EXPECT_FATAL_FAILURE({ // NOLINT
4355 FAIL() << "Line 1." << std::endl
4356 << "A NUL char " << std::ends << std::flush << " in line 2.";
4357 }, "Line 1.\nA NUL char \\0 in line 2.");
4360 // Tests the macros that haven't been covered so far.
4362 void AddFailureHelper(bool* aborted) {
4364 ADD_FAILURE() << "Failure";
4368 // Tests ADD_FAILURE.
4369 TEST(MacroTest, ADD_FAILURE) {
4370 bool aborted = true;
4371 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4373 EXPECT_FALSE(aborted);
4377 TEST(MacroTest, FAIL) {
4378 EXPECT_FATAL_FAILURE(FAIL(),
4380 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4381 "Intentional failure.");
4385 TEST(MacroTest, SUCCEED) {
4387 SUCCEED() << "Explicit success.";
4391 // Tests for EXPECT_EQ() and ASSERT_EQ().
4393 // These tests fail *intentionally*, s.t. the failure messages can be
4394 // generated and tested.
4396 // We have different tests for different argument types.
4398 // Tests using bool values in {EXPECT|ASSERT}_EQ.
4399 TEST(EqAssertionTest, Bool) {
4400 EXPECT_EQ(true, true);
4401 EXPECT_FATAL_FAILURE(ASSERT_EQ(false, true),
4405 // Tests using int values in {EXPECT|ASSERT}_EQ.
4406 TEST(EqAssertionTest, Int) {
4408 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4412 // Tests using time_t values in {EXPECT|ASSERT}_EQ.
4413 TEST(EqAssertionTest, Time_T) {
4414 EXPECT_EQ(static_cast<time_t>(0),
4415 static_cast<time_t>(0));
4416 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4417 static_cast<time_t>(1234)),
4421 // Tests using char values in {EXPECT|ASSERT}_EQ.
4422 TEST(EqAssertionTest, Char) {
4423 ASSERT_EQ('z', 'z');
4424 const char ch = 'b';
4425 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4427 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4431 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4432 TEST(EqAssertionTest, WideChar) {
4433 EXPECT_EQ(L'b', L'b');
4435 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4437 " Actual: L'x' (120, 0x78)\n"
4439 "Which is: L'\0' (0, 0x0)");
4441 static wchar_t wchar;
4443 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4446 EXPECT_FATAL_FAILURE(ASSERT_EQ(L'\x8120', wchar),
4450 // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4451 TEST(EqAssertionTest, StdString) {
4452 // Compares a const char* to an std::string that has identical
4454 ASSERT_EQ("Test", ::std::string("Test"));
4456 // Compares two identical std::strings.
4457 static const ::std::string str1("A * in the middle");
4458 static const ::std::string str2(str1);
4459 EXPECT_EQ(str1, str2);
4461 // Compares a const char* to an std::string that has different
4463 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4464 "::std::string(\"test\")");
4466 // Compares an std::string to a char* that has different content.
4467 char* const p1 = const_cast<char*>("foo");
4468 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4471 // Compares two std::strings that have different contents, one of
4472 // which having a NUL character in the middle. This should fail.
4473 static ::std::string str3(str1);
4475 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4477 " Actual: \"A \\0 in the middle\"");
4480 #if GTEST_HAS_STD_WSTRING
4482 // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4483 TEST(EqAssertionTest, StdWideString) {
4484 // Compares an std::wstring to a const wchar_t* that has identical
4486 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8119");
4488 // Compares two identical std::wstrings.
4489 const ::std::wstring wstr1(L"A * in the middle");
4490 const ::std::wstring wstr2(wstr1);
4491 ASSERT_EQ(wstr1, wstr2);
4493 // Compares an std::wstring to a const wchar_t* that has different
4495 EXPECT_NONFATAL_FAILURE({ // NOLINT
4496 EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8120");
4497 }, "L\"Test\\x8120\"");
4499 // Compares two std::wstrings that have different contents, one of
4500 // which having a NUL character in the middle.
4501 ::std::wstring wstr3(wstr1);
4502 wstr3.at(2) = L'\0';
4503 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4506 // Compares a wchar_t* to an std::wstring that has different
4508 EXPECT_FATAL_FAILURE({ // NOLINT
4509 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4513 #endif // GTEST_HAS_STD_WSTRING
4515 #if GTEST_HAS_GLOBAL_STRING
4516 // Tests using ::string values in {EXPECT|ASSERT}_EQ.
4517 TEST(EqAssertionTest, GlobalString) {
4518 // Compares a const char* to a ::string that has identical content.
4519 EXPECT_EQ("Test", ::string("Test"));
4521 // Compares two identical ::strings.
4522 const ::string str1("A * in the middle");
4523 const ::string str2(str1);
4524 ASSERT_EQ(str1, str2);
4526 // Compares a ::string to a const char* that has different content.
4527 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4530 // Compares two ::strings that have different contents, one of which
4531 // having a NUL character in the middle.
4532 ::string str3(str1);
4534 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4537 // Compares a ::string to a char* that has different content.
4538 EXPECT_FATAL_FAILURE({ // NOLINT
4539 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4543 #endif // GTEST_HAS_GLOBAL_STRING
4545 #if GTEST_HAS_GLOBAL_WSTRING
4547 // Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4548 TEST(EqAssertionTest, GlobalWideString) {
4549 // Compares a const wchar_t* to a ::wstring that has identical content.
4550 ASSERT_EQ(L"Test\x8119", ::wstring(L"Test\x8119"));
4552 // Compares two identical ::wstrings.
4553 static const ::wstring wstr1(L"A * in the middle");
4554 static const ::wstring wstr2(wstr1);
4555 EXPECT_EQ(wstr1, wstr2);
4557 // Compares a const wchar_t* to a ::wstring that has different
4559 EXPECT_NONFATAL_FAILURE({ // NOLINT
4560 EXPECT_EQ(L"Test\x8120", ::wstring(L"Test\x8119"));
4563 // Compares a wchar_t* to a ::wstring that has different content.
4564 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4565 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4568 // Compares two ::wstrings that have different contents, one of which
4569 // having a NUL character in the middle.
4570 static ::wstring wstr3;
4572 wstr3.at(2) = L'\0';
4573 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4577 #endif // GTEST_HAS_GLOBAL_WSTRING
4579 // Tests using char pointers in {EXPECT|ASSERT}_EQ.
4580 TEST(EqAssertionTest, CharPointer) {
4581 char* const p0 = NULL;
4582 // Only way to get the Nokia compiler to compile the cast
4583 // is to have a separate void* variable first. Putting
4584 // the two casts on the same line doesn't work, neither does
4585 // a direct C-style to char*.
4586 void* pv1 = (void*)0x1234; // NOLINT
4587 void* pv2 = (void*)0xABC0; // NOLINT
4588 char* const p1 = reinterpret_cast<char*>(pv1);
4589 char* const p2 = reinterpret_cast<char*>(pv2);
4592 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4594 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4596 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4597 reinterpret_cast<char*>(0xABC0)),
4601 // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4602 TEST(EqAssertionTest, WideCharPointer) {
4603 wchar_t* const p0 = NULL;
4604 // Only way to get the Nokia compiler to compile the cast
4605 // is to have a separate void* variable first. Putting
4606 // the two casts on the same line doesn't work, neither does
4607 // a direct C-style to char*.
4608 void* pv1 = (void*)0x1234; // NOLINT
4609 void* pv2 = (void*)0xABC0; // NOLINT
4610 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4611 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4614 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4616 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4618 void* pv3 = (void*)0x1234; // NOLINT
4619 void* pv4 = (void*)0xABC0; // NOLINT
4620 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4621 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4622 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4626 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4627 TEST(EqAssertionTest, OtherPointer) {
4628 ASSERT_EQ(static_cast<const int*>(NULL),
4629 static_cast<const int*>(NULL));
4630 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4631 reinterpret_cast<const int*>(0x1234)),
4635 // Tests the FRIEND_TEST macro.
4637 // This class has a private member we want to test. We will test it
4638 // both in a TEST and in a TEST_F.
4644 int Bar() const { return 1; }
4646 // Declares the friend tests that can access the private member
4648 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4649 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4652 // Tests that the FRIEND_TEST declaration allows a TEST to access a
4653 // class's private members. This should compile.
4654 TEST(FRIEND_TEST_Test, TEST) {
4655 ASSERT_EQ(1, Foo().Bar());
4658 // The fixture needed to test using FRIEND_TEST with TEST_F.
4659 class FRIEND_TEST_Test2 : public Test {
4664 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
4665 // class's private members. This should compile.
4666 TEST_F(FRIEND_TEST_Test2, TEST_F) {
4667 ASSERT_EQ(1, foo.Bar());
4670 // Tests the life cycle of Test objects.
4672 // The test fixture for testing the life cycle of Test objects.
4674 // This class counts the number of live test objects that uses this
4676 class TestLifeCycleTest : public Test {
4678 // Constructor. Increments the number of test objects that uses
4680 TestLifeCycleTest() { count_++; }
4682 // Destructor. Decrements the number of test objects that uses this
4684 ~TestLifeCycleTest() { count_--; }
4686 // Returns the number of live test objects that uses this fixture.
4687 int count() const { return count_; }
4693 int TestLifeCycleTest::count_ = 0;
4695 // Tests the life cycle of test objects.
4696 TEST_F(TestLifeCycleTest, Test1) {
4697 // There should be only one test object in this test case that's
4699 ASSERT_EQ(1, count());
4702 // Tests the life cycle of test objects.
4703 TEST_F(TestLifeCycleTest, Test2) {
4704 // After Test1 is done and Test2 is started, there should still be
4705 // only one live test object, as the object for Test1 should've been
4707 ASSERT_EQ(1, count());
4712 // Tests that the copy constructor works when it is NOT optimized away by
4714 TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
4715 // Checks that the copy constructor doesn't try to dereference NULL pointers
4716 // in the source object.
4717 AssertionResult r1 = AssertionSuccess();
4718 AssertionResult r2 = r1;
4719 // The following line is added to prevent the compiler from optimizing
4720 // away the constructor call.
4723 AssertionResult r3 = r1;
4724 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
4725 EXPECT_STREQ("abc", r1.message());
4728 // Tests that AssertionSuccess and AssertionFailure construct
4729 // AssertionResult objects as expected.
4730 TEST(AssertionResultTest, ConstructionWorks) {
4731 AssertionResult r1 = AssertionSuccess();
4733 EXPECT_STREQ("", r1.message());
4735 AssertionResult r2 = AssertionSuccess() << "abc";
4737 EXPECT_STREQ("abc", r2.message());
4739 AssertionResult r3 = AssertionFailure();
4741 EXPECT_STREQ("", r3.message());
4743 AssertionResult r4 = AssertionFailure() << "def";
4745 EXPECT_STREQ("def", r4.message());
4747 AssertionResult r5 = AssertionFailure(Message() << "ghi");
4749 EXPECT_STREQ("ghi", r5.message());
4752 // Tests that the negation fips the predicate result but keeps the message.
4753 TEST(AssertionResultTest, NegationWorks) {
4754 AssertionResult r1 = AssertionSuccess() << "abc";
4756 EXPECT_STREQ("abc", (!r1).message());
4758 AssertionResult r2 = AssertionFailure() << "def";
4760 EXPECT_STREQ("def", (!r2).message());
4763 TEST(AssertionResultTest, StreamingWorks) {
4764 AssertionResult r = AssertionSuccess();
4765 r << "abc" << 'd' << 0 << true;
4766 EXPECT_STREQ("abcd0true", r.message());
4769 // Tests streaming a user type whose definition and operator << are
4770 // both in the global namespace.
4773 explicit Base(int an_x) : x_(an_x) {}
4774 int x() const { return x_; }
4778 std::ostream& operator<<(std::ostream& os,
4780 return os << val.x();
4782 std::ostream& operator<<(std::ostream& os,
4783 const Base* pointer) {
4784 return os << "(" << pointer->x() << ")";
4787 TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
4791 msg << a << &a; // Uses ::operator<<.
4792 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4795 // Tests streaming a user type whose definition and operator<< are
4796 // both in an unnamed namespace.
4798 class MyTypeInUnnamedNameSpace : public Base {
4800 explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
4802 std::ostream& operator<<(std::ostream& os,
4803 const MyTypeInUnnamedNameSpace& val) {
4804 return os << val.x();
4806 std::ostream& operator<<(std::ostream& os,
4807 const MyTypeInUnnamedNameSpace* pointer) {
4808 return os << "(" << pointer->x() << ")";
4812 TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
4814 MyTypeInUnnamedNameSpace a(1);
4816 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
4817 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4820 // Tests streaming a user type whose definition and operator<< are
4821 // both in a user namespace.
4822 namespace namespace1 {
4823 class MyTypeInNameSpace1 : public Base {
4825 explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
4827 std::ostream& operator<<(std::ostream& os,
4828 const MyTypeInNameSpace1& val) {
4829 return os << val.x();
4831 std::ostream& operator<<(std::ostream& os,
4832 const MyTypeInNameSpace1* pointer) {
4833 return os << "(" << pointer->x() << ")";
4835 } // namespace namespace1
4837 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
4839 namespace1::MyTypeInNameSpace1 a(1);
4841 msg << a << &a; // Uses namespace1::operator<<.
4842 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4845 // Tests streaming a user type whose definition is in a user namespace
4846 // but whose operator<< is in the global namespace.
4847 namespace namespace2 {
4848 class MyTypeInNameSpace2 : public ::Base {
4850 explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
4852 } // namespace namespace2
4853 std::ostream& operator<<(std::ostream& os,
4854 const namespace2::MyTypeInNameSpace2& val) {
4855 return os << val.x();
4857 std::ostream& operator<<(std::ostream& os,
4858 const namespace2::MyTypeInNameSpace2* pointer) {
4859 return os << "(" << pointer->x() << ")";
4862 TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
4864 namespace2::MyTypeInNameSpace2 a(1);
4866 msg << a << &a; // Uses ::operator<<.
4867 EXPECT_STREQ("1(1)", msg.GetString().c_str());
4870 // Tests streaming NULL pointers to testing::Message.
4871 TEST(MessageTest, NullPointers) {
4873 char* const p1 = NULL;
4874 unsigned char* const p2 = NULL;
4880 msg << p1 << p2 << p3 << p4 << p5 << p6;
4881 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
4882 msg.GetString().c_str());
4885 // Tests streaming wide strings to testing::Message.
4886 TEST(MessageTest, WideStrings) {
4887 // Streams a NULL of type const wchar_t*.
4888 const wchar_t* const_wstr = NULL;
4889 EXPECT_STREQ("(null)",
4890 (Message() << const_wstr).GetString().c_str());
4892 // Streams a NULL of type wchar_t*.
4893 wchar_t* wstr = NULL;
4894 EXPECT_STREQ("(null)",
4895 (Message() << wstr).GetString().c_str());
4897 // Streams a non-NULL of type const wchar_t*.
4898 const_wstr = L"abc\x8119";
4899 EXPECT_STREQ("abc\xe8\x84\x99",
4900 (Message() << const_wstr).GetString().c_str());
4902 // Streams a non-NULL of type wchar_t*.
4903 wstr = const_cast<wchar_t*>(const_wstr);
4904 EXPECT_STREQ("abc\xe8\x84\x99",
4905 (Message() << wstr).GetString().c_str());
4909 // This line tests that we can define tests in the testing namespace.
4912 // Tests the TestInfo class.
4914 class TestInfoTest : public Test {
4916 static const TestInfo* GetTestInfo(const char* test_name) {
4917 const TestCase* const test_case = GetUnitTestImpl()->
4918 GetTestCase("TestInfoTest", "", NULL, NULL);
4920 for (int i = 0; i < test_case->total_test_count(); ++i) {
4921 const TestInfo* const test_info = test_case->GetTestInfo(i);
4922 if (strcmp(test_name, test_info->name()) == 0)
4928 static const TestResult* GetTestResult(
4929 const TestInfo* test_info) {
4930 return test_info->result();
4934 // Tests TestInfo::test_case_name() and TestInfo::name().
4935 TEST_F(TestInfoTest, Names) {
4936 const TestInfo* const test_info = GetTestInfo("Names");
4938 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
4939 ASSERT_STREQ("Names", test_info->name());
4942 // Tests TestInfo::result().
4943 TEST_F(TestInfoTest, result) {
4944 const TestInfo* const test_info = GetTestInfo("result");
4946 // Initially, there is no TestPartResult for this test.
4947 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
4949 // After the previous assertion, there is still none.
4950 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
4953 // Tests setting up and tearing down a test case.
4955 class SetUpTestCaseTest : public Test {
4957 // This will be called once before the first test in this test case
4959 static void SetUpTestCase() {
4960 printf("Setting up the test case . . .\n");
4962 // Initializes some shared resource. In this simple example, we
4963 // just create a C string. More complex stuff can be done if
4965 shared_resource_ = "123";
4967 // Increments the number of test cases that have been set up.
4970 // SetUpTestCase() should be called only once.
4971 EXPECT_EQ(1, counter_);
4974 // This will be called once after the last test in this test case is
4976 static void TearDownTestCase() {
4977 printf("Tearing down the test case . . .\n");
4979 // Decrements the number of test cases that have been set up.
4982 // TearDownTestCase() should be called only once.
4983 EXPECT_EQ(0, counter_);
4985 // Cleans up the shared resource.
4986 shared_resource_ = NULL;
4989 // This will be called before each test in this test case.
4990 virtual void SetUp() {
4991 // SetUpTestCase() should be called only once, so counter_ should
4993 EXPECT_EQ(1, counter_);
4996 // Number of test cases that have been set up.
4997 static int counter_;
4999 // Some resource to be shared by all tests in this test case.
5000 static const char* shared_resource_;
5003 int SetUpTestCaseTest::counter_ = 0;
5004 const char* SetUpTestCaseTest::shared_resource_ = NULL;
5006 // A test that uses the shared resource.
5007 TEST_F(SetUpTestCaseTest, Test1) {
5008 EXPECT_STRNE(NULL, shared_resource_);
5011 // Another test that uses the shared resource.
5012 TEST_F(SetUpTestCaseTest, Test2) {
5013 EXPECT_STREQ("123", shared_resource_);
5016 // The InitGoogleTestTest test case tests testing::InitGoogleTest().
5018 // The Flags struct stores a copy of all Google Test flags.
5020 // Constructs a Flags struct where each flag has its default value.
5021 Flags() : also_run_disabled_tests(false),
5022 break_on_failure(false),
5023 catch_exceptions(false),
5024 death_test_use_fork(false),
5032 stack_trace_depth(kMaxStackTraceDepth),
5033 throw_on_failure(false) {}
5037 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5039 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5041 flags.also_run_disabled_tests = also_run_disabled_tests;
5045 // Creates a Flags struct where the gtest_break_on_failure flag has
5047 static Flags BreakOnFailure(bool break_on_failure) {
5049 flags.break_on_failure = break_on_failure;
5053 // Creates a Flags struct where the gtest_catch_exceptions flag has
5055 static Flags CatchExceptions(bool catch_exceptions) {
5057 flags.catch_exceptions = catch_exceptions;
5061 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5063 static Flags DeathTestUseFork(bool death_test_use_fork) {
5065 flags.death_test_use_fork = death_test_use_fork;
5069 // Creates a Flags struct where the gtest_filter flag has the given
5071 static Flags Filter(const char* filter) {
5073 flags.filter = filter;
5077 // Creates a Flags struct where the gtest_list_tests flag has the
5079 static Flags ListTests(bool list_tests) {
5081 flags.list_tests = list_tests;
5085 // Creates a Flags struct where the gtest_output flag has the given
5087 static Flags Output(const char* output) {
5089 flags.output = output;
5093 // Creates a Flags struct where the gtest_print_time flag has the given
5095 static Flags PrintTime(bool print_time) {
5097 flags.print_time = print_time;
5101 // Creates a Flags struct where the gtest_random_seed flag has
5103 static Flags RandomSeed(Int32 random_seed) {
5105 flags.random_seed = random_seed;
5109 // Creates a Flags struct where the gtest_repeat flag has the given
5111 static Flags Repeat(Int32 repeat) {
5113 flags.repeat = repeat;
5117 // Creates a Flags struct where the gtest_shuffle flag has
5119 static Flags Shuffle(bool shuffle) {
5121 flags.shuffle = shuffle;
5125 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5127 static Flags StackTraceDepth(Int32 stack_trace_depth) {
5129 flags.stack_trace_depth = stack_trace_depth;
5133 // Creates a Flags struct where the gtest_throw_on_failure flag has
5135 static Flags ThrowOnFailure(bool throw_on_failure) {
5137 flags.throw_on_failure = throw_on_failure;
5141 // These fields store the flag values.
5142 bool also_run_disabled_tests;
5143 bool break_on_failure;
5144 bool catch_exceptions;
5145 bool death_test_use_fork;
5153 Int32 stack_trace_depth;
5154 bool throw_on_failure;
5157 // Fixture for testing InitGoogleTest().
5158 class InitGoogleTestTest : public Test {
5160 // Clears the flags before each test.
5161 virtual void SetUp() {
5162 GTEST_FLAG(also_run_disabled_tests) = false;
5163 GTEST_FLAG(break_on_failure) = false;
5164 GTEST_FLAG(catch_exceptions) = false;
5165 GTEST_FLAG(death_test_use_fork) = false;
5166 GTEST_FLAG(filter) = "";
5167 GTEST_FLAG(list_tests) = false;
5168 GTEST_FLAG(output) = "";
5169 GTEST_FLAG(print_time) = true;
5170 GTEST_FLAG(random_seed) = 0;
5171 GTEST_FLAG(repeat) = 1;
5172 GTEST_FLAG(shuffle) = false;
5173 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
5174 GTEST_FLAG(throw_on_failure) = false;
5177 // Asserts that two narrow or wide string arrays are equal.
5178 template <typename CharType>
5179 static void AssertStringArrayEq(size_t size1, CharType** array1,
5180 size_t size2, CharType** array2) {
5181 ASSERT_EQ(size1, size2) << " Array sizes different.";
5183 for (size_t i = 0; i != size1; i++) {
5184 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5188 // Verifies that the flag values match the expected values.
5189 static void CheckFlags(const Flags& expected) {
5190 EXPECT_EQ(expected.also_run_disabled_tests,
5191 GTEST_FLAG(also_run_disabled_tests));
5192 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5193 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
5194 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
5195 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5196 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5197 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
5198 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
5199 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
5200 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
5201 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
5202 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
5203 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
5206 // Parses a command line (specified by argc1 and argv1), then
5207 // verifies that the flag values are expected and that the
5208 // recognized flags are removed from the command line.
5209 template <typename CharType>
5210 static void TestParsingFlags(int argc1, const CharType** argv1,
5211 int argc2, const CharType** argv2,
5212 const Flags& expected, bool should_print_help) {
5213 const bool saved_help_flag = ::testing::internal::g_help_flag;
5214 ::testing::internal::g_help_flag = false;
5216 #if GTEST_HAS_STREAM_REDIRECTION_
5218 #endif // GTEST_HAS_STREAM_REDIRECTION_
5220 // Parses the command line.
5221 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5223 #if GTEST_HAS_STREAM_REDIRECTION_
5224 const String captured_stdout = GetCapturedStdout();
5225 #endif // GTEST_HAS_STREAM_REDIRECTION_
5227 // Verifies the flag values.
5228 CheckFlags(expected);
5230 // Verifies that the recognized flags are removed from the command
5232 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5234 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5235 // help message for the flags it recognizes.
5236 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5238 #if GTEST_HAS_STREAM_REDIRECTION_
5239 const char* const expected_help_fragment =
5240 "This program contains tests written using";
5241 if (should_print_help) {
5242 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5244 EXPECT_PRED_FORMAT2(IsNotSubstring,
5245 expected_help_fragment, captured_stdout);
5247 #endif // GTEST_HAS_STREAM_REDIRECTION_
5249 ::testing::internal::g_help_flag = saved_help_flag;
5252 // This macro wraps TestParsingFlags s.t. the user doesn't need
5253 // to specify the array sizes.
5254 #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5255 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5256 sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5257 expected, should_print_help)
5260 // Tests parsing an empty command line.
5261 TEST_F(InitGoogleTestTest, Empty) {
5262 const char* argv[] = {
5266 const char* argv2[] = {
5270 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5273 // Tests parsing a command line that has no flag.
5274 TEST_F(InitGoogleTestTest, NoFlag) {
5275 const char* argv[] = {
5280 const char* argv2[] = {
5285 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5288 // Tests parsing a bad --gtest_filter flag.
5289 TEST_F(InitGoogleTestTest, FilterBad) {
5290 const char* argv[] = {
5296 const char* argv2[] = {
5302 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
5305 // Tests parsing an empty --gtest_filter flag.
5306 TEST_F(InitGoogleTestTest, FilterEmpty) {
5307 const char* argv[] = {
5313 const char* argv2[] = {
5318 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5321 // Tests parsing a non-empty --gtest_filter flag.
5322 TEST_F(InitGoogleTestTest, FilterNonEmpty) {
5323 const char* argv[] = {
5325 "--gtest_filter=abc",
5329 const char* argv2[] = {
5334 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5337 // Tests parsing --gtest_break_on_failure.
5338 TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
5339 const char* argv[] = {
5341 "--gtest_break_on_failure",
5345 const char* argv2[] = {
5350 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5353 // Tests parsing --gtest_break_on_failure=0.
5354 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
5355 const char* argv[] = {
5357 "--gtest_break_on_failure=0",
5361 const char* argv2[] = {
5366 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5369 // Tests parsing --gtest_break_on_failure=f.
5370 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5371 const char* argv[] = {
5373 "--gtest_break_on_failure=f",
5377 const char* argv2[] = {
5382 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5385 // Tests parsing --gtest_break_on_failure=F.
5386 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5387 const char* argv[] = {
5389 "--gtest_break_on_failure=F",
5393 const char* argv2[] = {
5398 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5401 // Tests parsing a --gtest_break_on_failure flag that has a "true"
5403 TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5404 const char* argv[] = {
5406 "--gtest_break_on_failure=1",
5410 const char* argv2[] = {
5415 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5418 // Tests parsing --gtest_catch_exceptions.
5419 TEST_F(InitGoogleTestTest, CatchExceptions) {
5420 const char* argv[] = {
5422 "--gtest_catch_exceptions",
5426 const char* argv2[] = {
5431 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5434 // Tests parsing --gtest_death_test_use_fork.
5435 TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5436 const char* argv[] = {
5438 "--gtest_death_test_use_fork",
5442 const char* argv2[] = {
5447 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5450 // Tests having the same flag twice with different values. The
5451 // expected behavior is that the one coming last takes precedence.
5452 TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5453 const char* argv[] = {
5460 const char* argv2[] = {
5465 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5468 // Tests having an unrecognized flag on the command line.
5469 TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5470 const char* argv[] = {
5472 "--gtest_break_on_failure",
5473 "bar", // Unrecognized by Google Test.
5478 const char* argv2[] = {
5485 flags.break_on_failure = true;
5487 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5490 // Tests having a --gtest_list_tests flag
5491 TEST_F(InitGoogleTestTest, ListTestsFlag) {
5492 const char* argv[] = {
5494 "--gtest_list_tests",
5498 const char* argv2[] = {
5503 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5506 // Tests having a --gtest_list_tests flag with a "true" value
5507 TEST_F(InitGoogleTestTest, ListTestsTrue) {
5508 const char* argv[] = {
5510 "--gtest_list_tests=1",
5514 const char* argv2[] = {
5519 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5522 // Tests having a --gtest_list_tests flag with a "false" value
5523 TEST_F(InitGoogleTestTest, ListTestsFalse) {
5524 const char* argv[] = {
5526 "--gtest_list_tests=0",
5530 const char* argv2[] = {
5535 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5538 // Tests parsing --gtest_list_tests=f.
5539 TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5540 const char* argv[] = {
5542 "--gtest_list_tests=f",
5546 const char* argv2[] = {
5551 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5554 // Tests parsing --gtest_list_tests=F.
5555 TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
5556 const char* argv[] = {
5558 "--gtest_list_tests=F",
5562 const char* argv2[] = {
5567 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5570 // Tests parsing --gtest_output (invalid).
5571 TEST_F(InitGoogleTestTest, OutputEmpty) {
5572 const char* argv[] = {
5578 const char* argv2[] = {
5584 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
5587 // Tests parsing --gtest_output=xml
5588 TEST_F(InitGoogleTestTest, OutputXml) {
5589 const char* argv[] = {
5591 "--gtest_output=xml",
5595 const char* argv2[] = {
5600 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
5603 // Tests parsing --gtest_output=xml:file
5604 TEST_F(InitGoogleTestTest, OutputXmlFile) {
5605 const char* argv[] = {
5607 "--gtest_output=xml:file",
5611 const char* argv2[] = {
5616 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
5619 // Tests parsing --gtest_output=xml:directory/path/
5620 TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
5621 const char* argv[] = {
5623 "--gtest_output=xml:directory/path/",
5627 const char* argv2[] = {
5632 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5633 Flags::Output("xml:directory/path/"), false);
5636 // Tests having a --gtest_print_time flag
5637 TEST_F(InitGoogleTestTest, PrintTimeFlag) {
5638 const char* argv[] = {
5640 "--gtest_print_time",
5644 const char* argv2[] = {
5649 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
5652 // Tests having a --gtest_print_time flag with a "true" value
5653 TEST_F(InitGoogleTestTest, PrintTimeTrue) {
5654 const char* argv[] = {
5656 "--gtest_print_time=1",
5660 const char* argv2[] = {
5665 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
5668 // Tests having a --gtest_print_time flag with a "false" value
5669 TEST_F(InitGoogleTestTest, PrintTimeFalse) {
5670 const char* argv[] = {
5672 "--gtest_print_time=0",
5676 const char* argv2[] = {
5681 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
5684 // Tests parsing --gtest_print_time=f.
5685 TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
5686 const char* argv[] = {
5688 "--gtest_print_time=f",
5692 const char* argv2[] = {
5697 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
5700 // Tests parsing --gtest_print_time=F.
5701 TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
5702 const char* argv[] = {
5704 "--gtest_print_time=F",
5708 const char* argv2[] = {
5713 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
5716 // Tests parsing --gtest_random_seed=number
5717 TEST_F(InitGoogleTestTest, RandomSeed) {
5718 const char* argv[] = {
5720 "--gtest_random_seed=1000",
5724 const char* argv2[] = {
5729 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
5732 // Tests parsing --gtest_repeat=number
5733 TEST_F(InitGoogleTestTest, Repeat) {
5734 const char* argv[] = {
5736 "--gtest_repeat=1000",
5740 const char* argv2[] = {
5745 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
5748 // Tests having a --gtest_also_run_disabled_tests flag
5749 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
5750 const char* argv[] = {
5752 "--gtest_also_run_disabled_tests",
5756 const char* argv2[] = {
5761 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5762 Flags::AlsoRunDisabledTests(true), false);
5765 // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
5766 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
5767 const char* argv[] = {
5769 "--gtest_also_run_disabled_tests=1",
5773 const char* argv2[] = {
5778 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5779 Flags::AlsoRunDisabledTests(true), false);
5782 // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
5783 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
5784 const char* argv[] = {
5786 "--gtest_also_run_disabled_tests=0",
5790 const char* argv2[] = {
5795 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
5796 Flags::AlsoRunDisabledTests(false), false);
5799 // Tests parsing --gtest_shuffle.
5800 TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
5801 const char* argv[] = {
5807 const char* argv2[] = {
5812 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
5815 // Tests parsing --gtest_shuffle=0.
5816 TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
5817 const char* argv[] = {
5819 "--gtest_shuffle=0",
5823 const char* argv2[] = {
5828 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
5831 // Tests parsing a --gtest_shuffle flag that has a "true"
5833 TEST_F(InitGoogleTestTest, ShuffleTrue) {
5834 const char* argv[] = {
5836 "--gtest_shuffle=1",
5840 const char* argv2[] = {
5845 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
5848 // Tests parsing --gtest_stack_trace_depth=number.
5849 TEST_F(InitGoogleTestTest, StackTraceDepth) {
5850 const char* argv[] = {
5852 "--gtest_stack_trace_depth=5",
5856 const char* argv2[] = {
5861 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
5864 // Tests parsing --gtest_throw_on_failure.
5865 TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
5866 const char* argv[] = {
5868 "--gtest_throw_on_failure",
5872 const char* argv2[] = {
5877 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
5880 // Tests parsing --gtest_throw_on_failure=0.
5881 TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
5882 const char* argv[] = {
5884 "--gtest_throw_on_failure=0",
5888 const char* argv2[] = {
5893 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
5896 // Tests parsing a --gtest_throw_on_failure flag that has a "true"
5898 TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
5899 const char* argv[] = {
5901 "--gtest_throw_on_failure=1",
5905 const char* argv2[] = {
5910 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
5913 #if GTEST_OS_WINDOWS
5914 // Tests parsing wide strings.
5915 TEST_F(InitGoogleTestTest, WideStrings) {
5916 const wchar_t* argv[] = {
5918 L"--gtest_filter=Foo*",
5919 L"--gtest_list_tests=1",
5920 L"--gtest_break_on_failure",
5921 L"--non_gtest_flag",
5925 const wchar_t* argv2[] = {
5927 L"--non_gtest_flag",
5931 Flags expected_flags;
5932 expected_flags.break_on_failure = true;
5933 expected_flags.filter = "Foo*";
5934 expected_flags.list_tests = true;
5936 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
5938 #endif // GTEST_OS_WINDOWS
5940 // Tests current_test_info() in UnitTest.
5941 class CurrentTestInfoTest : public Test {
5943 // Tests that current_test_info() returns NULL before the first test in
5944 // the test case is run.
5945 static void SetUpTestCase() {
5946 // There should be no tests running at this point.
5947 const TestInfo* test_info =
5948 UnitTest::GetInstance()->current_test_info();
5949 EXPECT_TRUE(test_info == NULL)
5950 << "There should be no tests running at this point.";
5953 // Tests that current_test_info() returns NULL after the last test in
5954 // the test case has run.
5955 static void TearDownTestCase() {
5956 const TestInfo* test_info =
5957 UnitTest::GetInstance()->current_test_info();
5958 EXPECT_TRUE(test_info == NULL)
5959 << "There should be no tests running at this point.";
5963 // Tests that current_test_info() returns TestInfo for currently running
5964 // test by checking the expected test name against the actual one.
5965 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
5966 const TestInfo* test_info =
5967 UnitTest::GetInstance()->current_test_info();
5968 ASSERT_TRUE(NULL != test_info)
5969 << "There is a test running so we should have a valid TestInfo.";
5970 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
5971 << "Expected the name of the currently running test case.";
5972 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
5973 << "Expected the name of the currently running test.";
5976 // Tests that current_test_info() returns TestInfo for currently running
5977 // test by checking the expected test name against the actual one. We
5978 // use this test to see that the TestInfo object actually changed from
5979 // the previous invocation.
5980 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
5981 const TestInfo* test_info =
5982 UnitTest::GetInstance()->current_test_info();
5983 ASSERT_TRUE(NULL != test_info)
5984 << "There is a test running so we should have a valid TestInfo.";
5985 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
5986 << "Expected the name of the currently running test case.";
5987 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
5988 << "Expected the name of the currently running test.";
5991 } // namespace testing
5993 // These two lines test that we can define tests in a namespace that
5994 // has the name "testing" and is nested in another namespace.
5995 namespace my_namespace {
5998 // Makes sure that TEST knows to use ::testing::Test instead of
5999 // ::my_namespace::testing::Test.
6002 // Makes sure that an assertion knows to use ::testing::Message instead of
6003 // ::my_namespace::testing::Message.
6006 // Makes sure that an assertion knows to use
6007 // ::testing::AssertionResult instead of
6008 // ::my_namespace::testing::AssertionResult.
6009 class AssertionResult {};
6011 // Tests that an assertion that should succeed works as expected.
6012 TEST(NestedTestingNamespaceTest, Success) {
6013 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6016 // Tests that an assertion that should fail works as expected.
6017 TEST(NestedTestingNamespaceTest, Failure) {
6018 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6019 "This failure is expected.");
6022 } // namespace testing
6023 } // namespace my_namespace
6025 // Tests that one can call superclass SetUp and TearDown methods--
6026 // that is, that they are not private.
6027 // No tests are based on this fixture; the test "passes" if it compiles
6029 class ProtectedFixtureMethodsTest : public Test {
6031 virtual void SetUp() {
6034 virtual void TearDown() {
6039 // StreamingAssertionsTest tests the streaming versions of a representative
6040 // sample of assertions.
6041 TEST(StreamingAssertionsTest, Unconditional) {
6042 SUCCEED() << "expected success";
6043 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6044 "expected failure");
6045 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6046 "expected failure");
6050 // Silences warnings: "Condition is always true", "Unreachable code"
6051 #pragma option push -w-ccc -w-rch
6054 TEST(StreamingAssertionsTest, Truth) {
6055 EXPECT_TRUE(true) << "unexpected failure";
6056 ASSERT_TRUE(true) << "unexpected failure";
6057 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6058 "expected failure");
6059 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6060 "expected failure");
6063 TEST(StreamingAssertionsTest, Truth2) {
6064 EXPECT_FALSE(false) << "unexpected failure";
6065 ASSERT_FALSE(false) << "unexpected failure";
6066 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6067 "expected failure");
6068 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6069 "expected failure");
6073 // Restores warnings after previous "#pragma option push" supressed them
6077 TEST(StreamingAssertionsTest, IntegerEquals) {
6078 EXPECT_EQ(1, 1) << "unexpected failure";
6079 ASSERT_EQ(1, 1) << "unexpected failure";
6080 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6081 "expected failure");
6082 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6083 "expected failure");
6086 TEST(StreamingAssertionsTest, IntegerLessThan) {
6087 EXPECT_LT(1, 2) << "unexpected failure";
6088 ASSERT_LT(1, 2) << "unexpected failure";
6089 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6090 "expected failure");
6091 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6092 "expected failure");
6095 TEST(StreamingAssertionsTest, StringsEqual) {
6096 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6097 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6098 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6099 "expected failure");
6100 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6101 "expected failure");
6104 TEST(StreamingAssertionsTest, StringsNotEqual) {
6105 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6106 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6107 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6108 "expected failure");
6109 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6110 "expected failure");
6113 TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6114 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6115 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6116 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6117 "expected failure");
6118 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6119 "expected failure");
6122 TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6123 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6124 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6125 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6126 "expected failure");
6127 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6128 "expected failure");
6131 TEST(StreamingAssertionsTest, FloatingPointEquals) {
6132 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6133 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6134 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6135 "expected failure");
6136 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6137 "expected failure");
6140 #if GTEST_HAS_EXCEPTIONS
6142 TEST(StreamingAssertionsTest, Throw) {
6143 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6144 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6145 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6146 "expected failure", "expected failure");
6147 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6148 "expected failure", "expected failure");
6151 TEST(StreamingAssertionsTest, NoThrow) {
6152 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6153 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6154 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6155 "expected failure", "expected failure");
6156 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6157 "expected failure", "expected failure");
6160 TEST(StreamingAssertionsTest, AnyThrow) {
6161 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6162 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6163 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
6164 "expected failure", "expected failure");
6165 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
6166 "expected failure", "expected failure");
6169 #endif // GTEST_HAS_EXCEPTIONS
6171 // Tests that Google Test correctly decides whether to use colors in the output.
6173 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6174 GTEST_FLAG(color) = "yes";
6176 SetEnv("TERM", "xterm"); // TERM supports colors.
6177 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6178 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6180 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6181 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6182 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6185 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6186 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6188 GTEST_FLAG(color) = "True";
6189 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6191 GTEST_FLAG(color) = "t";
6192 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6194 GTEST_FLAG(color) = "1";
6195 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6198 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6199 GTEST_FLAG(color) = "no";
6201 SetEnv("TERM", "xterm"); // TERM supports colors.
6202 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6203 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6205 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6206 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6207 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6210 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6211 SetEnv("TERM", "xterm"); // TERM supports colors.
6213 GTEST_FLAG(color) = "F";
6214 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6216 GTEST_FLAG(color) = "0";
6217 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6219 GTEST_FLAG(color) = "unknown";
6220 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6223 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6224 GTEST_FLAG(color) = "auto";
6226 SetEnv("TERM", "xterm"); // TERM supports colors.
6227 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6228 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6231 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6232 GTEST_FLAG(color) = "auto";
6234 #if GTEST_OS_WINDOWS
6235 // On Windows, we ignore the TERM variable as it's usually not set.
6237 SetEnv("TERM", "dumb");
6238 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6241 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6243 SetEnv("TERM", "xterm");
6244 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6246 // On non-Windows platforms, we rely on TERM to determine if the
6247 // terminal supports colors.
6249 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6250 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6252 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6253 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6255 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6256 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6258 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6259 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6261 SetEnv("TERM", "xterm"); // TERM supports colors.
6262 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6264 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6265 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6267 SetEnv("TERM", "linux"); // TERM supports colors.
6268 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6269 #endif // GTEST_OS_WINDOWS
6272 // Verifies that StaticAssertTypeEq works in a namespace scope.
6274 static bool dummy1 = StaticAssertTypeEq<bool, bool>();
6275 static bool dummy2 = StaticAssertTypeEq<const int, const int>();
6277 // Verifies that StaticAssertTypeEq works in a class.
6279 template <typename T>
6280 class StaticAssertTypeEqTestHelper {
6282 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6285 TEST(StaticAssertTypeEqTest, WorksInClass) {
6286 StaticAssertTypeEqTestHelper<bool>();
6289 // Verifies that StaticAssertTypeEq works inside a function.
6291 typedef int IntAlias;
6293 TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6294 StaticAssertTypeEq<int, IntAlias>();
6295 StaticAssertTypeEq<int*, IntAlias*>();
6298 TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
6299 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
6301 // We don't have a stack walker in Google Test yet.
6302 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
6303 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
6306 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6307 EXPECT_FALSE(HasNonfatalFailure());
6310 static void FailFatally() { FAIL(); }
6312 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6314 const bool has_nonfatal_failure = HasNonfatalFailure();
6315 ClearCurrentTestPartResults();
6316 EXPECT_FALSE(has_nonfatal_failure);
6319 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6321 const bool has_nonfatal_failure = HasNonfatalFailure();
6322 ClearCurrentTestPartResults();
6323 EXPECT_TRUE(has_nonfatal_failure);
6326 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6329 const bool has_nonfatal_failure = HasNonfatalFailure();
6330 ClearCurrentTestPartResults();
6331 EXPECT_TRUE(has_nonfatal_failure);
6334 // A wrapper for calling HasNonfatalFailure outside of a test body.
6335 static bool HasNonfatalFailureHelper() {
6336 return testing::Test::HasNonfatalFailure();
6339 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6340 EXPECT_FALSE(HasNonfatalFailureHelper());
6343 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6345 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6346 ClearCurrentTestPartResults();
6347 EXPECT_TRUE(has_nonfatal_failure);
6350 TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6351 EXPECT_FALSE(HasFailure());
6354 TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6356 const bool has_failure = HasFailure();
6357 ClearCurrentTestPartResults();
6358 EXPECT_TRUE(has_failure);
6361 TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6363 const bool has_failure = HasFailure();
6364 ClearCurrentTestPartResults();
6365 EXPECT_TRUE(has_failure);
6368 TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6371 const bool has_failure = HasFailure();
6372 ClearCurrentTestPartResults();
6373 EXPECT_TRUE(has_failure);
6376 // A wrapper for calling HasFailure outside of a test body.
6377 static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6379 TEST(HasFailureTest, WorksOutsideOfTestBody) {
6380 EXPECT_FALSE(HasFailureHelper());
6383 TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6385 const bool has_failure = HasFailureHelper();
6386 ClearCurrentTestPartResults();
6387 EXPECT_TRUE(has_failure);
6390 class TestListener : public EmptyTestEventListener {
6392 TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
6393 TestListener(int* on_start_counter, bool* is_destroyed)
6394 : on_start_counter_(on_start_counter),
6395 is_destroyed_(is_destroyed) {}
6397 virtual ~TestListener() {
6399 *is_destroyed_ = true;
6403 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
6404 if (on_start_counter_ != NULL)
6405 (*on_start_counter_)++;
6409 int* on_start_counter_;
6410 bool* is_destroyed_;
6413 // Tests the constructor.
6414 TEST(TestEventListenersTest, ConstructionWorks) {
6415 TestEventListeners listeners;
6417 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
6418 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6419 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6422 // Tests that the TestEventListeners destructor deletes all the listeners it
6424 TEST(TestEventListenersTest, DestructionWorks) {
6425 bool default_result_printer_is_destroyed = false;
6426 bool default_xml_printer_is_destroyed = false;
6427 bool extra_listener_is_destroyed = false;
6428 TestListener* default_result_printer = new TestListener(
6429 NULL, &default_result_printer_is_destroyed);
6430 TestListener* default_xml_printer = new TestListener(
6431 NULL, &default_xml_printer_is_destroyed);
6432 TestListener* extra_listener = new TestListener(
6433 NULL, &extra_listener_is_destroyed);
6436 TestEventListeners listeners;
6437 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
6438 default_result_printer);
6439 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
6440 default_xml_printer);
6441 listeners.Append(extra_listener);
6443 EXPECT_TRUE(default_result_printer_is_destroyed);
6444 EXPECT_TRUE(default_xml_printer_is_destroyed);
6445 EXPECT_TRUE(extra_listener_is_destroyed);
6448 // Tests that a listener Append'ed to a TestEventListeners list starts
6449 // receiving events.
6450 TEST(TestEventListenersTest, Append) {
6451 int on_start_counter = 0;
6452 bool is_destroyed = false;
6453 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6455 TestEventListeners listeners;
6456 listeners.Append(listener);
6457 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6458 *UnitTest::GetInstance());
6459 EXPECT_EQ(1, on_start_counter);
6461 EXPECT_TRUE(is_destroyed);
6464 // Tests that listeners receive events in the order they were appended to
6465 // the list, except for *End requests, which must be received in the reverse
6467 class SequenceTestingListener : public EmptyTestEventListener {
6469 SequenceTestingListener(std::vector<String>* vector, const char* id)
6470 : vector_(vector), id_(id) {}
6473 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
6474 vector_->push_back(GetEventDescription("OnTestProgramStart"));
6477 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
6478 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
6481 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
6482 int /*iteration*/) {
6483 vector_->push_back(GetEventDescription("OnTestIterationStart"));
6486 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
6487 int /*iteration*/) {
6488 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
6492 String GetEventDescription(const char* method) {
6494 message << id_ << "." << method;
6495 return message.GetString();
6498 std::vector<String>* vector_;
6499 const char* const id_;
6501 GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
6504 TEST(EventListenerTest, AppendKeepsOrder) {
6505 std::vector<String> vec;
6506 TestEventListeners listeners;
6507 listeners.Append(new SequenceTestingListener(&vec, "1st"));
6508 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
6509 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
6511 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6512 *UnitTest::GetInstance());
6513 ASSERT_EQ(3U, vec.size());
6514 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
6515 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
6516 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
6519 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
6520 *UnitTest::GetInstance());
6521 ASSERT_EQ(3U, vec.size());
6522 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
6523 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
6524 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
6527 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
6528 *UnitTest::GetInstance(), 0);
6529 ASSERT_EQ(3U, vec.size());
6530 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
6531 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
6532 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
6535 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
6536 *UnitTest::GetInstance(), 0);
6537 ASSERT_EQ(3U, vec.size());
6538 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
6539 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
6540 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
6543 // Tests that a listener removed from a TestEventListeners list stops receiving
6544 // events and is not deleted when the list is destroyed.
6545 TEST(TestEventListenersTest, Release) {
6546 int on_start_counter = 0;
6547 bool is_destroyed = false;
6548 // Although Append passes the ownership of this object to the list,
6549 // the following calls release it, and we need to delete it before the
6551 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6553 TestEventListeners listeners;
6554 listeners.Append(listener);
6555 EXPECT_EQ(listener, listeners.Release(listener));
6556 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6557 *UnitTest::GetInstance());
6558 EXPECT_TRUE(listeners.Release(listener) == NULL);
6560 EXPECT_EQ(0, on_start_counter);
6561 EXPECT_FALSE(is_destroyed);
6565 // Tests that no events are forwarded when event forwarding is disabled.
6566 TEST(EventListenerTest, SuppressEventForwarding) {
6567 int on_start_counter = 0;
6568 TestListener* listener = new TestListener(&on_start_counter, NULL);
6570 TestEventListeners listeners;
6571 listeners.Append(listener);
6572 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6573 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
6574 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6575 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6576 *UnitTest::GetInstance());
6577 EXPECT_EQ(0, on_start_counter);
6580 // Tests that events generated by Google Test are not forwarded in
6581 // death test subprocesses.
6582 TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
6583 EXPECT_DEATH_IF_SUPPORTED({
6584 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
6585 *GetUnitTestImpl()->listeners())) << "expected failure";},
6586 "expected failure");
6589 // Tests that a listener installed via SetDefaultResultPrinter() starts
6590 // receiving events and is returned via default_result_printer() and that
6591 // the previous default_result_printer is removed from the list and deleted.
6592 TEST(EventListenerTest, default_result_printer) {
6593 int on_start_counter = 0;
6594 bool is_destroyed = false;
6595 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6597 TestEventListeners listeners;
6598 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
6600 EXPECT_EQ(listener, listeners.default_result_printer());
6602 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6603 *UnitTest::GetInstance());
6605 EXPECT_EQ(1, on_start_counter);
6607 // Replacing default_result_printer with something else should remove it
6608 // from the list and destroy it.
6609 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
6611 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6612 EXPECT_TRUE(is_destroyed);
6614 // After broadcasting an event the counter is still the same, indicating
6615 // the listener is not in the list anymore.
6616 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6617 *UnitTest::GetInstance());
6618 EXPECT_EQ(1, on_start_counter);
6621 // Tests that the default_result_printer listener stops receiving events
6622 // when removed via Release and that is not owned by the list anymore.
6623 TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
6624 int on_start_counter = 0;
6625 bool is_destroyed = false;
6626 // Although Append passes the ownership of this object to the list,
6627 // the following calls release it, and we need to delete it before the
6629 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6631 TestEventListeners listeners;
6632 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
6634 EXPECT_EQ(listener, listeners.Release(listener));
6635 EXPECT_TRUE(listeners.default_result_printer() == NULL);
6636 EXPECT_FALSE(is_destroyed);
6638 // Broadcasting events now should not affect default_result_printer.
6639 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6640 *UnitTest::GetInstance());
6641 EXPECT_EQ(0, on_start_counter);
6643 // Destroying the list should not affect the listener now, too.
6644 EXPECT_FALSE(is_destroyed);
6648 // Tests that a listener installed via SetDefaultXmlGenerator() starts
6649 // receiving events and is returned via default_xml_generator() and that
6650 // the previous default_xml_generator is removed from the list and deleted.
6651 TEST(EventListenerTest, default_xml_generator) {
6652 int on_start_counter = 0;
6653 bool is_destroyed = false;
6654 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6656 TestEventListeners listeners;
6657 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
6659 EXPECT_EQ(listener, listeners.default_xml_generator());
6661 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6662 *UnitTest::GetInstance());
6664 EXPECT_EQ(1, on_start_counter);
6666 // Replacing default_xml_generator with something else should remove it
6667 // from the list and destroy it.
6668 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
6670 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6671 EXPECT_TRUE(is_destroyed);
6673 // After broadcasting an event the counter is still the same, indicating
6674 // the listener is not in the list anymore.
6675 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6676 *UnitTest::GetInstance());
6677 EXPECT_EQ(1, on_start_counter);
6680 // Tests that the default_xml_generator listener stops receiving events
6681 // when removed via Release and that is not owned by the list anymore.
6682 TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
6683 int on_start_counter = 0;
6684 bool is_destroyed = false;
6685 // Although Append passes the ownership of this object to the list,
6686 // the following calls release it, and we need to delete it before the
6688 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6690 TestEventListeners listeners;
6691 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
6693 EXPECT_EQ(listener, listeners.Release(listener));
6694 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
6695 EXPECT_FALSE(is_destroyed);
6697 // Broadcasting events now should not affect default_xml_generator.
6698 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6699 *UnitTest::GetInstance());
6700 EXPECT_EQ(0, on_start_counter);
6702 // Destroying the list should not affect the listener now, too.
6703 EXPECT_FALSE(is_destroyed);
6707 // Sanity tests to ensure that the alternative, verbose spellings of
6708 // some of the macros work. We don't test them thoroughly as that
6709 // would be quite involved. Since their implementations are
6710 // straightforward, and they are rarely used, we'll just rely on the
6711 // users to tell us when they are broken.
6712 GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
6713 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
6715 // GTEST_FAIL is the same as FAIL.
6716 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
6717 "An expected failure");