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