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