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