1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 // Tests for Google Test itself. This verifies that the basic constructs of
34 #include "gtest/gtest.h"
36 // Verifies that the command line flag variables can be accessed in
37 // code once "gtest.h" has been #included.
38 // Do not move it after other gtest #includes.
39 TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
40 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
41 || testing::GTEST_FLAG(break_on_failure)
42 || testing::GTEST_FLAG(catch_exceptions)
43 || testing::GTEST_FLAG(color) != "unknown"
44 || testing::GTEST_FLAG(filter) != "unknown"
45 || testing::GTEST_FLAG(list_tests)
46 || testing::GTEST_FLAG(output) != "unknown"
47 || testing::GTEST_FLAG(print_time)
48 || testing::GTEST_FLAG(random_seed)
49 || testing::GTEST_FLAG(repeat) > 0
50 || testing::GTEST_FLAG(show_internal_stack_frames)
51 || testing::GTEST_FLAG(shuffle)
52 || testing::GTEST_FLAG(stack_trace_depth) > 0
53 || testing::GTEST_FLAG(stream_result_to) != "unknown"
54 || testing::GTEST_FLAG(throw_on_failure);
55 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
58 #include <limits.h> // For INT_MAX.
67 #include <unordered_set>
68 #endif // GTEST_LANG_CXX11
70 #include "gtest/gtest-spi.h"
71 #include "src/gtest-internal-inl.h"
76 #if GTEST_CAN_STREAM_RESULTS_
78 class StreamingListenerTest : public Test {
80 class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
82 // Sends a string to the socket.
83 virtual void Send(const std::string& message) { output_ += message; }
88 StreamingListenerTest()
89 : fake_sock_writer_(new FakeSocketWriter),
90 streamer_(fake_sock_writer_),
91 test_info_obj_("FooTest", "Bar", NULL, NULL,
92 CodeLocation(__FILE__, __LINE__), 0, NULL) {}
95 std::string* output() { return &(fake_sock_writer_->output_); }
97 FakeSocketWriter* const fake_sock_writer_;
98 StreamingListener streamer_;
100 TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test.
103 TEST_F(StreamingListenerTest, OnTestProgramEnd) {
105 streamer_.OnTestProgramEnd(unit_test_);
106 EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
109 TEST_F(StreamingListenerTest, OnTestIterationEnd) {
111 streamer_.OnTestIterationEnd(unit_test_, 42);
112 EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
115 TEST_F(StreamingListenerTest, OnTestCaseStart) {
117 streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", NULL, NULL));
118 EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
121 TEST_F(StreamingListenerTest, OnTestCaseEnd) {
123 streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", NULL, NULL));
124 EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
127 TEST_F(StreamingListenerTest, OnTestStart) {
129 streamer_.OnTestStart(test_info_obj_);
130 EXPECT_EQ("event=TestStart&name=Bar\n", *output());
133 TEST_F(StreamingListenerTest, OnTestEnd) {
135 streamer_.OnTestEnd(test_info_obj_);
136 EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
139 TEST_F(StreamingListenerTest, OnTestPartResult) {
141 streamer_.OnTestPartResult(TestPartResult(
142 TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
144 // Meta characters in the failure message should be properly escaped.
146 "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
150 #endif // GTEST_CAN_STREAM_RESULTS_
152 // Provides access to otherwise private parts of the TestEventListeners class
153 // that are needed to test it.
154 class TestEventListenersAccessor {
156 static TestEventListener* GetRepeater(TestEventListeners* listeners) {
157 return listeners->repeater();
160 static void SetDefaultResultPrinter(TestEventListeners* listeners,
161 TestEventListener* listener) {
162 listeners->SetDefaultResultPrinter(listener);
164 static void SetDefaultXmlGenerator(TestEventListeners* listeners,
165 TestEventListener* listener) {
166 listeners->SetDefaultXmlGenerator(listener);
169 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
170 return listeners.EventForwardingEnabled();
173 static void SuppressEventForwarding(TestEventListeners* listeners) {
174 listeners->SuppressEventForwarding();
178 class UnitTestRecordPropertyTestHelper : public Test {
180 UnitTestRecordPropertyTestHelper() {}
182 // Forwards to UnitTest::RecordProperty() to bypass access controls.
183 void UnitTestRecordProperty(const char* key, const std::string& value) {
184 unit_test_.RecordProperty(key, value);
190 } // namespace internal
191 } // namespace testing
193 using testing::AssertionFailure;
194 using testing::AssertionResult;
195 using testing::AssertionSuccess;
196 using testing::DoubleLE;
197 using testing::EmptyTestEventListener;
198 using testing::Environment;
199 using testing::FloatLE;
200 using testing::GTEST_FLAG(also_run_disabled_tests);
201 using testing::GTEST_FLAG(break_on_failure);
202 using testing::GTEST_FLAG(catch_exceptions);
203 using testing::GTEST_FLAG(color);
204 using testing::GTEST_FLAG(death_test_use_fork);
205 using testing::GTEST_FLAG(filter);
206 using testing::GTEST_FLAG(list_tests);
207 using testing::GTEST_FLAG(output);
208 using testing::GTEST_FLAG(print_time);
209 using testing::GTEST_FLAG(random_seed);
210 using testing::GTEST_FLAG(repeat);
211 using testing::GTEST_FLAG(show_internal_stack_frames);
212 using testing::GTEST_FLAG(shuffle);
213 using testing::GTEST_FLAG(stack_trace_depth);
214 using testing::GTEST_FLAG(stream_result_to);
215 using testing::GTEST_FLAG(throw_on_failure);
216 using testing::IsNotSubstring;
217 using testing::IsSubstring;
218 using testing::Message;
219 using testing::ScopedFakeTestPartResultReporter;
220 using testing::StaticAssertTypeEq;
222 using testing::TestCase;
223 using testing::TestEventListeners;
224 using testing::TestInfo;
225 using testing::TestPartResult;
226 using testing::TestPartResultArray;
227 using testing::TestProperty;
228 using testing::TestResult;
229 using testing::TimeInMillis;
230 using testing::UnitTest;
231 using testing::internal::AddReference;
232 using testing::internal::AlwaysFalse;
233 using testing::internal::AlwaysTrue;
234 using testing::internal::AppendUserMessage;
235 using testing::internal::ArrayAwareFind;
236 using testing::internal::ArrayEq;
237 using testing::internal::CodePointToUtf8;
238 using testing::internal::CompileAssertTypesEqual;
239 using testing::internal::CopyArray;
240 using testing::internal::CountIf;
241 using testing::internal::EqFailure;
242 using testing::internal::FloatingPoint;
243 using testing::internal::ForEach;
244 using testing::internal::FormatEpochTimeInMillisAsIso8601;
245 using testing::internal::FormatTimeInMillisAsSeconds;
246 using testing::internal::GTestFlagSaver;
247 using testing::internal::GetCurrentOsStackTraceExceptTop;
248 using testing::internal::GetElementOr;
249 using testing::internal::GetNextRandomSeed;
250 using testing::internal::GetRandomSeedFromFlag;
251 using testing::internal::GetTestTypeId;
252 using testing::internal::GetTimeInMillis;
253 using testing::internal::GetTypeId;
254 using testing::internal::GetUnitTestImpl;
255 using testing::internal::ImplicitlyConvertible;
256 using testing::internal::Int32;
257 using testing::internal::Int32FromEnvOrDie;
258 using testing::internal::IsAProtocolMessage;
259 using testing::internal::IsContainer;
260 using testing::internal::IsContainerTest;
261 using testing::internal::IsNotContainer;
262 using testing::internal::NativeArray;
263 using testing::internal::OsStackTraceGetter;
264 using testing::internal::OsStackTraceGetterInterface;
265 using testing::internal::ParseInt32Flag;
266 using testing::internal::RelationToSourceCopy;
267 using testing::internal::RelationToSourceReference;
268 using testing::internal::RemoveConst;
269 using testing::internal::RemoveReference;
270 using testing::internal::ShouldRunTestOnShard;
271 using testing::internal::ShouldShard;
272 using testing::internal::ShouldUseColor;
273 using testing::internal::Shuffle;
274 using testing::internal::ShuffleRange;
275 using testing::internal::SkipPrefix;
276 using testing::internal::StreamableToString;
277 using testing::internal::String;
278 using testing::internal::TestEventListenersAccessor;
279 using testing::internal::TestResultAccessor;
280 using testing::internal::UInt32;
281 using testing::internal::UnitTestImpl;
282 using testing::internal::WideStringToUtf8;
283 using testing::internal::edit_distance::CalculateOptimalEdits;
284 using testing::internal::edit_distance::CreateUnifiedDiff;
285 using testing::internal::edit_distance::EditType;
286 using testing::internal::kMaxRandomSeed;
287 using testing::internal::kTestTypeIdInGoogleTest;
288 using testing::kMaxStackTraceDepth;
290 #if GTEST_HAS_STREAM_REDIRECTION
291 using testing::internal::CaptureStdout;
292 using testing::internal::GetCapturedStdout;
295 #if GTEST_IS_THREADSAFE
296 using testing::internal::ThreadWithParam;
299 class TestingVector : public std::vector<int> {
302 ::std::ostream& operator<<(::std::ostream& os,
303 const TestingVector& vector) {
305 for (size_t i = 0; i < vector.size(); i++) {
306 os << vector[i] << " ";
312 // This line tests that we can define tests in an unnamed namespace.
315 TEST(GetRandomSeedFromFlagTest, HandlesZero) {
316 const int seed = GetRandomSeedFromFlag(0);
318 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
321 TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
322 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
323 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
324 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
325 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
326 GetRandomSeedFromFlag(kMaxRandomSeed));
329 TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
330 const int seed1 = GetRandomSeedFromFlag(-1);
332 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
334 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
336 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
339 TEST(GetNextRandomSeedTest, WorksForValidInput) {
340 EXPECT_EQ(2, GetNextRandomSeed(1));
341 EXPECT_EQ(3, GetNextRandomSeed(2));
342 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
343 GetNextRandomSeed(kMaxRandomSeed - 1));
344 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
346 // We deliberately don't test GetNextRandomSeed() with invalid
347 // inputs, as that requires death tests, which are expensive. This
348 // is fine as GetNextRandomSeed() is internal and has a
349 // straightforward definition.
352 static void ClearCurrentTestPartResults() {
353 TestResultAccessor::ClearTestPartResults(
354 GetUnitTestImpl()->current_test_result());
359 TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
360 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
361 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
364 class SubClassOfTest : public Test {};
365 class AnotherSubClassOfTest : public Test {};
367 TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
368 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
369 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
370 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
371 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
372 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
373 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
376 // Verifies that GetTestTypeId() returns the same value, no matter it
377 // is called from inside Google Test or outside of it.
378 TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
379 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
382 // Tests CanonicalizeForStdLibVersioning.
384 using ::testing::internal::CanonicalizeForStdLibVersioning;
386 TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) {
387 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind"));
388 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_"));
389 EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo"));
390 EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x"));
391 EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x"));
392 EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x"));
395 TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
396 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind"));
397 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_"));
399 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind"));
400 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_"));
402 EXPECT_EQ("std::bind",
403 CanonicalizeForStdLibVersioning("std::__google::bind"));
404 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_"));
407 // Tests FormatTimeInMillisAsSeconds().
409 TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
410 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
413 TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
414 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
415 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
416 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
417 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
418 EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
421 TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
422 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
423 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
424 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
425 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
426 EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
429 // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
430 // for particular dates below was verified in Python using
431 // datetime.datetime.fromutctimestamp(<timetamp>/1000).
433 // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
434 // have to set up a particular timezone to obtain predictable results.
435 class FormatEpochTimeInMillisAsIso8601Test : public Test {
437 // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
438 // 32 bits, even when 64-bit integer types are available. We have to
439 // force the constants to have a 64-bit type here.
440 static const TimeInMillis kMillisPerSec = 1000;
443 virtual void SetUp() {
446 GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
448 saved_tz_ = strdup(getenv("TZ"));
449 GTEST_DISABLE_MSC_DEPRECATED_POP_()
451 // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
452 // cannot use the local time zone because the function's output depends
454 SetTimeZone("UTC+00");
457 virtual void TearDown() {
458 SetTimeZone(saved_tz_);
459 free(const_cast<char*>(saved_tz_));
463 static void SetTimeZone(const char* time_zone) {
464 // tzset() distinguishes between the TZ variable being present and empty
465 // and not being present, so we have to consider the case of time_zone
467 #if _MSC_VER || GTEST_OS_WINDOWS_MINGW
468 // ...Unless it's MSVC, whose standard library's _putenv doesn't
469 // distinguish between an empty and a missing variable.
470 const std::string env_var =
471 std::string("TZ=") + (time_zone ? time_zone : "");
472 _putenv(env_var.c_str());
473 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
475 GTEST_DISABLE_MSC_WARNINGS_POP_()
478 setenv(("TZ"), time_zone, 1);
486 const char* saved_tz_;
489 const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
491 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
492 EXPECT_EQ("2011-10-31T18:52:42",
493 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
496 TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) {
498 "2011-10-31T18:52:42",
499 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
502 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
503 EXPECT_EQ("2011-09-03T05:07:02",
504 FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
507 TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
508 EXPECT_EQ("2011-09-28T17:08:22",
509 FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
512 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
513 EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0));
516 #if GTEST_CAN_COMPARE_NULL
519 // Silences warnings: "Condition is always true", "Unreachable code"
520 # pragma option push -w-ccc -w-rch
523 // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
525 TEST(NullLiteralTest, IsTrueForNullLiterals) {
526 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
527 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
528 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
529 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
532 // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
534 TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
535 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
536 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
537 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
538 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
542 // Restores warnings after previous "#pragma option push" suppressed them.
546 #endif // GTEST_CAN_COMPARE_NULL
548 // Tests CodePointToUtf8().
550 // Tests that the NUL character L'\0' is encoded correctly.
551 TEST(CodePointToUtf8Test, CanEncodeNul) {
552 EXPECT_EQ("", CodePointToUtf8(L'\0'));
555 // Tests that ASCII characters are encoded correctly.
556 TEST(CodePointToUtf8Test, CanEncodeAscii) {
557 EXPECT_EQ("a", CodePointToUtf8(L'a'));
558 EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
559 EXPECT_EQ("&", CodePointToUtf8(L'&'));
560 EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
563 // Tests that Unicode code-points that have 8 to 11 bits are encoded
564 // as 110xxxxx 10xxxxxx.
565 TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
566 // 000 1101 0011 => 110-00011 10-010011
567 EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
569 // 101 0111 0110 => 110-10101 10-110110
570 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
571 // in wide strings and wide chars. In order to accommodate them, we have to
572 // introduce such character constants as integers.
573 EXPECT_EQ("\xD5\xB6",
574 CodePointToUtf8(static_cast<wchar_t>(0x576)));
577 // Tests that Unicode code-points that have 12 to 16 bits are encoded
578 // as 1110xxxx 10xxxxxx 10xxxxxx.
579 TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
580 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
581 EXPECT_EQ("\xE0\xA3\x93",
582 CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
584 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
585 EXPECT_EQ("\xEC\x9D\x8D",
586 CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
589 #if !GTEST_WIDE_STRING_USES_UTF16_
590 // Tests in this group require a wchar_t to hold > 16 bits, and thus
591 // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
592 // 16-bit wide. This code may not compile on those systems.
594 // Tests that Unicode code-points that have 17 to 21 bits are encoded
595 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
596 TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
597 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
598 EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
600 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
601 EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
603 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
604 EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
607 // Tests that encoding an invalid code-point generates the expected result.
608 TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
609 EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
612 #endif // !GTEST_WIDE_STRING_USES_UTF16_
614 // Tests WideStringToUtf8().
616 // Tests that the NUL character L'\0' is encoded correctly.
617 TEST(WideStringToUtf8Test, CanEncodeNul) {
618 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
619 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
622 // Tests that ASCII strings are encoded correctly.
623 TEST(WideStringToUtf8Test, CanEncodeAscii) {
624 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
625 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
626 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
627 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
630 // Tests that Unicode code-points that have 8 to 11 bits are encoded
631 // as 110xxxxx 10xxxxxx.
632 TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
633 // 000 1101 0011 => 110-00011 10-010011
634 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
635 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
637 // 101 0111 0110 => 110-10101 10-110110
638 const wchar_t s[] = { 0x576, '\0' };
639 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
640 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
643 // Tests that Unicode code-points that have 12 to 16 bits are encoded
644 // as 1110xxxx 10xxxxxx 10xxxxxx.
645 TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
646 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
647 const wchar_t s1[] = { 0x8D3, '\0' };
648 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
649 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
651 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
652 const wchar_t s2[] = { 0xC74D, '\0' };
653 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
654 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
657 // Tests that the conversion stops when the function encounters \0 character.
658 TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
659 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
662 // Tests that the conversion stops when the function reaches the limit
663 // specified by the 'length' parameter.
664 TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
665 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
668 #if !GTEST_WIDE_STRING_USES_UTF16_
669 // Tests that Unicode code-points that have 17 to 21 bits are encoded
670 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
671 // on the systems using UTF-16 encoding.
672 TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
673 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
674 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
675 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
677 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
678 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
679 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
682 // Tests that encoding an invalid code-point generates the expected result.
683 TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
684 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
685 WideStringToUtf8(L"\xABCDFF", -1).c_str());
687 #else // !GTEST_WIDE_STRING_USES_UTF16_
688 // Tests that surrogate pairs are encoded correctly on the systems using
689 // UTF-16 encoding in the wide strings.
690 TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
691 const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
692 EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
695 // Tests that encoding an invalid UTF-16 surrogate pair
696 // generates the expected result.
697 TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
698 // Leading surrogate is at the end of the string.
699 const wchar_t s1[] = { 0xD800, '\0' };
700 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
701 // Leading surrogate is not followed by the trailing surrogate.
702 const wchar_t s2[] = { 0xD800, 'M', '\0' };
703 EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
704 // Trailing surrogate appearas without a leading surrogate.
705 const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
706 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
708 #endif // !GTEST_WIDE_STRING_USES_UTF16_
710 // Tests that codepoint concatenation works correctly.
711 #if !GTEST_WIDE_STRING_USES_UTF16_
712 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
713 const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
721 WideStringToUtf8(s, -1).c_str());
724 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
725 const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
727 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
728 WideStringToUtf8(s, -1).c_str());
730 #endif // !GTEST_WIDE_STRING_USES_UTF16_
732 // Tests the Random class.
734 TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
735 testing::internal::Random random(42);
736 EXPECT_DEATH_IF_SUPPORTED(
738 "Cannot generate a number in the range \\[0, 0\\)");
739 EXPECT_DEATH_IF_SUPPORTED(
740 random.Generate(testing::internal::Random::kMaxRange + 1),
741 "Generation of a number in \\[0, 2147483649\\) was requested, "
742 "but this can only generate numbers in \\[0, 2147483648\\)");
745 TEST(RandomTest, GeneratesNumbersWithinRange) {
746 const UInt32 kRange = 10000;
747 testing::internal::Random random(12345);
748 for (int i = 0; i < 10; i++) {
749 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
752 testing::internal::Random random2(testing::internal::Random::kMaxRange);
753 for (int i = 0; i < 10; i++) {
754 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
758 TEST(RandomTest, RepeatsWhenReseeded) {
759 const int kSeed = 123;
760 const int kArraySize = 10;
761 const UInt32 kRange = 10000;
762 UInt32 values[kArraySize];
764 testing::internal::Random random(kSeed);
765 for (int i = 0; i < kArraySize; i++) {
766 values[i] = random.Generate(kRange);
769 random.Reseed(kSeed);
770 for (int i = 0; i < kArraySize; i++) {
771 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
775 // Tests STL container utilities.
779 static bool IsPositive(int n) { return n > 0; }
781 TEST(ContainerUtilityTest, CountIf) {
783 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
787 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
792 EXPECT_EQ(2, CountIf(v, IsPositive));
797 static int g_sum = 0;
798 static void Accumulate(int n) { g_sum += n; }
800 TEST(ContainerUtilityTest, ForEach) {
803 ForEach(v, Accumulate);
804 EXPECT_EQ(0, g_sum); // Works for an empty container;
808 ForEach(v, Accumulate);
809 EXPECT_EQ(1, g_sum); // Works for a container with one element.
814 ForEach(v, Accumulate);
815 EXPECT_EQ(321, g_sum);
818 // Tests GetElementOr().
819 TEST(ContainerUtilityTest, GetElementOr) {
821 EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
825 EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
826 EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
827 EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
828 EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
831 TEST(ContainerUtilityDeathTest, ShuffleRange) {
836 testing::internal::Random random(1);
838 EXPECT_DEATH_IF_SUPPORTED(
839 ShuffleRange(&random, -1, 1, &a),
840 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
841 EXPECT_DEATH_IF_SUPPORTED(
842 ShuffleRange(&random, 4, 4, &a),
843 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
844 EXPECT_DEATH_IF_SUPPORTED(
845 ShuffleRange(&random, 3, 2, &a),
846 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
847 EXPECT_DEATH_IF_SUPPORTED(
848 ShuffleRange(&random, 3, 4, &a),
849 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
852 class VectorShuffleTest : public Test {
854 static const int kVectorSize = 20;
856 VectorShuffleTest() : random_(1) {
857 for (int i = 0; i < kVectorSize; i++) {
858 vector_.push_back(i);
862 static bool VectorIsCorrupt(const TestingVector& vector) {
863 if (kVectorSize != static_cast<int>(vector.size())) {
867 bool found_in_vector[kVectorSize] = { false };
868 for (size_t i = 0; i < vector.size(); i++) {
869 const int e = vector[i];
870 if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
873 found_in_vector[e] = true;
876 // Vector size is correct, elements' range is correct, no
877 // duplicate elements. Therefore no corruption has occurred.
881 static bool VectorIsNotCorrupt(const TestingVector& vector) {
882 return !VectorIsCorrupt(vector);
885 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
886 for (int i = begin; i < end; i++) {
887 if (i != vector[i]) {
894 static bool RangeIsUnshuffled(
895 const TestingVector& vector, int begin, int end) {
896 return !RangeIsShuffled(vector, begin, end);
899 static bool VectorIsShuffled(const TestingVector& vector) {
900 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
903 static bool VectorIsUnshuffled(const TestingVector& vector) {
904 return !VectorIsShuffled(vector);
907 testing::internal::Random random_;
908 TestingVector vector_;
909 }; // class VectorShuffleTest
911 const int VectorShuffleTest::kVectorSize;
913 TEST_F(VectorShuffleTest, HandlesEmptyRange) {
914 // Tests an empty range at the beginning...
915 ShuffleRange(&random_, 0, 0, &vector_);
916 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
917 ASSERT_PRED1(VectorIsUnshuffled, vector_);
919 // ...in the middle...
920 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
921 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
922 ASSERT_PRED1(VectorIsUnshuffled, vector_);
925 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
926 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
927 ASSERT_PRED1(VectorIsUnshuffled, vector_);
929 // ...and past the end.
930 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
931 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
932 ASSERT_PRED1(VectorIsUnshuffled, vector_);
935 TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
936 // Tests a size one range at the beginning...
937 ShuffleRange(&random_, 0, 1, &vector_);
938 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
939 ASSERT_PRED1(VectorIsUnshuffled, vector_);
941 // ...in the middle...
942 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
943 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
944 ASSERT_PRED1(VectorIsUnshuffled, vector_);
946 // ...and at the end.
947 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
948 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
949 ASSERT_PRED1(VectorIsUnshuffled, vector_);
952 // Because we use our own random number generator and a fixed seed,
953 // we can guarantee that the following "random" tests will succeed.
955 TEST_F(VectorShuffleTest, ShufflesEntireVector) {
956 Shuffle(&random_, &vector_);
957 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
958 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
960 // Tests the first and last elements in particular to ensure that
961 // there are no off-by-one problems in our shuffle algorithm.
962 EXPECT_NE(0, vector_[0]);
963 EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
966 TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
967 const int kRangeSize = kVectorSize/2;
969 ShuffleRange(&random_, 0, kRangeSize, &vector_);
971 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
972 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
973 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
976 TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
977 const int kRangeSize = kVectorSize / 2;
978 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
980 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
981 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
982 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
985 TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
986 int kRangeSize = kVectorSize/3;
987 ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
989 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
990 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
991 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
992 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
995 TEST_F(VectorShuffleTest, ShufflesRepeatably) {
996 TestingVector vector2;
997 for (int i = 0; i < kVectorSize; i++) {
998 vector2.push_back(i);
1001 random_.Reseed(1234);
1002 Shuffle(&random_, &vector_);
1003 random_.Reseed(1234);
1004 Shuffle(&random_, &vector2);
1006 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1007 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
1009 for (int i = 0; i < kVectorSize; i++) {
1010 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
1014 // Tests the size of the AssertHelper class.
1016 TEST(AssertHelperTest, AssertHelperIsSmall) {
1017 // To avoid breaking clients that use lots of assertions in one
1018 // function, we cannot grow the size of AssertHelper.
1019 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
1022 // Tests String::EndsWithCaseInsensitive().
1023 TEST(StringTest, EndsWithCaseInsensitive) {
1024 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
1025 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
1026 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
1027 EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
1029 EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
1030 EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
1031 EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
1034 // C++Builder's preprocessor is buggy; it fails to expand macros that
1035 // appear in macro parameters after wide char literals. Provide an alias
1036 // for NULL as a workaround.
1037 static const wchar_t* const kNull = NULL;
1039 // Tests String::CaseInsensitiveWideCStringEquals
1040 TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1041 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
1042 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1043 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1044 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1045 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
1046 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1047 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1048 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1051 #if GTEST_OS_WINDOWS
1053 // Tests String::ShowWideCString().
1054 TEST(StringTest, ShowWideCString) {
1055 EXPECT_STREQ("(null)",
1056 String::ShowWideCString(NULL).c_str());
1057 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1058 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1061 # if GTEST_OS_WINDOWS_MOBILE
1062 TEST(StringTest, AnsiAndUtf16Null) {
1063 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1064 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1067 TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1068 const char* ansi = String::Utf16ToAnsi(L"str");
1069 EXPECT_STREQ("str", ansi);
1071 const WCHAR* utf16 = String::AnsiToUtf16("str");
1072 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
1076 TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1077 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1078 EXPECT_STREQ(".:\\ \"*?", ansi);
1080 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
1081 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
1084 # endif // GTEST_OS_WINDOWS_MOBILE
1086 #endif // GTEST_OS_WINDOWS
1088 // Tests TestProperty construction.
1089 TEST(TestPropertyTest, StringValue) {
1090 TestProperty property("key", "1");
1091 EXPECT_STREQ("key", property.key());
1092 EXPECT_STREQ("1", property.value());
1095 // Tests TestProperty replacing a value.
1096 TEST(TestPropertyTest, ReplaceStringValue) {
1097 TestProperty property("key", "1");
1098 EXPECT_STREQ("1", property.value());
1099 property.SetValue("2");
1100 EXPECT_STREQ("2", property.value());
1103 // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1104 // functions (i.e. their definitions cannot be inlined at the call
1105 // sites), or C++Builder won't compile the code.
1106 static void AddFatalFailure() {
1107 FAIL() << "Expected fatal failure.";
1110 static void AddNonfatalFailure() {
1111 ADD_FAILURE() << "Expected non-fatal failure.";
1114 class ScopedFakeTestPartResultReporterTest : public Test {
1115 public: // Must be public and not protected due to a bug in g++ 3.4.2.
1120 static void AddFailure(FailureMode failure) {
1121 if (failure == FATAL_FAILURE) {
1124 AddNonfatalFailure();
1129 // Tests that ScopedFakeTestPartResultReporter intercepts test
1131 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
1132 TestPartResultArray results;
1134 ScopedFakeTestPartResultReporter reporter(
1135 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1137 AddFailure(NONFATAL_FAILURE);
1138 AddFailure(FATAL_FAILURE);
1141 EXPECT_EQ(2, results.size());
1142 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1143 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1146 TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1147 TestPartResultArray results;
1149 // Tests, that the deprecated constructor still works.
1150 ScopedFakeTestPartResultReporter reporter(&results);
1151 AddFailure(NONFATAL_FAILURE);
1153 EXPECT_EQ(1, results.size());
1156 #if GTEST_IS_THREADSAFE
1158 class ScopedFakeTestPartResultReporterWithThreadsTest
1159 : public ScopedFakeTestPartResultReporterTest {
1161 static void AddFailureInOtherThread(FailureMode failure) {
1162 ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
1167 TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1168 InterceptsTestFailuresInAllThreads) {
1169 TestPartResultArray results;
1171 ScopedFakeTestPartResultReporter reporter(
1172 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1173 AddFailure(NONFATAL_FAILURE);
1174 AddFailure(FATAL_FAILURE);
1175 AddFailureInOtherThread(NONFATAL_FAILURE);
1176 AddFailureInOtherThread(FATAL_FAILURE);
1179 EXPECT_EQ(4, results.size());
1180 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1181 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1182 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1183 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1186 #endif // GTEST_IS_THREADSAFE
1188 // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1189 // work even if the failure is generated in a called function rather than
1190 // the current context.
1192 typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
1194 TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1195 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
1198 #if GTEST_HAS_GLOBAL_STRING
1199 TEST_F(ExpectFatalFailureTest, AcceptsStringObject) {
1200 EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure."));
1204 TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1205 EXPECT_FATAL_FAILURE(AddFatalFailure(),
1206 ::std::string("Expected fatal failure."));
1209 TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1210 // We have another test below to verify that the macro catches fatal
1211 // failures generated on another thread.
1212 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
1213 "Expected fatal failure.");
1217 // Silences warnings: "Condition is always true"
1218 # pragma option push -w-ccc
1221 // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1222 // function even when the statement in it contains ASSERT_*.
1224 int NonVoidFunction() {
1225 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1226 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1230 TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1234 // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1235 // current function even though 'statement' generates a fatal failure.
1237 void DoesNotAbortHelper(bool* aborted) {
1238 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1239 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1245 // Restores warnings after previous "#pragma option push" suppressed them.
1249 TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1250 bool aborted = true;
1251 DoesNotAbortHelper(&aborted);
1252 EXPECT_FALSE(aborted);
1255 // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1256 // statement that contains a macro which expands to code containing an
1257 // unprotected comma.
1259 static int global_var = 0;
1260 #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1262 TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1263 #ifndef __BORLANDC__
1264 // ICE's in C++Builder.
1265 EXPECT_FATAL_FAILURE({
1266 GTEST_USE_UNPROTECTED_COMMA_;
1271 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1272 GTEST_USE_UNPROTECTED_COMMA_;
1277 // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1279 typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1281 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1282 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1283 "Expected non-fatal failure.");
1286 #if GTEST_HAS_GLOBAL_STRING
1287 TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) {
1288 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1289 ::string("Expected non-fatal failure."));
1293 TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1294 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1295 ::std::string("Expected non-fatal failure."));
1298 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1299 // We have another test below to verify that the macro catches
1300 // non-fatal failures generated on another thread.
1301 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
1302 "Expected non-fatal failure.");
1305 // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1306 // statement that contains a macro which expands to code containing an
1307 // unprotected comma.
1308 TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1309 EXPECT_NONFATAL_FAILURE({
1310 GTEST_USE_UNPROTECTED_COMMA_;
1311 AddNonfatalFailure();
1314 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1315 GTEST_USE_UNPROTECTED_COMMA_;
1316 AddNonfatalFailure();
1320 #if GTEST_IS_THREADSAFE
1322 typedef ScopedFakeTestPartResultReporterWithThreadsTest
1323 ExpectFailureWithThreadsTest;
1325 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1326 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1327 "Expected fatal failure.");
1330 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1331 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1332 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1335 #endif // GTEST_IS_THREADSAFE
1337 // Tests the TestProperty class.
1339 TEST(TestPropertyTest, ConstructorWorks) {
1340 const TestProperty property("key", "value");
1341 EXPECT_STREQ("key", property.key());
1342 EXPECT_STREQ("value", property.value());
1345 TEST(TestPropertyTest, SetValue) {
1346 TestProperty property("key", "value_1");
1347 EXPECT_STREQ("key", property.key());
1348 property.SetValue("value_2");
1349 EXPECT_STREQ("key", property.key());
1350 EXPECT_STREQ("value_2", property.value());
1353 // Tests the TestResult class
1355 // The test fixture for testing TestResult.
1356 class TestResultTest : public Test {
1358 typedef std::vector<TestPartResult> TPRVector;
1360 // We make use of 2 TestPartResult objects,
1361 TestPartResult * pr1, * pr2;
1363 // ... and 3 TestResult objects.
1364 TestResult * r0, * r1, * r2;
1366 virtual void SetUp() {
1367 // pr1 is for success.
1368 pr1 = new TestPartResult(TestPartResult::kSuccess,
1373 // pr2 is for fatal failure.
1374 pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1376 -1, // This line number means "unknown"
1379 // Creates the TestResult objects.
1380 r0 = new TestResult();
1381 r1 = new TestResult();
1382 r2 = new TestResult();
1384 // In order to test TestResult, we need to modify its internal
1385 // state, in particular the TestPartResult vector it holds.
1386 // test_part_results() returns a const reference to this vector.
1387 // We cast it to a non-const object s.t. it can be modified
1388 TPRVector* results1 = const_cast<TPRVector*>(
1389 &TestResultAccessor::test_part_results(*r1));
1390 TPRVector* results2 = const_cast<TPRVector*>(
1391 &TestResultAccessor::test_part_results(*r2));
1393 // r0 is an empty TestResult.
1395 // r1 contains a single SUCCESS TestPartResult.
1396 results1->push_back(*pr1);
1398 // r2 contains a SUCCESS, and a FAILURE.
1399 results2->push_back(*pr1);
1400 results2->push_back(*pr2);
1403 virtual void TearDown() {
1412 // Helper that compares two TestPartResults.
1413 static void CompareTestPartResult(const TestPartResult& expected,
1414 const TestPartResult& actual) {
1415 EXPECT_EQ(expected.type(), actual.type());
1416 EXPECT_STREQ(expected.file_name(), actual.file_name());
1417 EXPECT_EQ(expected.line_number(), actual.line_number());
1418 EXPECT_STREQ(expected.summary(), actual.summary());
1419 EXPECT_STREQ(expected.message(), actual.message());
1420 EXPECT_EQ(expected.passed(), actual.passed());
1421 EXPECT_EQ(expected.failed(), actual.failed());
1422 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1423 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
1427 // Tests TestResult::total_part_count().
1428 TEST_F(TestResultTest, total_part_count) {
1429 ASSERT_EQ(0, r0->total_part_count());
1430 ASSERT_EQ(1, r1->total_part_count());
1431 ASSERT_EQ(2, r2->total_part_count());
1434 // Tests TestResult::Passed().
1435 TEST_F(TestResultTest, Passed) {
1436 ASSERT_TRUE(r0->Passed());
1437 ASSERT_TRUE(r1->Passed());
1438 ASSERT_FALSE(r2->Passed());
1441 // Tests TestResult::Failed().
1442 TEST_F(TestResultTest, Failed) {
1443 ASSERT_FALSE(r0->Failed());
1444 ASSERT_FALSE(r1->Failed());
1445 ASSERT_TRUE(r2->Failed());
1448 // Tests TestResult::GetTestPartResult().
1450 typedef TestResultTest TestResultDeathTest;
1452 TEST_F(TestResultDeathTest, GetTestPartResult) {
1453 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1454 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1455 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1456 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
1459 // Tests TestResult has no properties when none are added.
1460 TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1461 TestResult test_result;
1462 ASSERT_EQ(0, test_result.test_property_count());
1465 // Tests TestResult has the expected property when added.
1466 TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1467 TestResult test_result;
1468 TestProperty property("key_1", "1");
1469 TestResultAccessor::RecordProperty(&test_result, "testcase", property);
1470 ASSERT_EQ(1, test_result.test_property_count());
1471 const TestProperty& actual_property = test_result.GetTestProperty(0);
1472 EXPECT_STREQ("key_1", actual_property.key());
1473 EXPECT_STREQ("1", actual_property.value());
1476 // Tests TestResult has multiple properties when added.
1477 TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1478 TestResult test_result;
1479 TestProperty property_1("key_1", "1");
1480 TestProperty property_2("key_2", "2");
1481 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1482 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1483 ASSERT_EQ(2, test_result.test_property_count());
1484 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1485 EXPECT_STREQ("key_1", actual_property_1.key());
1486 EXPECT_STREQ("1", actual_property_1.value());
1488 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1489 EXPECT_STREQ("key_2", actual_property_2.key());
1490 EXPECT_STREQ("2", actual_property_2.value());
1493 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
1494 TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1495 TestResult test_result;
1496 TestProperty property_1_1("key_1", "1");
1497 TestProperty property_2_1("key_2", "2");
1498 TestProperty property_1_2("key_1", "12");
1499 TestProperty property_2_2("key_2", "22");
1500 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
1501 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
1502 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
1503 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
1505 ASSERT_EQ(2, test_result.test_property_count());
1506 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1507 EXPECT_STREQ("key_1", actual_property_1.key());
1508 EXPECT_STREQ("12", actual_property_1.value());
1510 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1511 EXPECT_STREQ("key_2", actual_property_2.key());
1512 EXPECT_STREQ("22", actual_property_2.value());
1515 // Tests TestResult::GetTestProperty().
1516 TEST(TestResultPropertyTest, GetTestProperty) {
1517 TestResult test_result;
1518 TestProperty property_1("key_1", "1");
1519 TestProperty property_2("key_2", "2");
1520 TestProperty property_3("key_3", "3");
1521 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1522 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1523 TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
1525 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1526 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1527 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
1529 EXPECT_STREQ("key_1", fetched_property_1.key());
1530 EXPECT_STREQ("1", fetched_property_1.value());
1532 EXPECT_STREQ("key_2", fetched_property_2.key());
1533 EXPECT_STREQ("2", fetched_property_2.value());
1535 EXPECT_STREQ("key_3", fetched_property_3.key());
1536 EXPECT_STREQ("3", fetched_property_3.value());
1538 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1539 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
1542 // Tests the Test class.
1544 // It's difficult to test every public method of this class (we are
1545 // already stretching the limit of Google Test by using it to test itself!).
1546 // Fortunately, we don't have to do that, as we are already testing
1547 // the functionalities of the Test class extensively by using Google Test
1550 // Therefore, this section only contains one test.
1552 // Tests that GTestFlagSaver works on Windows and Mac.
1554 class GTestFlagSaverTest : public Test {
1556 // Saves the Google Test flags such that we can restore them later, and
1557 // then sets them to their default values. This will be called
1558 // before the first test in this test case is run.
1559 static void SetUpTestCase() {
1560 saver_ = new GTestFlagSaver;
1562 GTEST_FLAG(also_run_disabled_tests) = false;
1563 GTEST_FLAG(break_on_failure) = false;
1564 GTEST_FLAG(catch_exceptions) = false;
1565 GTEST_FLAG(death_test_use_fork) = false;
1566 GTEST_FLAG(color) = "auto";
1567 GTEST_FLAG(filter) = "";
1568 GTEST_FLAG(list_tests) = false;
1569 GTEST_FLAG(output) = "";
1570 GTEST_FLAG(print_time) = true;
1571 GTEST_FLAG(random_seed) = 0;
1572 GTEST_FLAG(repeat) = 1;
1573 GTEST_FLAG(shuffle) = false;
1574 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
1575 GTEST_FLAG(stream_result_to) = "";
1576 GTEST_FLAG(throw_on_failure) = false;
1579 // Restores the Google Test flags that the tests have modified. This will
1580 // be called after the last test in this test case is run.
1581 static void TearDownTestCase() {
1586 // Verifies that the Google Test flags have their default values, and then
1587 // modifies each of them.
1588 void VerifyAndModifyFlags() {
1589 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
1590 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1591 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1592 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
1593 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
1594 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1595 EXPECT_FALSE(GTEST_FLAG(list_tests));
1596 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
1597 EXPECT_TRUE(GTEST_FLAG(print_time));
1598 EXPECT_EQ(0, GTEST_FLAG(random_seed));
1599 EXPECT_EQ(1, GTEST_FLAG(repeat));
1600 EXPECT_FALSE(GTEST_FLAG(shuffle));
1601 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
1602 EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
1603 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
1605 GTEST_FLAG(also_run_disabled_tests) = true;
1606 GTEST_FLAG(break_on_failure) = true;
1607 GTEST_FLAG(catch_exceptions) = true;
1608 GTEST_FLAG(color) = "no";
1609 GTEST_FLAG(death_test_use_fork) = true;
1610 GTEST_FLAG(filter) = "abc";
1611 GTEST_FLAG(list_tests) = true;
1612 GTEST_FLAG(output) = "xml:foo.xml";
1613 GTEST_FLAG(print_time) = false;
1614 GTEST_FLAG(random_seed) = 1;
1615 GTEST_FLAG(repeat) = 100;
1616 GTEST_FLAG(shuffle) = true;
1617 GTEST_FLAG(stack_trace_depth) = 1;
1618 GTEST_FLAG(stream_result_to) = "localhost:1234";
1619 GTEST_FLAG(throw_on_failure) = true;
1623 // For saving Google Test flags during this test case.
1624 static GTestFlagSaver* saver_;
1627 GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
1629 // Google Test doesn't guarantee the order of tests. The following two
1630 // tests are designed to work regardless of their order.
1632 // Modifies the Google Test flags in the test body.
1633 TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1634 VerifyAndModifyFlags();
1637 // Verifies that the Google Test flags in the body of the previous test were
1638 // restored to their original values.
1639 TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1640 VerifyAndModifyFlags();
1643 // Sets an environment variable with the given name to the given
1644 // value. If the value argument is "", unsets the environment
1645 // variable. The caller must ensure that both arguments are not NULL.
1646 static void SetEnv(const char* name, const char* value) {
1647 #if GTEST_OS_WINDOWS_MOBILE
1648 // Environment variables are not supported on Windows CE.
1650 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1651 // C++Builder's putenv only stores a pointer to its parameter; we have to
1652 // ensure that the string remains valid as long as it might be needed.
1653 // We use an std::map to do so.
1654 static std::map<std::string, std::string*> added_env;
1656 // Because putenv stores a pointer to the string buffer, we can't delete the
1657 // previous string (if present) until after it's replaced.
1658 std::string *prev_env = NULL;
1659 if (added_env.find(name) != added_env.end()) {
1660 prev_env = added_env[name];
1662 added_env[name] = new std::string(
1663 (Message() << name << "=" << value).GetString());
1665 // The standard signature of putenv accepts a 'char*' argument. Other
1666 // implementations, like C++Builder's, accept a 'const char*'.
1667 // We cast away the 'const' since that would work for both variants.
1668 putenv(const_cast<char*>(added_env[name]->c_str()));
1670 #elif GTEST_OS_WINDOWS // If we are on Windows proper.
1671 _putenv((Message() << name << "=" << value).GetString().c_str());
1673 if (*value == '\0') {
1676 setenv(name, value, 1);
1678 #endif // GTEST_OS_WINDOWS_MOBILE
1681 #if !GTEST_OS_WINDOWS_MOBILE
1682 // Environment variables are not supported on Windows CE.
1684 using testing::internal::Int32FromGTestEnv;
1686 // Tests Int32FromGTestEnv().
1688 // Tests that Int32FromGTestEnv() returns the default value when the
1689 // environment variable is not set.
1690 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1691 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1692 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1695 # if !defined(GTEST_GET_INT32_FROM_ENV_)
1697 // Tests that Int32FromGTestEnv() returns the default value when the
1698 // environment variable overflows as an Int32.
1699 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1700 printf("(expecting 2 warnings)\n");
1702 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1703 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1705 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1706 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1709 // Tests that Int32FromGTestEnv() returns the default value when the
1710 // environment variable does not represent a valid decimal integer.
1711 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1712 printf("(expecting 2 warnings)\n");
1714 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1715 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1717 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1718 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1721 # endif // !defined(GTEST_GET_INT32_FROM_ENV_)
1723 // Tests that Int32FromGTestEnv() parses and returns the value of the
1724 // environment variable when it represents a valid decimal integer in
1725 // the range of an Int32.
1726 TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1727 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1728 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1730 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1731 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1733 #endif // !GTEST_OS_WINDOWS_MOBILE
1735 // Tests ParseInt32Flag().
1737 // Tests that ParseInt32Flag() returns false and doesn't change the
1738 // output value when the flag has wrong format
1739 TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1741 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1742 EXPECT_EQ(123, value);
1744 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1745 EXPECT_EQ(123, value);
1748 // Tests that ParseInt32Flag() returns false and doesn't change the
1749 // output value when the flag overflows as an Int32.
1750 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1751 printf("(expecting 2 warnings)\n");
1754 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1755 EXPECT_EQ(123, value);
1757 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1758 EXPECT_EQ(123, value);
1761 // Tests that ParseInt32Flag() returns false and doesn't change the
1762 // output value when the flag does not represent a valid decimal
1764 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1765 printf("(expecting 2 warnings)\n");
1768 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1769 EXPECT_EQ(123, value);
1771 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1772 EXPECT_EQ(123, value);
1775 // Tests that ParseInt32Flag() parses the value of the flag and
1776 // returns true when the flag represents a valid decimal integer in
1777 // the range of an Int32.
1778 TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1780 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1781 EXPECT_EQ(456, value);
1783 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1785 EXPECT_EQ(-789, value);
1788 // Tests that Int32FromEnvOrDie() parses the value of the var or
1789 // returns the correct default.
1790 // Environment variables are not supported on Windows CE.
1791 #if !GTEST_OS_WINDOWS_MOBILE
1792 TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1793 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1794 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1795 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1796 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1797 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1799 #endif // !GTEST_OS_WINDOWS_MOBILE
1801 // Tests that Int32FromEnvOrDie() aborts with an error message
1802 // if the variable is not an Int32.
1803 TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1804 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1805 EXPECT_DEATH_IF_SUPPORTED(
1806 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1810 // Tests that Int32FromEnvOrDie() aborts with an error message
1811 // if the variable cannot be represented by an Int32.
1812 TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1813 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1814 EXPECT_DEATH_IF_SUPPORTED(
1815 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1819 // Tests that ShouldRunTestOnShard() selects all tests
1820 // where there is 1 shard.
1821 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1822 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1823 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1824 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1825 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1826 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1829 class ShouldShardTest : public testing::Test {
1831 virtual void SetUp() {
1832 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1833 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1836 virtual void TearDown() {
1837 SetEnv(index_var_, "");
1838 SetEnv(total_var_, "");
1841 const char* index_var_;
1842 const char* total_var_;
1845 // Tests that sharding is disabled if neither of the environment variables
1847 TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1848 SetEnv(index_var_, "");
1849 SetEnv(total_var_, "");
1851 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1852 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1855 // Tests that sharding is not enabled if total_shards == 1.
1856 TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1857 SetEnv(index_var_, "0");
1858 SetEnv(total_var_, "1");
1859 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1860 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1863 // Tests that sharding is enabled if total_shards > 1 and
1864 // we are not in a death test subprocess.
1865 // Environment variables are not supported on Windows CE.
1866 #if !GTEST_OS_WINDOWS_MOBILE
1867 TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1868 SetEnv(index_var_, "4");
1869 SetEnv(total_var_, "22");
1870 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1871 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1873 SetEnv(index_var_, "8");
1874 SetEnv(total_var_, "9");
1875 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1876 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1878 SetEnv(index_var_, "0");
1879 SetEnv(total_var_, "9");
1880 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1881 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1883 #endif // !GTEST_OS_WINDOWS_MOBILE
1885 // Tests that we exit in error if the sharding values are not valid.
1887 typedef ShouldShardTest ShouldShardDeathTest;
1889 TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
1890 SetEnv(index_var_, "4");
1891 SetEnv(total_var_, "4");
1892 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1894 SetEnv(index_var_, "4");
1895 SetEnv(total_var_, "-2");
1896 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1898 SetEnv(index_var_, "5");
1899 SetEnv(total_var_, "");
1900 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1902 SetEnv(index_var_, "");
1903 SetEnv(total_var_, "5");
1904 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1907 // Tests that ShouldRunTestOnShard is a partition when 5
1909 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1910 // Choose an arbitrary number of tests and shards.
1911 const int num_tests = 17;
1912 const int num_shards = 5;
1914 // Check partitioning: each test should be on exactly 1 shard.
1915 for (int test_id = 0; test_id < num_tests; test_id++) {
1916 int prev_selected_shard_index = -1;
1917 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1918 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1919 if (prev_selected_shard_index < 0) {
1920 prev_selected_shard_index = shard_index;
1922 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1923 << shard_index << " are both selected to run test " << test_id;
1929 // Check balance: This is not required by the sharding protocol, but is a
1930 // desirable property for performance.
1931 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1932 int num_tests_on_shard = 0;
1933 for (int test_id = 0; test_id < num_tests; test_id++) {
1934 num_tests_on_shard +=
1935 ShouldRunTestOnShard(num_shards, shard_index, test_id);
1937 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1941 // For the same reason we are not explicitly testing everything in the
1942 // Test class, there are no separate tests for the following classes
1943 // (except for some trivial cases):
1945 // TestCase, UnitTest, UnitTestResultPrinter.
1947 // Similarly, there are no separate tests for the following macros:
1949 // TEST, TEST_F, RUN_ALL_TESTS
1951 TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1952 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
1953 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1956 TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
1957 EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
1958 EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
1961 // When a property using a reserved key is supplied to this function, it
1962 // tests that a non-fatal failure is added, a fatal failure is not added,
1963 // and that the property is not recorded.
1964 void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1965 const TestResult& test_result, const char* key) {
1966 EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
1967 ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
1968 << "' recorded unexpectedly.";
1971 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
1973 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
1974 ASSERT_TRUE(test_info != NULL);
1975 ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
1979 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1981 const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
1982 ASSERT_TRUE(test_case != NULL);
1983 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1984 test_case->ad_hoc_test_result(), key);
1987 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
1989 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1990 UnitTest::GetInstance()->ad_hoc_test_result(), key);
1993 // Tests that property recording functions in UnitTest outside of tests
1994 // functions correcly. Creating a separate instance of UnitTest ensures it
1995 // is in a state similar to the UnitTest's singleton's between tests.
1996 class UnitTestRecordPropertyTest :
1997 public testing::internal::UnitTestRecordPropertyTestHelper {
1999 static void SetUpTestCase() {
2000 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
2002 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
2004 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
2006 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
2008 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
2010 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
2013 Test::RecordProperty("test_case_key_1", "1");
2014 const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
2015 ASSERT_TRUE(test_case != NULL);
2017 ASSERT_EQ(1, test_case->ad_hoc_test_result().test_property_count());
2018 EXPECT_STREQ("test_case_key_1",
2019 test_case->ad_hoc_test_result().GetTestProperty(0).key());
2021 test_case->ad_hoc_test_result().GetTestProperty(0).value());
2025 // Tests TestResult has the expected property when added.
2026 TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
2027 UnitTestRecordProperty("key_1", "1");
2029 ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
2031 EXPECT_STREQ("key_1",
2032 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2034 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2037 // Tests TestResult has multiple properties when added.
2038 TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
2039 UnitTestRecordProperty("key_1", "1");
2040 UnitTestRecordProperty("key_2", "2");
2042 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2044 EXPECT_STREQ("key_1",
2045 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2046 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2048 EXPECT_STREQ("key_2",
2049 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2050 EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2053 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
2054 TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
2055 UnitTestRecordProperty("key_1", "1");
2056 UnitTestRecordProperty("key_2", "2");
2057 UnitTestRecordProperty("key_1", "12");
2058 UnitTestRecordProperty("key_2", "22");
2060 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2062 EXPECT_STREQ("key_1",
2063 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2065 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2067 EXPECT_STREQ("key_2",
2068 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2070 unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2073 TEST_F(UnitTestRecordPropertyTest,
2074 AddFailureInsideTestsWhenUsingTestCaseReservedKeys) {
2075 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2077 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2079 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2081 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2083 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2085 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2089 TEST_F(UnitTestRecordPropertyTest,
2090 AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
2091 EXPECT_NONFATAL_FAILURE(
2092 Test::RecordProperty("name", "1"),
2093 "'classname', 'name', 'status', 'time', 'type_param', 'value_param',"
2094 " 'file', and 'line' are reserved");
2097 class UnitTestRecordPropertyTestEnvironment : public Environment {
2099 virtual void TearDown() {
2100 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2102 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2104 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2106 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2108 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2110 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2112 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2114 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2119 // This will test property recording outside of any test or test case.
2120 static Environment* record_property_env =
2121 AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
2123 // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2124 // of various arities. They do not attempt to be exhaustive. Rather,
2125 // view them as smoke tests that can be easily reviewed and verified.
2126 // A more complete set of tests for predicate assertions can be found
2127 // in gtest_pred_impl_unittest.cc.
2129 // First, some predicates and predicate-formatters needed by the tests.
2131 // Returns true iff the argument is an even number.
2132 bool IsEven(int n) {
2133 return (n % 2) == 0;
2136 // A functor that returns true iff the argument is an even number.
2137 struct IsEvenFunctor {
2138 bool operator()(int n) { return IsEven(n); }
2141 // A predicate-formatter function that asserts the argument is an even
2143 AssertionResult AssertIsEven(const char* expr, int n) {
2145 return AssertionSuccess();
2149 msg << expr << " evaluates to " << n << ", which is not even.";
2150 return AssertionFailure(msg);
2153 // A predicate function that returns AssertionResult for use in
2154 // EXPECT/ASSERT_TRUE/FALSE.
2155 AssertionResult ResultIsEven(int n) {
2157 return AssertionSuccess() << n << " is even";
2159 return AssertionFailure() << n << " is odd";
2162 // A predicate function that returns AssertionResult but gives no
2163 // explanation why it succeeds. Needed for testing that
2164 // EXPECT/ASSERT_FALSE handles such functions correctly.
2165 AssertionResult ResultIsEvenNoExplanation(int n) {
2167 return AssertionSuccess();
2169 return AssertionFailure() << n << " is odd";
2172 // A predicate-formatter functor that asserts the argument is an even
2174 struct AssertIsEvenFunctor {
2175 AssertionResult operator()(const char* expr, int n) {
2176 return AssertIsEven(expr, n);
2180 // Returns true iff the sum of the arguments is an even number.
2181 bool SumIsEven2(int n1, int n2) {
2182 return IsEven(n1 + n2);
2185 // A functor that returns true iff the sum of the arguments is an even
2187 struct SumIsEven3Functor {
2188 bool operator()(int n1, int n2, int n3) {
2189 return IsEven(n1 + n2 + n3);
2193 // A predicate-formatter function that asserts the sum of the
2194 // arguments is an even number.
2195 AssertionResult AssertSumIsEven4(
2196 const char* e1, const char* e2, const char* e3, const char* e4,
2197 int n1, int n2, int n3, int n4) {
2198 const int sum = n1 + n2 + n3 + n4;
2200 return AssertionSuccess();
2204 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2205 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2206 << ") evaluates to " << sum << ", which is not even.";
2207 return AssertionFailure(msg);
2210 // A predicate-formatter functor that asserts the sum of the arguments
2211 // is an even number.
2212 struct AssertSumIsEven5Functor {
2213 AssertionResult operator()(
2214 const char* e1, const char* e2, const char* e3, const char* e4,
2215 const char* e5, int n1, int n2, int n3, int n4, int n5) {
2216 const int sum = n1 + n2 + n3 + n4 + n5;
2218 return AssertionSuccess();
2222 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2224 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2225 << ") evaluates to " << sum << ", which is not even.";
2226 return AssertionFailure(msg);
2231 // Tests unary predicate assertions.
2233 // Tests unary predicate assertions that don't use a custom formatter.
2234 TEST(Pred1Test, WithoutFormat) {
2236 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2237 ASSERT_PRED1(IsEven, 4);
2240 EXPECT_NONFATAL_FAILURE({ // NOLINT
2241 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2242 }, "This failure is expected.");
2243 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2244 "evaluates to false");
2247 // Tests unary predicate assertions that use a custom formatter.
2248 TEST(Pred1Test, WithFormat) {
2250 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2251 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2252 << "This failure is UNEXPECTED!";
2256 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2257 "n evaluates to 5, which is not even.");
2258 EXPECT_FATAL_FAILURE({ // NOLINT
2259 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2260 }, "This failure is expected.");
2263 // Tests that unary predicate assertions evaluates their arguments
2265 TEST(Pred1Test, SingleEvaluationOnFailure) {
2268 EXPECT_PRED1(IsEven, n++);
2269 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2272 EXPECT_FATAL_FAILURE({ // NOLINT
2273 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2274 << "This failure is expected.";
2275 }, "This failure is expected.");
2276 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2280 // Tests predicate assertions whose arity is >= 2.
2282 // Tests predicate assertions that don't use a custom formatter.
2283 TEST(PredTest, WithoutFormat) {
2285 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2286 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2291 EXPECT_NONFATAL_FAILURE({ // NOLINT
2292 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2293 }, "This failure is expected.");
2294 EXPECT_FATAL_FAILURE({ // NOLINT
2295 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2296 }, "evaluates to false");
2299 // Tests predicate assertions that use a custom formatter.
2300 TEST(PredTest, WithFormat) {
2302 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2303 "This failure is UNEXPECTED!";
2304 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2311 EXPECT_NONFATAL_FAILURE({ // NOLINT
2312 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2313 }, "evaluates to 13, which is not even.");
2314 EXPECT_FATAL_FAILURE({ // NOLINT
2315 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2316 << "This failure is expected.";
2317 }, "This failure is expected.");
2320 // Tests that predicate assertions evaluates their arguments
2322 TEST(PredTest, SingleEvaluationOnFailure) {
2326 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2327 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2328 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2330 // Another success case.
2335 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2336 n1++, n2++, n3++, n4++, n5++)
2337 << "This failure is UNEXPECTED!";
2338 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2339 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2340 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2341 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2342 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2346 EXPECT_NONFATAL_FAILURE({ // NOLINT
2347 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2348 << "This failure is expected.";
2349 }, "This failure is expected.");
2350 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2351 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2352 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2354 // Another failure case.
2355 n1 = n2 = n3 = n4 = 0;
2356 EXPECT_NONFATAL_FAILURE({ // NOLINT
2357 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2358 }, "evaluates to 1, which is not even.");
2359 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2360 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2361 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2362 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2366 // Some helper functions for testing using overloaded/template
2367 // functions with ASSERT_PREDn and EXPECT_PREDn.
2369 bool IsPositive(double x) {
2373 template <typename T>
2374 bool IsNegative(T x) {
2378 template <typename T1, typename T2>
2379 bool GreaterThan(T1 x1, T2 x2) {
2383 // Tests that overloaded functions can be used in *_PRED* as long as
2384 // their types are explicitly specified.
2385 TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2386 // C++Builder requires C-style casts rather than static_cast.
2387 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2388 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
2391 // Tests that template functions can be used in *_PRED* as long as
2392 // their types are explicitly specified.
2393 TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2394 EXPECT_PRED1(IsNegative<int>, -5);
2395 // Makes sure that we can handle templates with more than one
2397 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2401 // Some helper functions for testing using overloaded/template
2402 // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2404 AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2405 return n > 0 ? AssertionSuccess() :
2406 AssertionFailure(Message() << "Failure");
2409 AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2410 return x > 0 ? AssertionSuccess() :
2411 AssertionFailure(Message() << "Failure");
2414 template <typename T>
2415 AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2416 return x < 0 ? AssertionSuccess() :
2417 AssertionFailure(Message() << "Failure");
2420 template <typename T1, typename T2>
2421 AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2422 const T1& x1, const T2& x2) {
2423 return x1 == x2 ? AssertionSuccess() :
2424 AssertionFailure(Message() << "Failure");
2427 // Tests that overloaded functions can be used in *_PRED_FORMAT*
2428 // without explicitly specifying their types.
2429 TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2430 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2431 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2434 // Tests that template functions can be used in *_PRED_FORMAT* without
2435 // explicitly specifying their types.
2436 TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2437 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2438 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2442 // Tests string assertions.
2444 // Tests ASSERT_STREQ with non-NULL arguments.
2445 TEST(StringAssertionTest, ASSERT_STREQ) {
2446 const char * const p1 = "good";
2447 ASSERT_STREQ(p1, p1);
2449 // Let p2 have the same content as p1, but be at a different address.
2450 const char p2[] = "good";
2451 ASSERT_STREQ(p1, p2);
2453 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2454 " \"bad\"\n \"good\"");
2457 // Tests ASSERT_STREQ with NULL arguments.
2458 TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2459 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2460 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2464 // Tests ASSERT_STREQ with NULL arguments.
2465 TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2466 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2470 // Tests ASSERT_STRNE.
2471 TEST(StringAssertionTest, ASSERT_STRNE) {
2472 ASSERT_STRNE("hi", "Hi");
2473 ASSERT_STRNE("Hi", NULL);
2474 ASSERT_STRNE(NULL, "Hi");
2475 ASSERT_STRNE("", NULL);
2476 ASSERT_STRNE(NULL, "");
2477 ASSERT_STRNE("", "Hi");
2478 ASSERT_STRNE("Hi", "");
2479 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2480 "\"Hi\" vs \"Hi\"");
2483 // Tests ASSERT_STRCASEEQ.
2484 TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2485 ASSERT_STRCASEEQ("hi", "Hi");
2486 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2488 ASSERT_STRCASEEQ("", "");
2489 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2493 // Tests ASSERT_STRCASENE.
2494 TEST(StringAssertionTest, ASSERT_STRCASENE) {
2495 ASSERT_STRCASENE("hi1", "Hi2");
2496 ASSERT_STRCASENE("Hi", NULL);
2497 ASSERT_STRCASENE(NULL, "Hi");
2498 ASSERT_STRCASENE("", NULL);
2499 ASSERT_STRCASENE(NULL, "");
2500 ASSERT_STRCASENE("", "Hi");
2501 ASSERT_STRCASENE("Hi", "");
2502 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2506 // Tests *_STREQ on wide strings.
2507 TEST(StringAssertionTest, STREQ_Wide) {
2509 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2512 ASSERT_STREQ(L"", L"");
2514 // Non-null vs NULL.
2515 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2519 EXPECT_STREQ(L"Hi", L"Hi");
2522 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2525 // Strings containing wide characters.
2526 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2529 // The streaming variation.
2530 EXPECT_NONFATAL_FAILURE({ // NOLINT
2531 EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
2532 }, "Expected failure");
2535 // Tests *_STRNE on wide strings.
2536 TEST(StringAssertionTest, STRNE_Wide) {
2538 EXPECT_NONFATAL_FAILURE({ // NOLINT
2539 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2543 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2546 // Non-null vs NULL.
2547 ASSERT_STRNE(L"non-null", NULL);
2550 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2554 EXPECT_STRNE(L"abc", L"Abc");
2556 // Strings containing wide characters.
2557 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2560 // The streaming variation.
2561 ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
2564 // Tests for ::testing::IsSubstring().
2566 // Tests that IsSubstring() returns the correct result when the input
2567 // argument type is const char*.
2568 TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2569 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2570 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2571 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2573 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2574 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2577 // Tests that IsSubstring() returns the correct result when the input
2578 // argument type is const wchar_t*.
2579 TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2580 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2581 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
2582 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2584 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2585 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2588 // Tests that IsSubstring() generates the correct message when the input
2589 // argument type is const char*.
2590 TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2591 EXPECT_STREQ("Value of: needle_expr\n"
2592 " Actual: \"needle\"\n"
2593 "Expected: a substring of haystack_expr\n"
2594 "Which is: \"haystack\"",
2595 IsSubstring("needle_expr", "haystack_expr",
2596 "needle", "haystack").failure_message());
2599 // Tests that IsSubstring returns the correct result when the input
2600 // argument type is ::std::string.
2601 TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2602 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2603 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2606 #if GTEST_HAS_STD_WSTRING
2607 // Tests that IsSubstring returns the correct result when the input
2608 // argument type is ::std::wstring.
2609 TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2610 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2611 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2614 // Tests that IsSubstring() generates the correct message when the input
2615 // argument type is ::std::wstring.
2616 TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2617 EXPECT_STREQ("Value of: needle_expr\n"
2618 " Actual: L\"needle\"\n"
2619 "Expected: a substring of haystack_expr\n"
2620 "Which is: L\"haystack\"",
2622 "needle_expr", "haystack_expr",
2623 ::std::wstring(L"needle"), L"haystack").failure_message());
2626 #endif // GTEST_HAS_STD_WSTRING
2628 // Tests for ::testing::IsNotSubstring().
2630 // Tests that IsNotSubstring() returns the correct result when the input
2631 // argument type is const char*.
2632 TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2633 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2634 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2637 // Tests that IsNotSubstring() returns the correct result when the input
2638 // argument type is const wchar_t*.
2639 TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2640 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2641 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2644 // Tests that IsNotSubstring() generates the correct message when the input
2645 // argument type is const wchar_t*.
2646 TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2647 EXPECT_STREQ("Value of: needle_expr\n"
2648 " Actual: L\"needle\"\n"
2649 "Expected: not a substring of haystack_expr\n"
2650 "Which is: L\"two needles\"",
2652 "needle_expr", "haystack_expr",
2653 L"needle", L"two needles").failure_message());
2656 // Tests that IsNotSubstring returns the correct result when the input
2657 // argument type is ::std::string.
2658 TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2659 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2660 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2663 // Tests that IsNotSubstring() generates the correct message when the input
2664 // argument type is ::std::string.
2665 TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2666 EXPECT_STREQ("Value of: needle_expr\n"
2667 " Actual: \"needle\"\n"
2668 "Expected: not a substring of haystack_expr\n"
2669 "Which is: \"two needles\"",
2671 "needle_expr", "haystack_expr",
2672 ::std::string("needle"), "two needles").failure_message());
2675 #if GTEST_HAS_STD_WSTRING
2677 // Tests that IsNotSubstring returns the correct result when the input
2678 // argument type is ::std::wstring.
2679 TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2681 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2682 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2685 #endif // GTEST_HAS_STD_WSTRING
2687 // Tests floating-point assertions.
2689 template <typename RawType>
2690 class FloatingPointTest : public Test {
2692 // Pre-calculated numbers to be used by the tests.
2694 RawType close_to_positive_zero;
2695 RawType close_to_negative_zero;
2696 RawType further_from_negative_zero;
2698 RawType close_to_one;
2699 RawType further_from_one;
2702 RawType close_to_infinity;
2703 RawType further_from_infinity;
2709 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2710 typedef typename Floating::Bits Bits;
2712 virtual void SetUp() {
2713 const size_t max_ulps = Floating::kMaxUlps;
2715 // The bits that represent 0.0.
2716 const Bits zero_bits = Floating(0).bits();
2718 // Makes some numbers close to 0.0.
2719 values_.close_to_positive_zero = Floating::ReinterpretBits(
2720 zero_bits + max_ulps/2);
2721 values_.close_to_negative_zero = -Floating::ReinterpretBits(
2722 zero_bits + max_ulps - max_ulps/2);
2723 values_.further_from_negative_zero = -Floating::ReinterpretBits(
2724 zero_bits + max_ulps + 1 - max_ulps/2);
2726 // The bits that represent 1.0.
2727 const Bits one_bits = Floating(1).bits();
2729 // Makes some numbers close to 1.0.
2730 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2731 values_.further_from_one = Floating::ReinterpretBits(
2732 one_bits + max_ulps + 1);
2735 values_.infinity = Floating::Infinity();
2737 // The bits that represent +infinity.
2738 const Bits infinity_bits = Floating(values_.infinity).bits();
2740 // Makes some numbers close to infinity.
2741 values_.close_to_infinity = Floating::ReinterpretBits(
2742 infinity_bits - max_ulps);
2743 values_.further_from_infinity = Floating::ReinterpretBits(
2744 infinity_bits - max_ulps - 1);
2746 // Makes some NAN's. Sets the most significant bit of the fraction so that
2747 // our NaN's are quiet; trying to process a signaling NaN would raise an
2748 // exception if our environment enables floating point exceptions.
2749 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2750 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2751 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2752 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
2756 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2759 static TestValues values_;
2762 template <typename RawType>
2763 typename FloatingPointTest<RawType>::TestValues
2764 FloatingPointTest<RawType>::values_;
2766 // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2767 typedef FloatingPointTest<float> FloatTest;
2769 // Tests that the size of Float::Bits matches the size of float.
2770 TEST_F(FloatTest, Size) {
2774 // Tests comparing with +0 and -0.
2775 TEST_F(FloatTest, Zeros) {
2776 EXPECT_FLOAT_EQ(0.0, -0.0);
2777 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2779 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2783 // Tests comparing numbers close to 0.
2785 // This ensures that *_FLOAT_EQ handles the sign correctly and no
2786 // overflow occurs when comparing numbers whose absolute value is very
2788 TEST_F(FloatTest, AlmostZeros) {
2789 // In C++Builder, names within local classes (such as used by
2790 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2791 // scoping class. Use a static local alias as a workaround.
2792 // We use the assignment syntax since some compilers, like Sun Studio,
2793 // don't allow initializing references using construction syntax
2795 static const FloatTest::TestValues& v = this->values_;
2797 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2798 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2799 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2801 EXPECT_FATAL_FAILURE({ // NOLINT
2802 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2803 v.further_from_negative_zero);
2804 }, "v.further_from_negative_zero");
2807 // Tests comparing numbers close to each other.
2808 TEST_F(FloatTest, SmallDiff) {
2809 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2810 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2811 "values_.further_from_one");
2814 // Tests comparing numbers far apart.
2815 TEST_F(FloatTest, LargeDiff) {
2816 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2820 // Tests comparing with infinity.
2822 // This ensures that no overflow occurs when comparing numbers whose
2823 // absolute value is very large.
2824 TEST_F(FloatTest, Infinity) {
2825 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2826 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
2827 #if !GTEST_OS_SYMBIAN
2828 // Nokia's STLport crashes if we try to output infinity or NaN.
2829 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2830 "-values_.infinity");
2832 // This is interesting as the representations of infinity and nan1
2833 // are only 1 DLP apart.
2834 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2836 #endif // !GTEST_OS_SYMBIAN
2839 // Tests that comparing with NAN always returns false.
2840 TEST_F(FloatTest, NaN) {
2841 #if !GTEST_OS_SYMBIAN
2842 // Nokia's STLport crashes if we try to output infinity or NaN.
2844 // In C++Builder, names within local classes (such as used by
2845 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2846 // scoping class. Use a static local alias as a workaround.
2847 // We use the assignment syntax since some compilers, like Sun Studio,
2848 // don't allow initializing references using construction syntax
2850 static const FloatTest::TestValues& v = this->values_;
2852 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2854 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2856 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2859 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2861 #endif // !GTEST_OS_SYMBIAN
2864 // Tests that *_FLOAT_EQ are reflexive.
2865 TEST_F(FloatTest, Reflexive) {
2866 EXPECT_FLOAT_EQ(0.0, 0.0);
2867 EXPECT_FLOAT_EQ(1.0, 1.0);
2868 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
2871 // Tests that *_FLOAT_EQ are commutative.
2872 TEST_F(FloatTest, Commutative) {
2873 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2874 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2876 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2877 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2881 // Tests EXPECT_NEAR.
2882 TEST_F(FloatTest, EXPECT_NEAR) {
2883 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2884 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2885 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2886 "The difference between 1.0f and 1.5f is 0.5, "
2887 "which exceeds 0.25f");
2888 // To work around a bug in gcc 2.95.0, there is intentionally no
2889 // space after the first comma in the previous line.
2892 // Tests ASSERT_NEAR.
2893 TEST_F(FloatTest, ASSERT_NEAR) {
2894 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2895 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2896 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2897 "The difference between 1.0f and 1.5f is 0.5, "
2898 "which exceeds 0.25f");
2899 // To work around a bug in gcc 2.95.0, there is intentionally no
2900 // space after the first comma in the previous line.
2903 // Tests the cases where FloatLE() should succeed.
2904 TEST_F(FloatTest, FloatLESucceeds) {
2905 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2906 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
2908 // or when val1 is greater than, but almost equals to, val2.
2909 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2912 // Tests the cases where FloatLE() should fail.
2913 TEST_F(FloatTest, FloatLEFails) {
2914 // When val1 is greater than val2 by a large margin,
2915 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2916 "(2.0f) <= (1.0f)");
2918 // or by a small yet non-negligible margin,
2919 EXPECT_NONFATAL_FAILURE({ // NOLINT
2920 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2921 }, "(values_.further_from_one) <= (1.0f)");
2923 #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2924 // Nokia's STLport crashes if we try to output infinity or NaN.
2925 // C++Builder gives bad results for ordered comparisons involving NaNs
2926 // due to compiler bugs.
2927 EXPECT_NONFATAL_FAILURE({ // NOLINT
2928 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2929 }, "(values_.nan1) <= (values_.infinity)");
2930 EXPECT_NONFATAL_FAILURE({ // NOLINT
2931 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2932 }, "(-values_.infinity) <= (values_.nan1)");
2933 EXPECT_FATAL_FAILURE({ // NOLINT
2934 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2935 }, "(values_.nan1) <= (values_.nan1)");
2936 #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2939 // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2940 typedef FloatingPointTest<double> DoubleTest;
2942 // Tests that the size of Double::Bits matches the size of double.
2943 TEST_F(DoubleTest, Size) {
2947 // Tests comparing with +0 and -0.
2948 TEST_F(DoubleTest, Zeros) {
2949 EXPECT_DOUBLE_EQ(0.0, -0.0);
2950 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2952 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2956 // Tests comparing numbers close to 0.
2958 // This ensures that *_DOUBLE_EQ handles the sign correctly and no
2959 // overflow occurs when comparing numbers whose absolute value is very
2961 TEST_F(DoubleTest, AlmostZeros) {
2962 // In C++Builder, names within local classes (such as used by
2963 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2964 // scoping class. Use a static local alias as a workaround.
2965 // We use the assignment syntax since some compilers, like Sun Studio,
2966 // don't allow initializing references using construction syntax
2968 static const DoubleTest::TestValues& v = this->values_;
2970 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2971 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2972 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2974 EXPECT_FATAL_FAILURE({ // NOLINT
2975 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2976 v.further_from_negative_zero);
2977 }, "v.further_from_negative_zero");
2980 // Tests comparing numbers close to each other.
2981 TEST_F(DoubleTest, SmallDiff) {
2982 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2983 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2984 "values_.further_from_one");
2987 // Tests comparing numbers far apart.
2988 TEST_F(DoubleTest, LargeDiff) {
2989 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2993 // Tests comparing with infinity.
2995 // This ensures that no overflow occurs when comparing numbers whose
2996 // absolute value is very large.
2997 TEST_F(DoubleTest, Infinity) {
2998 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
2999 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
3000 #if !GTEST_OS_SYMBIAN
3001 // Nokia's STLport crashes if we try to output infinity or NaN.
3002 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
3003 "-values_.infinity");
3005 // This is interesting as the representations of infinity_ and nan1_
3006 // are only 1 DLP apart.
3007 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
3009 #endif // !GTEST_OS_SYMBIAN
3012 // Tests that comparing with NAN always returns false.
3013 TEST_F(DoubleTest, NaN) {
3014 #if !GTEST_OS_SYMBIAN
3015 // In C++Builder, names within local classes (such as used by
3016 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
3017 // scoping class. Use a static local alias as a workaround.
3018 // We use the assignment syntax since some compilers, like Sun Studio,
3019 // don't allow initializing references using construction syntax
3021 static const DoubleTest::TestValues& v = this->values_;
3023 // Nokia's STLport crashes if we try to output infinity or NaN.
3024 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
3026 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
3027 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3028 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
3030 #endif // !GTEST_OS_SYMBIAN
3033 // Tests that *_DOUBLE_EQ are reflexive.
3034 TEST_F(DoubleTest, Reflexive) {
3035 EXPECT_DOUBLE_EQ(0.0, 0.0);
3036 EXPECT_DOUBLE_EQ(1.0, 1.0);
3037 #if !GTEST_OS_SYMBIAN
3038 // Nokia's STLport crashes if we try to output infinity or NaN.
3039 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
3040 #endif // !GTEST_OS_SYMBIAN
3043 // Tests that *_DOUBLE_EQ are commutative.
3044 TEST_F(DoubleTest, Commutative) {
3045 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3046 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
3048 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3049 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3053 // Tests EXPECT_NEAR.
3054 TEST_F(DoubleTest, EXPECT_NEAR) {
3055 EXPECT_NEAR(-1.0, -1.1, 0.2);
3056 EXPECT_NEAR(2.0, 3.0, 1.0);
3057 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3058 "The difference between 1.0 and 1.5 is 0.5, "
3059 "which exceeds 0.25");
3060 // To work around a bug in gcc 2.95.0, there is intentionally no
3061 // space after the first comma in the previous statement.
3064 // Tests ASSERT_NEAR.
3065 TEST_F(DoubleTest, ASSERT_NEAR) {
3066 ASSERT_NEAR(-1.0, -1.1, 0.2);
3067 ASSERT_NEAR(2.0, 3.0, 1.0);
3068 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3069 "The difference between 1.0 and 1.5 is 0.5, "
3070 "which exceeds 0.25");
3071 // To work around a bug in gcc 2.95.0, there is intentionally no
3072 // space after the first comma in the previous statement.
3075 // Tests the cases where DoubleLE() should succeed.
3076 TEST_F(DoubleTest, DoubleLESucceeds) {
3077 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3078 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
3080 // or when val1 is greater than, but almost equals to, val2.
3081 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3084 // Tests the cases where DoubleLE() should fail.
3085 TEST_F(DoubleTest, DoubleLEFails) {
3086 // When val1 is greater than val2 by a large margin,
3087 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
3090 // or by a small yet non-negligible margin,
3091 EXPECT_NONFATAL_FAILURE({ // NOLINT
3092 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3093 }, "(values_.further_from_one) <= (1.0)");
3095 #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3096 // Nokia's STLport crashes if we try to output infinity or NaN.
3097 // C++Builder gives bad results for ordered comparisons involving NaNs
3098 // due to compiler bugs.
3099 EXPECT_NONFATAL_FAILURE({ // NOLINT
3100 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3101 }, "(values_.nan1) <= (values_.infinity)");
3102 EXPECT_NONFATAL_FAILURE({ // NOLINT
3103 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3104 }, " (-values_.infinity) <= (values_.nan1)");
3105 EXPECT_FATAL_FAILURE({ // NOLINT
3106 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3107 }, "(values_.nan1) <= (values_.nan1)");
3108 #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3112 // Verifies that a test or test case whose name starts with DISABLED_ is
3115 // A test whose name starts with DISABLED_.
3117 TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3118 FAIL() << "Unexpected failure: Disabled test should not be run.";
3121 // A test whose name does not start with DISABLED_.
3123 TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3127 // A test case whose name starts with DISABLED_.
3129 TEST(DISABLED_TestCase, TestShouldNotRun) {
3130 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3133 // A test case and test whose names start with DISABLED_.
3135 TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
3136 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3139 // Check that when all tests in a test case are disabled, SetUpTestCase() and
3140 // TearDownTestCase() are not called.
3141 class DisabledTestsTest : public Test {
3143 static void SetUpTestCase() {
3144 FAIL() << "Unexpected failure: All tests disabled in test case. "
3145 "SetUpTestCase() should not be called.";
3148 static void TearDownTestCase() {
3149 FAIL() << "Unexpected failure: All tests disabled in test case. "
3150 "TearDownTestCase() should not be called.";
3154 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3155 FAIL() << "Unexpected failure: Disabled test should not be run.";
3158 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3159 FAIL() << "Unexpected failure: Disabled test should not be run.";
3162 // Tests that disabled typed tests aren't run.
3164 #if GTEST_HAS_TYPED_TEST
3166 template <typename T>
3167 class TypedTest : public Test {
3170 typedef testing::Types<int, double> NumericTypes;
3171 TYPED_TEST_CASE(TypedTest, NumericTypes);
3173 TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3174 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3177 template <typename T>
3178 class DISABLED_TypedTest : public Test {
3181 TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
3183 TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3184 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3187 #endif // GTEST_HAS_TYPED_TEST
3189 // Tests that disabled type-parameterized tests aren't run.
3191 #if GTEST_HAS_TYPED_TEST_P
3193 template <typename T>
3194 class TypedTestP : public Test {
3197 TYPED_TEST_CASE_P(TypedTestP);
3199 TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3200 FAIL() << "Unexpected failure: "
3201 << "Disabled type-parameterized test should not run.";
3204 REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
3206 INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
3208 template <typename T>
3209 class DISABLED_TypedTestP : public Test {
3212 TYPED_TEST_CASE_P(DISABLED_TypedTestP);
3214 TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3215 FAIL() << "Unexpected failure: "
3216 << "Disabled type-parameterized test should not run.";
3219 REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
3221 INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
3223 #endif // GTEST_HAS_TYPED_TEST_P
3225 // Tests that assertion macros evaluate their arguments exactly once.
3227 class SingleEvaluationTest : public Test {
3228 public: // Must be public and not protected due to a bug in g++ 3.4.2.
3229 // This helper function is needed by the FailedASSERT_STREQ test
3230 // below. It's public to work around C++Builder's bug with scoping local
3232 static void CompareAndIncrementCharPtrs() {
3233 ASSERT_STREQ(p1_++, p2_++);
3236 // This helper function is needed by the FailedASSERT_NE test below. It's
3237 // public to work around C++Builder's bug with scoping local classes.
3238 static void CompareAndIncrementInts() {
3239 ASSERT_NE(a_++, b_++);
3243 SingleEvaluationTest() {
3250 static const char* const s1_;
3251 static const char* const s2_;
3252 static const char* p1_;
3253 static const char* p2_;
3259 const char* const SingleEvaluationTest::s1_ = "01234";
3260 const char* const SingleEvaluationTest::s2_ = "abcde";
3261 const char* SingleEvaluationTest::p1_;
3262 const char* SingleEvaluationTest::p2_;
3263 int SingleEvaluationTest::a_;
3264 int SingleEvaluationTest::b_;
3266 // Tests that when ASSERT_STREQ fails, it evaluates its arguments
3268 TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3269 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3271 EXPECT_EQ(s1_ + 1, p1_);
3272 EXPECT_EQ(s2_ + 1, p2_);
3275 // Tests that string assertion arguments are evaluated exactly once.
3276 TEST_F(SingleEvaluationTest, ASSERT_STR) {
3277 // successful EXPECT_STRNE
3278 EXPECT_STRNE(p1_++, p2_++);
3279 EXPECT_EQ(s1_ + 1, p1_);
3280 EXPECT_EQ(s2_ + 1, p2_);
3282 // failed EXPECT_STRCASEEQ
3283 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3285 EXPECT_EQ(s1_ + 2, p1_);
3286 EXPECT_EQ(s2_ + 2, p2_);
3289 // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3291 TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3292 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3293 "(a_++) != (b_++)");
3298 // Tests that assertion arguments are evaluated exactly once.
3299 TEST_F(SingleEvaluationTest, OtherCases) {
3300 // successful EXPECT_TRUE
3301 EXPECT_TRUE(0 == a_++); // NOLINT
3304 // failed EXPECT_TRUE
3305 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3308 // successful EXPECT_GT
3309 EXPECT_GT(a_++, b_++);
3314 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3318 // successful ASSERT_TRUE
3319 ASSERT_TRUE(0 < a_++); // NOLINT
3322 // successful ASSERT_GT
3323 ASSERT_GT(a_++, b_++);
3328 #if GTEST_HAS_EXCEPTIONS
3330 void ThrowAnInteger() {
3334 // Tests that assertion arguments are evaluated exactly once.
3335 TEST_F(SingleEvaluationTest, ExceptionTests) {
3336 // successful EXPECT_THROW
3337 EXPECT_THROW({ // NOLINT
3343 // failed EXPECT_THROW, throws different
3344 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3347 }, bool), "throws a different type");
3350 // failed EXPECT_THROW, throws nothing
3351 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3354 // successful EXPECT_NO_THROW
3355 EXPECT_NO_THROW(a_++);
3358 // failed EXPECT_NO_THROW
3359 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3365 // successful EXPECT_ANY_THROW
3366 EXPECT_ANY_THROW({ // NOLINT
3372 // failed EXPECT_ANY_THROW
3373 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3377 #endif // GTEST_HAS_EXCEPTIONS
3379 // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3380 class NoFatalFailureTest : public Test {
3383 void FailsNonFatal() {
3384 ADD_FAILURE() << "some non-fatal failure";
3387 FAIL() << "some fatal failure";
3390 void DoAssertNoFatalFailureOnFails() {
3391 ASSERT_NO_FATAL_FAILURE(Fails());
3392 ADD_FAILURE() << "should not reach here.";
3395 void DoExpectNoFatalFailureOnFails() {
3396 EXPECT_NO_FATAL_FAILURE(Fails());
3397 ADD_FAILURE() << "other failure";
3401 TEST_F(NoFatalFailureTest, NoFailure) {
3402 EXPECT_NO_FATAL_FAILURE(Succeeds());
3403 ASSERT_NO_FATAL_FAILURE(Succeeds());
3406 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3407 EXPECT_NONFATAL_FAILURE(
3408 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3409 "some non-fatal failure");
3410 EXPECT_NONFATAL_FAILURE(
3411 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3412 "some non-fatal failure");
3415 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3416 TestPartResultArray gtest_failures;
3418 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3419 DoAssertNoFatalFailureOnFails();
3421 ASSERT_EQ(2, gtest_failures.size());
3422 EXPECT_EQ(TestPartResult::kFatalFailure,
3423 gtest_failures.GetTestPartResult(0).type());
3424 EXPECT_EQ(TestPartResult::kFatalFailure,
3425 gtest_failures.GetTestPartResult(1).type());
3426 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3427 gtest_failures.GetTestPartResult(0).message());
3428 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3429 gtest_failures.GetTestPartResult(1).message());
3432 TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3433 TestPartResultArray gtest_failures;
3435 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3436 DoExpectNoFatalFailureOnFails();
3438 ASSERT_EQ(3, gtest_failures.size());
3439 EXPECT_EQ(TestPartResult::kFatalFailure,
3440 gtest_failures.GetTestPartResult(0).type());
3441 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3442 gtest_failures.GetTestPartResult(1).type());
3443 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3444 gtest_failures.GetTestPartResult(2).type());
3445 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3446 gtest_failures.GetTestPartResult(0).message());
3447 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3448 gtest_failures.GetTestPartResult(1).message());
3449 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3450 gtest_failures.GetTestPartResult(2).message());
3453 TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3454 TestPartResultArray gtest_failures;
3456 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3457 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3459 ASSERT_EQ(2, gtest_failures.size());
3460 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3461 gtest_failures.GetTestPartResult(0).type());
3462 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3463 gtest_failures.GetTestPartResult(1).type());
3464 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3465 gtest_failures.GetTestPartResult(0).message());
3466 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3467 gtest_failures.GetTestPartResult(1).message());
3470 // Tests non-string assertions.
3472 std::string EditsToString(const std::vector<EditType>& edits) {
3474 for (size_t i = 0; i < edits.size(); ++i) {
3475 static const char kEdits[] = " +-/";
3476 out.append(1, kEdits[edits[i]]);
3481 std::vector<size_t> CharsToIndices(const std::string& str) {
3482 std::vector<size_t> out;
3483 for (size_t i = 0; i < str.size(); ++i) {
3484 out.push_back(str[i]);
3489 std::vector<std::string> CharsToLines(const std::string& str) {
3490 std::vector<std::string> out;
3491 for (size_t i = 0; i < str.size(); ++i) {
3492 out.push_back(str.substr(i, 1));
3497 TEST(EditDistance, TestCases) {
3502 const char* expected_edits;
3503 const char* expected_diff;
3505 static const Case kCases[] = {
3507 {__LINE__, "A", "A", " ", ""},
3508 {__LINE__, "ABCDE", "ABCDE", " ", ""},
3510 {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
3511 {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
3513 {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
3514 {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
3516 {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
3517 {__LINE__, "ABCD", "abcd", "////",
3518 "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
3520 {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
3521 "@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"},
3522 {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
3523 "@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"},
3524 {__LINE__, "ABCDE", "BCDCD", "- +/",
3525 "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
3526 {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
3527 "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
3528 "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
3530 for (const Case* c = kCases; c->left; ++c) {
3531 EXPECT_TRUE(c->expected_edits ==
3532 EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3533 CharsToIndices(c->right))))
3534 << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
3535 << EditsToString(CalculateOptimalEdits(
3536 CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
3537 EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
3538 CharsToLines(c->right)))
3539 << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
3540 << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
3545 // Tests EqFailure(), used for implementing *EQ* assertions.
3546 TEST(AssertionTest, EqFailure) {
3547 const std::string foo_val("5"), bar_val("6");
3548 const std::string msg1(
3549 EqFailure("foo", "bar", foo_val, bar_val, false)
3550 .failure_message());
3552 "Expected equality of these values:\n"
3559 const std::string msg2(
3560 EqFailure("foo", "6", foo_val, bar_val, false)
3561 .failure_message());
3563 "Expected equality of these values:\n"
3569 const std::string msg3(
3570 EqFailure("5", "bar", foo_val, bar_val, false)
3571 .failure_message());
3573 "Expected equality of these values:\n"
3579 const std::string msg4(
3580 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3582 "Expected equality of these values:\n"
3587 const std::string msg5(
3588 EqFailure("foo", "bar",
3589 std::string("\"x\""), std::string("\"y\""),
3590 true).failure_message());
3592 "Expected equality of these values:\n"
3594 " Which is: \"x\"\n"
3596 " Which is: \"y\"\n"
3601 TEST(AssertionTest, EqFailureWithDiff) {
3602 const std::string left(
3603 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
3604 const std::string right(
3605 "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
3606 const std::string msg1(
3607 EqFailure("left", "right", left, right, false).failure_message());
3609 "Expected equality of these values:\n"
3612 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3614 " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3615 "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
3616 "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
3620 // Tests AppendUserMessage(), used for implementing the *EQ* macros.
3621 TEST(AssertionTest, AppendUserMessage) {
3622 const std::string foo("foo");
3626 AppendUserMessage(foo, msg).c_str());
3629 EXPECT_STREQ("foo\nbar",
3630 AppendUserMessage(foo, msg).c_str());
3634 // Silences warnings: "Condition is always true", "Unreachable code"
3635 # pragma option push -w-ccc -w-rch
3638 // Tests ASSERT_TRUE.
3639 TEST(AssertionTest, ASSERT_TRUE) {
3640 ASSERT_TRUE(2 > 1); // NOLINT
3641 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3645 // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3646 TEST(AssertionTest, AssertTrueWithAssertionResult) {
3647 ASSERT_TRUE(ResultIsEven(2));
3648 #ifndef __BORLANDC__
3649 // ICE's in C++Builder.
3650 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3651 "Value of: ResultIsEven(3)\n"
3652 " Actual: false (3 is odd)\n"
3655 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3656 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3657 "Value of: ResultIsEvenNoExplanation(3)\n"
3658 " Actual: false (3 is odd)\n"
3662 // Tests ASSERT_FALSE.
3663 TEST(AssertionTest, ASSERT_FALSE) {
3664 ASSERT_FALSE(2 < 1); // NOLINT
3665 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3671 // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3672 TEST(AssertionTest, AssertFalseWithAssertionResult) {
3673 ASSERT_FALSE(ResultIsEven(3));
3674 #ifndef __BORLANDC__
3675 // ICE's in C++Builder.
3676 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3677 "Value of: ResultIsEven(2)\n"
3678 " Actual: true (2 is even)\n"
3681 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3682 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3683 "Value of: ResultIsEvenNoExplanation(2)\n"
3689 // Restores warnings after previous "#pragma option push" suppressed them
3693 // Tests using ASSERT_EQ on double values. The purpose is to make
3694 // sure that the specialization we did for integer and anonymous enums
3695 // isn't used for double arguments.
3696 TEST(ExpectTest, ASSERT_EQ_Double) {
3698 ASSERT_EQ(5.6, 5.6);
3701 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3706 TEST(AssertionTest, ASSERT_EQ) {
3707 ASSERT_EQ(5, 2 + 3);
3708 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3709 "Expected equality of these values:\n"
3715 // Tests ASSERT_EQ(NULL, pointer).
3716 #if GTEST_CAN_COMPARE_NULL
3717 TEST(AssertionTest, ASSERT_EQ_NULL) {
3719 const char* p = NULL;
3720 // Some older GCC versions may issue a spurious warning in this or the next
3721 // assertion statement. This warning should not be suppressed with
3722 // static_cast since the test verifies the ability to use bare NULL as the
3723 // expected parameter to the macro.
3728 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3731 #endif // GTEST_CAN_COMPARE_NULL
3733 // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3734 // treated as a null pointer by the compiler, we need to make sure
3735 // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3736 // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3737 TEST(ExpectTest, ASSERT_EQ_0) {
3744 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3749 TEST(AssertionTest, ASSERT_NE) {
3751 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3752 "Expected: ('a') != ('a'), "
3753 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3757 TEST(AssertionTest, ASSERT_LE) {
3760 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3761 "Expected: (2) <= (0), actual: 2 vs 0");
3765 TEST(AssertionTest, ASSERT_LT) {
3767 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3768 "Expected: (2) < (2), actual: 2 vs 2");
3772 TEST(AssertionTest, ASSERT_GE) {
3775 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3776 "Expected: (2) >= (3), actual: 2 vs 3");
3780 TEST(AssertionTest, ASSERT_GT) {
3782 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3783 "Expected: (2) > (2), actual: 2 vs 2");
3786 #if GTEST_HAS_EXCEPTIONS
3788 void ThrowNothing() {}
3790 // Tests ASSERT_THROW.
3791 TEST(AssertionTest, ASSERT_THROW) {
3792 ASSERT_THROW(ThrowAnInteger(), int);
3794 # ifndef __BORLANDC__
3796 // ICE's in C++Builder 2007 and 2009.
3797 EXPECT_FATAL_FAILURE(
3798 ASSERT_THROW(ThrowAnInteger(), bool),
3799 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3800 " Actual: it throws a different type.");
3803 EXPECT_FATAL_FAILURE(
3804 ASSERT_THROW(ThrowNothing(), bool),
3805 "Expected: ThrowNothing() throws an exception of type bool.\n"
3806 " Actual: it throws nothing.");
3809 // Tests ASSERT_NO_THROW.
3810 TEST(AssertionTest, ASSERT_NO_THROW) {
3811 ASSERT_NO_THROW(ThrowNothing());
3812 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3813 "Expected: ThrowAnInteger() doesn't throw an exception."
3814 "\n Actual: it throws.");
3817 // Tests ASSERT_ANY_THROW.
3818 TEST(AssertionTest, ASSERT_ANY_THROW) {
3819 ASSERT_ANY_THROW(ThrowAnInteger());
3820 EXPECT_FATAL_FAILURE(
3821 ASSERT_ANY_THROW(ThrowNothing()),
3822 "Expected: ThrowNothing() throws an exception.\n"
3823 " Actual: it doesn't.");
3826 #endif // GTEST_HAS_EXCEPTIONS
3828 // Makes sure we deal with the precedence of <<. This test should
3830 TEST(AssertionTest, AssertPrecedence) {
3831 ASSERT_EQ(1 < 2, true);
3832 bool false_value = false;
3833 ASSERT_EQ(true && false_value, false);
3836 // A subroutine used by the following test.
3837 void TestEq1(int x) {
3841 // Tests calling a test subroutine that's not part of a fixture.
3842 TEST(AssertionTest, NonFixtureSubroutine) {
3843 EXPECT_FATAL_FAILURE(TestEq1(2),
3844 " x\n Which is: 2");
3847 // An uncopyable class.
3850 explicit Uncopyable(int a_value) : value_(a_value) {}
3852 int value() const { return value_; }
3853 bool operator==(const Uncopyable& rhs) const {
3854 return value() == rhs.value();
3857 // This constructor deliberately has no implementation, as we don't
3858 // want this class to be copyable.
3859 Uncopyable(const Uncopyable&); // NOLINT
3864 ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3865 return os << value.value();
3869 bool IsPositiveUncopyable(const Uncopyable& x) {
3870 return x.value() > 0;
3873 // A subroutine used by the following test.
3874 void TestAssertNonPositive() {
3876 ASSERT_PRED1(IsPositiveUncopyable, y);
3878 // A subroutine used by the following test.
3879 void TestAssertEqualsUncopyable() {
3885 // Tests that uncopyable objects can be used in assertions.
3886 TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3888 ASSERT_PRED1(IsPositiveUncopyable, x);
3890 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3891 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3892 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3893 "Expected equality of these values:\n"
3894 " x\n Which is: 5\n y\n Which is: -1");
3897 // Tests that uncopyable objects can be used in expects.
3898 TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3900 EXPECT_PRED1(IsPositiveUncopyable, x);
3902 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3903 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3905 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3906 "Expected equality of these values:\n"
3907 " x\n Which is: 5\n y\n Which is: -1");
3915 TEST(AssertionTest, NamedEnum) {
3916 EXPECT_EQ(kE1, kE1);
3917 EXPECT_LT(kE1, kE2);
3918 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3919 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
3922 // The version of gcc used in XCode 2.2 has a bug and doesn't allow
3923 // anonymous enums in assertions. Therefore the following test is not
3925 // Sun Studio and HP aCC also reject this code.
3926 #if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3928 // Tests using assertions with anonymous enums.
3934 // We want to test the case where the size of the anonymous enum is
3935 // larger than sizeof(int), to make sure our implementation of the
3936 // assertions doesn't truncate the enums. However, MSVC
3937 // (incorrectly) doesn't allow an enum value to exceed the range of
3938 // an int, so this has to be conditionally compiled.
3940 // On Linux, kCaseB and kCaseA have the same value when truncated to
3941 // int size. We want to test whether this will confuse the
3943 kCaseB = testing::internal::kMaxBiggestInt,
3949 # endif // GTEST_OS_LINUX
3954 TEST(AssertionTest, AnonymousEnum) {
3957 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
3959 # endif // GTEST_OS_LINUX
3961 EXPECT_EQ(kCaseA, kCaseA);
3962 EXPECT_NE(kCaseA, kCaseB);
3963 EXPECT_LT(kCaseA, kCaseB);
3964 EXPECT_LE(kCaseA, kCaseB);
3965 EXPECT_GT(kCaseB, kCaseA);
3966 EXPECT_GE(kCaseA, kCaseA);
3967 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
3968 "(kCaseA) >= (kCaseB)");
3969 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
3972 ASSERT_EQ(kCaseA, kCaseA);
3973 ASSERT_NE(kCaseA, kCaseB);
3974 ASSERT_LT(kCaseA, kCaseB);
3975 ASSERT_LE(kCaseA, kCaseB);
3976 ASSERT_GT(kCaseB, kCaseA);
3977 ASSERT_GE(kCaseA, kCaseA);
3979 # ifndef __BORLANDC__
3981 // ICE's in C++Builder.
3982 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
3983 " kCaseB\n Which is: ");
3984 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3988 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3992 #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
3994 #if GTEST_OS_WINDOWS
3996 static HRESULT UnexpectedHRESULTFailure() {
3997 return E_UNEXPECTED;
4000 static HRESULT OkHRESULTSuccess() {
4004 static HRESULT FalseHRESULTSuccess() {
4008 // HRESULT assertion tests test both zero and non-zero
4009 // success codes as well as failure message for each.
4011 // Windows CE doesn't support message texts.
4012 TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
4013 EXPECT_HRESULT_SUCCEEDED(S_OK);
4014 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
4016 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4017 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4018 " Actual: 0x8000FFFF");
4021 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
4022 ASSERT_HRESULT_SUCCEEDED(S_OK);
4023 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
4025 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4026 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4027 " Actual: 0x8000FFFF");
4030 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
4031 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
4033 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
4034 "Expected: (OkHRESULTSuccess()) fails.\n"
4036 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
4037 "Expected: (FalseHRESULTSuccess()) fails.\n"
4041 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4042 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
4044 # ifndef __BORLANDC__
4046 // ICE's in C++Builder 2007 and 2009.
4047 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4048 "Expected: (OkHRESULTSuccess()) fails.\n"
4052 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4053 "Expected: (FalseHRESULTSuccess()) fails.\n"
4057 // Tests that streaming to the HRESULT macros works.
4058 TEST(HRESULTAssertionTest, Streaming) {
4059 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4060 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4061 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4062 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4064 EXPECT_NONFATAL_FAILURE(
4065 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4066 "expected failure");
4068 # ifndef __BORLANDC__
4070 // ICE's in C++Builder 2007 and 2009.
4071 EXPECT_FATAL_FAILURE(
4072 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4073 "expected failure");
4076 EXPECT_NONFATAL_FAILURE(
4077 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4078 "expected failure");
4080 EXPECT_FATAL_FAILURE(
4081 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4082 "expected failure");
4085 #endif // GTEST_OS_WINDOWS
4088 // Silences warnings: "Condition is always true", "Unreachable code"
4089 # pragma option push -w-ccc -w-rch
4092 // Tests that the assertion macros behave like single statements.
4093 TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4095 ASSERT_TRUE(false) << "This should never be executed; "
4096 "It's a compilation test only.";
4099 EXPECT_FALSE(false);
4109 EXPECT_GT(3, 2) << "";
4112 #if GTEST_HAS_EXCEPTIONS
4113 // Tests that the compiler will not complain about unreachable code in the
4114 // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4115 TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4118 EXPECT_THROW(throw 1, int);
4119 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4120 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4121 EXPECT_NO_THROW(n++);
4122 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4123 EXPECT_ANY_THROW(throw 1);
4124 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4127 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4129 EXPECT_THROW(ThrowNothing(), bool);
4132 EXPECT_THROW(ThrowAnInteger(), int);
4137 EXPECT_NO_THROW(ThrowAnInteger());
4140 EXPECT_NO_THROW(ThrowNothing());
4145 EXPECT_ANY_THROW(ThrowNothing());
4148 EXPECT_ANY_THROW(ThrowAnInteger());
4152 #endif // GTEST_HAS_EXCEPTIONS
4154 TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4156 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4157 << "It's a compilation test only.";
4162 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4167 EXPECT_NO_FATAL_FAILURE(SUCCEED());
4174 ASSERT_NO_FATAL_FAILURE(SUCCEED());
4177 // Tests that the assertion macros work well with switch statements.
4178 TEST(AssertionSyntaxTest, WorksWithSwitch) {
4188 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4190 // Binary assertions are implemented using a different code path
4191 // than the Boolean assertions. Hence we test them separately.
4195 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4203 #if GTEST_HAS_EXCEPTIONS
4205 void ThrowAString() {
4206 throw "std::string";
4209 // Test that the exception assertion macros compile and work with const
4211 TEST(AssertionSyntaxTest, WorksWithConst) {
4212 ASSERT_THROW(ThrowAString(), const char*);
4214 EXPECT_THROW(ThrowAString(), const char*);
4217 #endif // GTEST_HAS_EXCEPTIONS
4223 // Tests that Google Test tracks SUCCEED*.
4224 TEST(SuccessfulAssertionTest, SUCCEED) {
4227 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4230 // Tests that Google Test doesn't track successful EXPECT_*.
4231 TEST(SuccessfulAssertionTest, EXPECT) {
4233 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4236 // Tests that Google Test doesn't track successful EXPECT_STR*.
4237 TEST(SuccessfulAssertionTest, EXPECT_STR) {
4238 EXPECT_STREQ("", "");
4239 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4242 // Tests that Google Test doesn't track successful ASSERT_*.
4243 TEST(SuccessfulAssertionTest, ASSERT) {
4245 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4248 // Tests that Google Test doesn't track successful ASSERT_STR*.
4249 TEST(SuccessfulAssertionTest, ASSERT_STR) {
4250 ASSERT_STREQ("", "");
4251 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4254 } // namespace testing
4258 // Tests the message streaming variation of assertions.
4260 TEST(AssertionWithMessageTest, EXPECT) {
4261 EXPECT_EQ(1, 1) << "This should succeed.";
4262 EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4263 "Expected failure #1");
4264 EXPECT_LE(1, 2) << "This should succeed.";
4265 EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4266 "Expected failure #2.");
4267 EXPECT_GE(1, 0) << "This should succeed.";
4268 EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4269 "Expected failure #3.");
4271 EXPECT_STREQ("1", "1") << "This should succeed.";
4272 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4273 "Expected failure #4.");
4274 EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4275 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4276 "Expected failure #5.");
4278 EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4279 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4280 "Expected failure #6.");
4281 EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4284 TEST(AssertionWithMessageTest, ASSERT) {
4285 ASSERT_EQ(1, 1) << "This should succeed.";
4286 ASSERT_NE(1, 2) << "This should succeed.";
4287 ASSERT_LE(1, 2) << "This should succeed.";
4288 ASSERT_LT(1, 2) << "This should succeed.";
4289 ASSERT_GE(1, 0) << "This should succeed.";
4290 EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4291 "Expected failure.");
4294 TEST(AssertionWithMessageTest, ASSERT_STR) {
4295 ASSERT_STREQ("1", "1") << "This should succeed.";
4296 ASSERT_STRNE("1", "2") << "This should succeed.";
4297 ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4298 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4299 "Expected failure.");
4302 TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4303 ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4304 ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4305 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.", // NOLINT
4307 // To work around a bug in gcc 2.95.0, there is intentionally no
4308 // space after the first comma in the previous statement.
4311 // Tests using ASSERT_FALSE with a streamed message.
4312 TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4313 ASSERT_FALSE(false) << "This shouldn't fail.";
4314 EXPECT_FATAL_FAILURE({ // NOLINT
4315 ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4316 << " evaluates to " << true;
4317 }, "Expected failure");
4320 // Tests using FAIL with a streamed message.
4321 TEST(AssertionWithMessageTest, FAIL) {
4322 EXPECT_FATAL_FAILURE(FAIL() << 0,
4326 // Tests using SUCCEED with a streamed message.
4327 TEST(AssertionWithMessageTest, SUCCEED) {
4328 SUCCEED() << "Success == " << 1;
4331 // Tests using ASSERT_TRUE with a streamed message.
4332 TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4333 ASSERT_TRUE(true) << "This should succeed.";
4334 ASSERT_TRUE(true) << true;
4335 EXPECT_FATAL_FAILURE({ // NOLINT
4336 ASSERT_TRUE(false) << static_cast<const char *>(NULL)
4337 << static_cast<char *>(NULL);
4341 #if GTEST_OS_WINDOWS
4342 // Tests using wide strings in assertion messages.
4343 TEST(AssertionWithMessageTest, WideStringMessage) {
4344 EXPECT_NONFATAL_FAILURE({ // NOLINT
4345 EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4346 }, "This failure is expected.");
4347 EXPECT_FATAL_FAILURE({ // NOLINT
4348 ASSERT_EQ(1, 2) << "This failure is "
4349 << L"expected too.\x8120";
4350 }, "This failure is expected too.");
4352 #endif // GTEST_OS_WINDOWS
4354 // Tests EXPECT_TRUE.
4355 TEST(ExpectTest, EXPECT_TRUE) {
4356 EXPECT_TRUE(true) << "Intentional success";
4357 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4358 "Intentional failure #1.");
4359 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4360 "Intentional failure #2.");
4361 EXPECT_TRUE(2 > 1); // NOLINT
4362 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4366 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4370 // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4371 TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4372 EXPECT_TRUE(ResultIsEven(2));
4373 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4374 "Value of: ResultIsEven(3)\n"
4375 " Actual: false (3 is odd)\n"
4377 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4378 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4379 "Value of: ResultIsEvenNoExplanation(3)\n"
4380 " Actual: false (3 is odd)\n"
4384 // Tests EXPECT_FALSE with a streamed message.
4385 TEST(ExpectTest, EXPECT_FALSE) {
4386 EXPECT_FALSE(2 < 1); // NOLINT
4387 EXPECT_FALSE(false) << "Intentional success";
4388 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4389 "Intentional failure #1.");
4390 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4391 "Intentional failure #2.");
4392 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4396 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4400 // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4401 TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4402 EXPECT_FALSE(ResultIsEven(3));
4403 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4404 "Value of: ResultIsEven(2)\n"
4405 " Actual: true (2 is even)\n"
4407 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4408 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4409 "Value of: ResultIsEvenNoExplanation(2)\n"
4415 // Restores warnings after previous "#pragma option push" suppressed them
4420 TEST(ExpectTest, EXPECT_EQ) {
4421 EXPECT_EQ(5, 2 + 3);
4422 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4423 "Expected equality of these values:\n"
4427 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4431 // Tests using EXPECT_EQ on double values. The purpose is to make
4432 // sure that the specialization we did for integer and anonymous enums
4433 // isn't used for double arguments.
4434 TEST(ExpectTest, EXPECT_EQ_Double) {
4436 EXPECT_EQ(5.6, 5.6);
4439 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4443 #if GTEST_CAN_COMPARE_NULL
4444 // Tests EXPECT_EQ(NULL, pointer).
4445 TEST(ExpectTest, EXPECT_EQ_NULL) {
4447 const char* p = NULL;
4448 // Some older GCC versions may issue a spurious warning in this or the next
4449 // assertion statement. This warning should not be suppressed with
4450 // static_cast since the test verifies the ability to use bare NULL as the
4451 // expected parameter to the macro.
4456 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
4459 #endif // GTEST_CAN_COMPARE_NULL
4461 // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4462 // treated as a null pointer by the compiler, we need to make sure
4463 // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4464 // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4465 TEST(ExpectTest, EXPECT_EQ_0) {
4472 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4477 TEST(ExpectTest, EXPECT_NE) {
4480 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4481 "Expected: ('a') != ('a'), "
4482 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4483 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4485 char* const p0 = NULL;
4486 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4488 // Only way to get the Nokia compiler to compile the cast
4489 // is to have a separate void* variable first. Putting
4490 // the two casts on the same line doesn't work, neither does
4491 // a direct C-style to char*.
4492 void* pv1 = (void*)0x1234; // NOLINT
4493 char* const p1 = reinterpret_cast<char*>(pv1);
4494 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4499 TEST(ExpectTest, EXPECT_LE) {
4502 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4503 "Expected: (2) <= (0), actual: 2 vs 0");
4504 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4509 TEST(ExpectTest, EXPECT_LT) {
4511 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4512 "Expected: (2) < (2), actual: 2 vs 2");
4513 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4518 TEST(ExpectTest, EXPECT_GE) {
4521 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4522 "Expected: (2) >= (3), actual: 2 vs 3");
4523 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4528 TEST(ExpectTest, EXPECT_GT) {
4530 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4531 "Expected: (2) > (2), actual: 2 vs 2");
4532 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4536 #if GTEST_HAS_EXCEPTIONS
4538 // Tests EXPECT_THROW.
4539 TEST(ExpectTest, EXPECT_THROW) {
4540 EXPECT_THROW(ThrowAnInteger(), int);
4541 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4542 "Expected: ThrowAnInteger() throws an exception of "
4543 "type bool.\n Actual: it throws a different type.");
4544 EXPECT_NONFATAL_FAILURE(
4545 EXPECT_THROW(ThrowNothing(), bool),
4546 "Expected: ThrowNothing() throws an exception of type bool.\n"
4547 " Actual: it throws nothing.");
4550 // Tests EXPECT_NO_THROW.
4551 TEST(ExpectTest, EXPECT_NO_THROW) {
4552 EXPECT_NO_THROW(ThrowNothing());
4553 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4554 "Expected: ThrowAnInteger() doesn't throw an "
4555 "exception.\n Actual: it throws.");
4558 // Tests EXPECT_ANY_THROW.
4559 TEST(ExpectTest, EXPECT_ANY_THROW) {
4560 EXPECT_ANY_THROW(ThrowAnInteger());
4561 EXPECT_NONFATAL_FAILURE(
4562 EXPECT_ANY_THROW(ThrowNothing()),
4563 "Expected: ThrowNothing() throws an exception.\n"
4564 " Actual: it doesn't.");
4567 #endif // GTEST_HAS_EXCEPTIONS
4569 // Make sure we deal with the precedence of <<.
4570 TEST(ExpectTest, ExpectPrecedence) {
4571 EXPECT_EQ(1 < 2, true);
4572 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4573 " true && false\n Which is: false");
4577 // Tests the StreamableToString() function.
4579 // Tests using StreamableToString() on a scalar.
4580 TEST(StreamableToStringTest, Scalar) {
4581 EXPECT_STREQ("5", StreamableToString(5).c_str());
4584 // Tests using StreamableToString() on a non-char pointer.
4585 TEST(StreamableToStringTest, Pointer) {
4588 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4591 // Tests using StreamableToString() on a NULL non-char pointer.
4592 TEST(StreamableToStringTest, NullPointer) {
4594 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4597 // Tests using StreamableToString() on a C string.
4598 TEST(StreamableToStringTest, CString) {
4599 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4602 // Tests using StreamableToString() on a NULL C string.
4603 TEST(StreamableToStringTest, NullCString) {
4605 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4608 // Tests using streamable values as assertion messages.
4610 // Tests using std::string as an assertion message.
4611 TEST(StreamableTest, string) {
4612 static const std::string str(
4613 "This failure message is a std::string, and is expected.");
4614 EXPECT_FATAL_FAILURE(FAIL() << str,
4618 // Tests that we can output strings containing embedded NULs.
4619 // Limited to Linux because we can only do this with std::string's.
4620 TEST(StreamableTest, stringWithEmbeddedNUL) {
4621 static const char char_array_with_nul[] =
4622 "Here's a NUL\0 and some more string";
4623 static const std::string string_with_nul(char_array_with_nul,
4624 sizeof(char_array_with_nul)
4625 - 1); // drops the trailing NUL
4626 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4627 "Here's a NUL\\0 and some more string");
4630 // Tests that we can output a NUL char.
4631 TEST(StreamableTest, NULChar) {
4632 EXPECT_FATAL_FAILURE({ // NOLINT
4633 FAIL() << "A NUL" << '\0' << " and some more string";
4634 }, "A NUL\\0 and some more string");
4637 // Tests using int as an assertion message.
4638 TEST(StreamableTest, int) {
4639 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4643 // Tests using NULL char pointer as an assertion message.
4645 // In MSVC, streaming a NULL char * causes access violation. Google Test
4646 // implemented a workaround (substituting "(null)" for NULL). This
4647 // tests whether the workaround works.
4648 TEST(StreamableTest, NullCharPtr) {
4649 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4653 // Tests that basic IO manipulators (endl, ends, and flush) can be
4654 // streamed to testing::Message.
4655 TEST(StreamableTest, BasicIoManip) {
4656 EXPECT_FATAL_FAILURE({ // NOLINT
4657 FAIL() << "Line 1." << std::endl
4658 << "A NUL char " << std::ends << std::flush << " in line 2.";
4659 }, "Line 1.\nA NUL char \\0 in line 2.");
4662 // Tests the macros that haven't been covered so far.
4664 void AddFailureHelper(bool* aborted) {
4666 ADD_FAILURE() << "Intentional failure.";
4670 // Tests ADD_FAILURE.
4671 TEST(MacroTest, ADD_FAILURE) {
4672 bool aborted = true;
4673 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4674 "Intentional failure.");
4675 EXPECT_FALSE(aborted);
4678 // Tests ADD_FAILURE_AT.
4679 TEST(MacroTest, ADD_FAILURE_AT) {
4680 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4681 // the failure message contains the user-streamed part.
4682 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4684 // Verifies that the user-streamed part is optional.
4685 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4687 // Unfortunately, we cannot verify that the failure message contains
4688 // the right file path and line number the same way, as
4689 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4690 // line number. Instead, we do that in googletest-output-test_.cc.
4694 TEST(MacroTest, FAIL) {
4695 EXPECT_FATAL_FAILURE(FAIL(),
4697 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4698 "Intentional failure.");
4702 TEST(MacroTest, SUCCEED) {
4704 SUCCEED() << "Explicit success.";
4707 // Tests for EXPECT_EQ() and ASSERT_EQ().
4709 // These tests fail *intentionally*, s.t. the failure messages can be
4710 // generated and tested.
4712 // We have different tests for different argument types.
4714 // Tests using bool values in {EXPECT|ASSERT}_EQ.
4715 TEST(EqAssertionTest, Bool) {
4716 EXPECT_EQ(true, true);
4717 EXPECT_FATAL_FAILURE({
4718 bool false_value = false;
4719 ASSERT_EQ(false_value, true);
4720 }, " false_value\n Which is: false\n true");
4723 // Tests using int values in {EXPECT|ASSERT}_EQ.
4724 TEST(EqAssertionTest, Int) {
4726 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4730 // Tests using time_t values in {EXPECT|ASSERT}_EQ.
4731 TEST(EqAssertionTest, Time_T) {
4732 EXPECT_EQ(static_cast<time_t>(0),
4733 static_cast<time_t>(0));
4734 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4735 static_cast<time_t>(1234)),
4739 // Tests using char values in {EXPECT|ASSERT}_EQ.
4740 TEST(EqAssertionTest, Char) {
4741 ASSERT_EQ('z', 'z');
4742 const char ch = 'b';
4743 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4744 " ch\n Which is: 'b'");
4745 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4746 " ch\n Which is: 'b'");
4749 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4750 TEST(EqAssertionTest, WideChar) {
4751 EXPECT_EQ(L'b', L'b');
4753 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4754 "Expected equality of these values:\n"
4756 " Which is: L'\0' (0, 0x0)\n"
4758 " Which is: L'x' (120, 0x78)");
4760 static wchar_t wchar;
4762 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4765 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
4766 " wchar\n Which is: L'");
4769 // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4770 TEST(EqAssertionTest, StdString) {
4771 // Compares a const char* to an std::string that has identical
4773 ASSERT_EQ("Test", ::std::string("Test"));
4775 // Compares two identical std::strings.
4776 static const ::std::string str1("A * in the middle");
4777 static const ::std::string str2(str1);
4778 EXPECT_EQ(str1, str2);
4780 // Compares a const char* to an std::string that has different
4782 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4785 // Compares an std::string to a char* that has different content.
4786 char* const p1 = const_cast<char*>("foo");
4787 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4790 // Compares two std::strings that have different contents, one of
4791 // which having a NUL character in the middle. This should fail.
4792 static ::std::string str3(str1);
4794 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4795 " str3\n Which is: \"A \\0 in the middle\"");
4798 #if GTEST_HAS_STD_WSTRING
4800 // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4801 TEST(EqAssertionTest, StdWideString) {
4802 // Compares two identical std::wstrings.
4803 const ::std::wstring wstr1(L"A * in the middle");
4804 const ::std::wstring wstr2(wstr1);
4805 ASSERT_EQ(wstr1, wstr2);
4807 // Compares an std::wstring to a const wchar_t* that has identical
4809 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4810 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4812 // Compares an std::wstring to a const wchar_t* that has different
4814 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4815 EXPECT_NONFATAL_FAILURE({ // NOLINT
4816 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4819 // Compares two std::wstrings that have different contents, one of
4820 // which having a NUL character in the middle.
4821 ::std::wstring wstr3(wstr1);
4822 wstr3.at(2) = L'\0';
4823 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4826 // Compares a wchar_t* to an std::wstring that has different
4828 EXPECT_FATAL_FAILURE({ // NOLINT
4829 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4833 #endif // GTEST_HAS_STD_WSTRING
4835 #if GTEST_HAS_GLOBAL_STRING
4836 // Tests using ::string values in {EXPECT|ASSERT}_EQ.
4837 TEST(EqAssertionTest, GlobalString) {
4838 // Compares a const char* to a ::string that has identical content.
4839 EXPECT_EQ("Test", ::string("Test"));
4841 // Compares two identical ::strings.
4842 const ::string str1("A * in the middle");
4843 const ::string str2(str1);
4844 ASSERT_EQ(str1, str2);
4846 // Compares a ::string to a const char* that has different content.
4847 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4850 // Compares two ::strings that have different contents, one of which
4851 // having a NUL character in the middle.
4852 ::string str3(str1);
4854 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4857 // Compares a ::string to a char* that has different content.
4858 EXPECT_FATAL_FAILURE({ // NOLINT
4859 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4863 #endif // GTEST_HAS_GLOBAL_STRING
4865 #if GTEST_HAS_GLOBAL_WSTRING
4867 // Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4868 TEST(EqAssertionTest, GlobalWideString) {
4869 // Compares two identical ::wstrings.
4870 static const ::wstring wstr1(L"A * in the middle");
4871 static const ::wstring wstr2(wstr1);
4872 EXPECT_EQ(wstr1, wstr2);
4874 // Compares a const wchar_t* to a ::wstring that has identical content.
4875 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4876 ASSERT_EQ(kTestX8119, ::wstring(kTestX8119));
4878 // Compares a const wchar_t* to a ::wstring that has different
4880 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4881 EXPECT_NONFATAL_FAILURE({ // NOLINT
4882 EXPECT_EQ(kTestX8120, ::wstring(kTestX8119));
4885 // Compares a wchar_t* to a ::wstring that has different content.
4886 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4887 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4890 // Compares two ::wstrings that have different contents, one of which
4891 // having a NUL character in the middle.
4892 static ::wstring wstr3;
4894 wstr3.at(2) = L'\0';
4895 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4899 #endif // GTEST_HAS_GLOBAL_WSTRING
4901 // Tests using char pointers in {EXPECT|ASSERT}_EQ.
4902 TEST(EqAssertionTest, CharPointer) {
4903 char* const p0 = NULL;
4904 // Only way to get the Nokia compiler to compile the cast
4905 // is to have a separate void* variable first. Putting
4906 // the two casts on the same line doesn't work, neither does
4907 // a direct C-style to char*.
4908 void* pv1 = (void*)0x1234; // NOLINT
4909 void* pv2 = (void*)0xABC0; // NOLINT
4910 char* const p1 = reinterpret_cast<char*>(pv1);
4911 char* const p2 = reinterpret_cast<char*>(pv2);
4914 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4916 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4918 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4919 reinterpret_cast<char*>(0xABC0)),
4923 // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4924 TEST(EqAssertionTest, WideCharPointer) {
4925 wchar_t* const p0 = NULL;
4926 // Only way to get the Nokia compiler to compile the cast
4927 // is to have a separate void* variable first. Putting
4928 // the two casts on the same line doesn't work, neither does
4929 // a direct C-style to char*.
4930 void* pv1 = (void*)0x1234; // NOLINT
4931 void* pv2 = (void*)0xABC0; // NOLINT
4932 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4933 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4936 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4938 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4940 void* pv3 = (void*)0x1234; // NOLINT
4941 void* pv4 = (void*)0xABC0; // NOLINT
4942 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4943 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4944 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4948 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4949 TEST(EqAssertionTest, OtherPointer) {
4950 ASSERT_EQ(static_cast<const int*>(NULL),
4951 static_cast<const int*>(NULL));
4952 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4953 reinterpret_cast<const int*>(0x1234)),
4957 // A class that supports binary comparison operators but not streaming.
4958 class UnprintableChar {
4960 explicit UnprintableChar(char ch) : char_(ch) {}
4962 bool operator==(const UnprintableChar& rhs) const {
4963 return char_ == rhs.char_;
4965 bool operator!=(const UnprintableChar& rhs) const {
4966 return char_ != rhs.char_;
4968 bool operator<(const UnprintableChar& rhs) const {
4969 return char_ < rhs.char_;
4971 bool operator<=(const UnprintableChar& rhs) const {
4972 return char_ <= rhs.char_;
4974 bool operator>(const UnprintableChar& rhs) const {
4975 return char_ > rhs.char_;
4977 bool operator>=(const UnprintableChar& rhs) const {
4978 return char_ >= rhs.char_;
4985 // Tests that ASSERT_EQ() and friends don't require the arguments to
4987 TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4988 const UnprintableChar x('x'), y('y');
4996 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
4997 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
4998 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
4999 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
5000 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
5002 // Code tested by EXPECT_FATAL_FAILURE cannot reference local
5003 // variables, so we have to write UnprintableChar('x') instead of x.
5004 #ifndef __BORLANDC__
5005 // ICE's in C++Builder.
5006 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
5007 "1-byte object <78>");
5008 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
5009 "1-byte object <78>");
5011 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
5012 "1-byte object <79>");
5013 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
5014 "1-byte object <78>");
5015 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
5016 "1-byte object <79>");
5019 // Tests the FRIEND_TEST macro.
5021 // This class has a private member we want to test. We will test it
5022 // both in a TEST and in a TEST_F.
5028 int Bar() const { return 1; }
5030 // Declares the friend tests that can access the private member
5032 FRIEND_TEST(FRIEND_TEST_Test, TEST);
5033 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
5036 // Tests that the FRIEND_TEST declaration allows a TEST to access a
5037 // class's private members. This should compile.
5038 TEST(FRIEND_TEST_Test, TEST) {
5039 ASSERT_EQ(1, Foo().Bar());
5042 // The fixture needed to test using FRIEND_TEST with TEST_F.
5043 class FRIEND_TEST_Test2 : public Test {
5048 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
5049 // class's private members. This should compile.
5050 TEST_F(FRIEND_TEST_Test2, TEST_F) {
5051 ASSERT_EQ(1, foo.Bar());
5054 // Tests the life cycle of Test objects.
5056 // The test fixture for testing the life cycle of Test objects.
5058 // This class counts the number of live test objects that uses this
5060 class TestLifeCycleTest : public Test {
5062 // Constructor. Increments the number of test objects that uses
5064 TestLifeCycleTest() { count_++; }
5066 // Destructor. Decrements the number of test objects that uses this
5068 ~TestLifeCycleTest() { count_--; }
5070 // Returns the number of live test objects that uses this fixture.
5071 int count() const { return count_; }
5077 int TestLifeCycleTest::count_ = 0;
5079 // Tests the life cycle of test objects.
5080 TEST_F(TestLifeCycleTest, Test1) {
5081 // There should be only one test object in this test case that's
5083 ASSERT_EQ(1, count());
5086 // Tests the life cycle of test objects.
5087 TEST_F(TestLifeCycleTest, Test2) {
5088 // After Test1 is done and Test2 is started, there should still be
5089 // only one live test object, as the object for Test1 should've been
5091 ASSERT_EQ(1, count());
5096 // Tests that the copy constructor works when it is NOT optimized away by
5098 TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5099 // Checks that the copy constructor doesn't try to dereference NULL pointers
5100 // in the source object.
5101 AssertionResult r1 = AssertionSuccess();
5102 AssertionResult r2 = r1;
5103 // The following line is added to prevent the compiler from optimizing
5104 // away the constructor call.
5107 AssertionResult r3 = r1;
5108 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
5109 EXPECT_STREQ("abc", r1.message());
5112 // Tests that AssertionSuccess and AssertionFailure construct
5113 // AssertionResult objects as expected.
5114 TEST(AssertionResultTest, ConstructionWorks) {
5115 AssertionResult r1 = AssertionSuccess();
5117 EXPECT_STREQ("", r1.message());
5119 AssertionResult r2 = AssertionSuccess() << "abc";
5121 EXPECT_STREQ("abc", r2.message());
5123 AssertionResult r3 = AssertionFailure();
5125 EXPECT_STREQ("", r3.message());
5127 AssertionResult r4 = AssertionFailure() << "def";
5129 EXPECT_STREQ("def", r4.message());
5131 AssertionResult r5 = AssertionFailure(Message() << "ghi");
5133 EXPECT_STREQ("ghi", r5.message());
5136 // Tests that the negation flips the predicate result but keeps the message.
5137 TEST(AssertionResultTest, NegationWorks) {
5138 AssertionResult r1 = AssertionSuccess() << "abc";
5140 EXPECT_STREQ("abc", (!r1).message());
5142 AssertionResult r2 = AssertionFailure() << "def";
5144 EXPECT_STREQ("def", (!r2).message());
5147 TEST(AssertionResultTest, StreamingWorks) {
5148 AssertionResult r = AssertionSuccess();
5149 r << "abc" << 'd' << 0 << true;
5150 EXPECT_STREQ("abcd0true", r.message());
5153 TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5154 AssertionResult r = AssertionSuccess();
5155 r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5156 EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5159 // The next test uses explicit conversion operators -- a C++11 feature.
5160 #if GTEST_LANG_CXX11
5162 TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5163 struct ExplicitlyConvertibleToBool {
5164 explicit operator bool() const { return value; }
5167 ExplicitlyConvertibleToBool v1 = {false};
5168 ExplicitlyConvertibleToBool v2 = {true};
5173 #endif // GTEST_LANG_CXX11
5175 struct ConvertibleToAssertionResult {
5176 operator AssertionResult() const { return AssertionResult(true); }
5179 TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5180 ConvertibleToAssertionResult obj;
5184 // Tests streaming a user type whose definition and operator << are
5185 // both in the global namespace.
5188 explicit Base(int an_x) : x_(an_x) {}
5189 int x() const { return x_; }
5193 std::ostream& operator<<(std::ostream& os,
5195 return os << val.x();
5197 std::ostream& operator<<(std::ostream& os,
5198 const Base* pointer) {
5199 return os << "(" << pointer->x() << ")";
5202 TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5206 msg << a << &a; // Uses ::operator<<.
5207 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5210 // Tests streaming a user type whose definition and operator<< are
5211 // both in an unnamed namespace.
5213 class MyTypeInUnnamedNameSpace : public Base {
5215 explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
5217 std::ostream& operator<<(std::ostream& os,
5218 const MyTypeInUnnamedNameSpace& val) {
5219 return os << val.x();
5221 std::ostream& operator<<(std::ostream& os,
5222 const MyTypeInUnnamedNameSpace* pointer) {
5223 return os << "(" << pointer->x() << ")";
5227 TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5229 MyTypeInUnnamedNameSpace a(1);
5231 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
5232 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5235 // Tests streaming a user type whose definition and operator<< are
5236 // both in a user namespace.
5237 namespace namespace1 {
5238 class MyTypeInNameSpace1 : public Base {
5240 explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
5242 std::ostream& operator<<(std::ostream& os,
5243 const MyTypeInNameSpace1& val) {
5244 return os << val.x();
5246 std::ostream& operator<<(std::ostream& os,
5247 const MyTypeInNameSpace1* pointer) {
5248 return os << "(" << pointer->x() << ")";
5250 } // namespace namespace1
5252 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5254 namespace1::MyTypeInNameSpace1 a(1);
5256 msg << a << &a; // Uses namespace1::operator<<.
5257 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5260 // Tests streaming a user type whose definition is in a user namespace
5261 // but whose operator<< is in the global namespace.
5262 namespace namespace2 {
5263 class MyTypeInNameSpace2 : public ::Base {
5265 explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
5267 } // namespace namespace2
5268 std::ostream& operator<<(std::ostream& os,
5269 const namespace2::MyTypeInNameSpace2& val) {
5270 return os << val.x();
5272 std::ostream& operator<<(std::ostream& os,
5273 const namespace2::MyTypeInNameSpace2* pointer) {
5274 return os << "(" << pointer->x() << ")";
5277 TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5279 namespace2::MyTypeInNameSpace2 a(1);
5281 msg << a << &a; // Uses ::operator<<.
5282 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5285 // Tests streaming NULL pointers to testing::Message.
5286 TEST(MessageTest, NullPointers) {
5288 char* const p1 = NULL;
5289 unsigned char* const p2 = NULL;
5295 msg << p1 << p2 << p3 << p4 << p5 << p6;
5296 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5297 msg.GetString().c_str());
5300 // Tests streaming wide strings to testing::Message.
5301 TEST(MessageTest, WideStrings) {
5302 // Streams a NULL of type const wchar_t*.
5303 const wchar_t* const_wstr = NULL;
5304 EXPECT_STREQ("(null)",
5305 (Message() << const_wstr).GetString().c_str());
5307 // Streams a NULL of type wchar_t*.
5308 wchar_t* wstr = NULL;
5309 EXPECT_STREQ("(null)",
5310 (Message() << wstr).GetString().c_str());
5312 // Streams a non-NULL of type const wchar_t*.
5313 const_wstr = L"abc\x8119";
5314 EXPECT_STREQ("abc\xe8\x84\x99",
5315 (Message() << const_wstr).GetString().c_str());
5317 // Streams a non-NULL of type wchar_t*.
5318 wstr = const_cast<wchar_t*>(const_wstr);
5319 EXPECT_STREQ("abc\xe8\x84\x99",
5320 (Message() << wstr).GetString().c_str());
5324 // This line tests that we can define tests in the testing namespace.
5327 // Tests the TestInfo class.
5329 class TestInfoTest : public Test {
5331 static const TestInfo* GetTestInfo(const char* test_name) {
5332 const TestCase* const test_case = GetUnitTestImpl()->
5333 GetTestCase("TestInfoTest", "", NULL, NULL);
5335 for (int i = 0; i < test_case->total_test_count(); ++i) {
5336 const TestInfo* const test_info = test_case->GetTestInfo(i);
5337 if (strcmp(test_name, test_info->name()) == 0)
5343 static const TestResult* GetTestResult(
5344 const TestInfo* test_info) {
5345 return test_info->result();
5349 // Tests TestInfo::test_case_name() and TestInfo::name().
5350 TEST_F(TestInfoTest, Names) {
5351 const TestInfo* const test_info = GetTestInfo("Names");
5353 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
5354 ASSERT_STREQ("Names", test_info->name());
5357 // Tests TestInfo::result().
5358 TEST_F(TestInfoTest, result) {
5359 const TestInfo* const test_info = GetTestInfo("result");
5361 // Initially, there is no TestPartResult for this test.
5362 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5364 // After the previous assertion, there is still none.
5365 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5368 #define VERIFY_CODE_LOCATION \
5369 const int expected_line = __LINE__ - 1; \
5370 const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
5371 ASSERT_TRUE(test_info); \
5372 EXPECT_STREQ(__FILE__, test_info->file()); \
5373 EXPECT_EQ(expected_line, test_info->line())
5375 TEST(CodeLocationForTEST, Verify) {
5376 VERIFY_CODE_LOCATION;
5379 class CodeLocationForTESTF : public Test {
5382 TEST_F(CodeLocationForTESTF, Verify) {
5383 VERIFY_CODE_LOCATION;
5386 class CodeLocationForTESTP : public TestWithParam<int> {
5389 TEST_P(CodeLocationForTESTP, Verify) {
5390 VERIFY_CODE_LOCATION;
5393 INSTANTIATE_TEST_CASE_P(, CodeLocationForTESTP, Values(0));
5395 template <typename T>
5396 class CodeLocationForTYPEDTEST : public Test {
5399 TYPED_TEST_CASE(CodeLocationForTYPEDTEST, int);
5401 TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
5402 VERIFY_CODE_LOCATION;
5405 template <typename T>
5406 class CodeLocationForTYPEDTESTP : public Test {
5409 TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP);
5411 TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
5412 VERIFY_CODE_LOCATION;
5415 REGISTER_TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP, Verify);
5417 INSTANTIATE_TYPED_TEST_CASE_P(My, CodeLocationForTYPEDTESTP, int);
5419 #undef VERIFY_CODE_LOCATION
5421 // Tests setting up and tearing down a test case.
5423 class SetUpTestCaseTest : public Test {
5425 // This will be called once before the first test in this test case
5427 static void SetUpTestCase() {
5428 printf("Setting up the test case . . .\n");
5430 // Initializes some shared resource. In this simple example, we
5431 // just create a C string. More complex stuff can be done if
5433 shared_resource_ = "123";
5435 // Increments the number of test cases that have been set up.
5438 // SetUpTestCase() should be called only once.
5439 EXPECT_EQ(1, counter_);
5442 // This will be called once after the last test in this test case is
5444 static void TearDownTestCase() {
5445 printf("Tearing down the test case . . .\n");
5447 // Decrements the number of test cases that have been set up.
5450 // TearDownTestCase() should be called only once.
5451 EXPECT_EQ(0, counter_);
5453 // Cleans up the shared resource.
5454 shared_resource_ = NULL;
5457 // This will be called before each test in this test case.
5458 virtual void SetUp() {
5459 // SetUpTestCase() should be called only once, so counter_ should
5461 EXPECT_EQ(1, counter_);
5464 // Number of test cases that have been set up.
5465 static int counter_;
5467 // Some resource to be shared by all tests in this test case.
5468 static const char* shared_resource_;
5471 int SetUpTestCaseTest::counter_ = 0;
5472 const char* SetUpTestCaseTest::shared_resource_ = NULL;
5474 // A test that uses the shared resource.
5475 TEST_F(SetUpTestCaseTest, Test1) {
5476 EXPECT_STRNE(NULL, shared_resource_);
5479 // Another test that uses the shared resource.
5480 TEST_F(SetUpTestCaseTest, Test2) {
5481 EXPECT_STREQ("123", shared_resource_);
5485 // The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.
5487 // The Flags struct stores a copy of all Google Test flags.
5489 // Constructs a Flags struct where each flag has its default value.
5490 Flags() : also_run_disabled_tests(false),
5491 break_on_failure(false),
5492 catch_exceptions(false),
5493 death_test_use_fork(false),
5501 stack_trace_depth(kMaxStackTraceDepth),
5502 stream_result_to(""),
5503 throw_on_failure(false) {}
5507 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5509 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5511 flags.also_run_disabled_tests = also_run_disabled_tests;
5515 // Creates a Flags struct where the gtest_break_on_failure flag has
5517 static Flags BreakOnFailure(bool break_on_failure) {
5519 flags.break_on_failure = break_on_failure;
5523 // Creates a Flags struct where the gtest_catch_exceptions flag has
5525 static Flags CatchExceptions(bool catch_exceptions) {
5527 flags.catch_exceptions = catch_exceptions;
5531 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5533 static Flags DeathTestUseFork(bool death_test_use_fork) {
5535 flags.death_test_use_fork = death_test_use_fork;
5539 // Creates a Flags struct where the gtest_filter flag has the given
5541 static Flags Filter(const char* filter) {
5543 flags.filter = filter;
5547 // Creates a Flags struct where the gtest_list_tests flag has the
5549 static Flags ListTests(bool list_tests) {
5551 flags.list_tests = list_tests;
5555 // Creates a Flags struct where the gtest_output flag has the given
5557 static Flags Output(const char* output) {
5559 flags.output = output;
5563 // Creates a Flags struct where the gtest_print_time flag has the given
5565 static Flags PrintTime(bool print_time) {
5567 flags.print_time = print_time;
5571 // Creates a Flags struct where the gtest_random_seed flag has the given
5573 static Flags RandomSeed(Int32 random_seed) {
5575 flags.random_seed = random_seed;
5579 // Creates a Flags struct where the gtest_repeat flag has the given
5581 static Flags Repeat(Int32 repeat) {
5583 flags.repeat = repeat;
5587 // Creates a Flags struct where the gtest_shuffle flag has the given
5589 static Flags Shuffle(bool shuffle) {
5591 flags.shuffle = shuffle;
5595 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5597 static Flags StackTraceDepth(Int32 stack_trace_depth) {
5599 flags.stack_trace_depth = stack_trace_depth;
5603 // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5605 static Flags StreamResultTo(const char* stream_result_to) {
5607 flags.stream_result_to = stream_result_to;
5611 // Creates a Flags struct where the gtest_throw_on_failure flag has
5613 static Flags ThrowOnFailure(bool throw_on_failure) {
5615 flags.throw_on_failure = throw_on_failure;
5619 // These fields store the flag values.
5620 bool also_run_disabled_tests;
5621 bool break_on_failure;
5622 bool catch_exceptions;
5623 bool death_test_use_fork;
5631 Int32 stack_trace_depth;
5632 const char* stream_result_to;
5633 bool throw_on_failure;
5636 // Fixture for testing ParseGoogleTestFlagsOnly().
5637 class ParseFlagsTest : public Test {
5639 // Clears the flags before each test.
5640 virtual void SetUp() {
5641 GTEST_FLAG(also_run_disabled_tests) = false;
5642 GTEST_FLAG(break_on_failure) = false;
5643 GTEST_FLAG(catch_exceptions) = false;
5644 GTEST_FLAG(death_test_use_fork) = false;
5645 GTEST_FLAG(filter) = "";
5646 GTEST_FLAG(list_tests) = false;
5647 GTEST_FLAG(output) = "";
5648 GTEST_FLAG(print_time) = true;
5649 GTEST_FLAG(random_seed) = 0;
5650 GTEST_FLAG(repeat) = 1;
5651 GTEST_FLAG(shuffle) = false;
5652 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
5653 GTEST_FLAG(stream_result_to) = "";
5654 GTEST_FLAG(throw_on_failure) = false;
5657 // Asserts that two narrow or wide string arrays are equal.
5658 template <typename CharType>
5659 static void AssertStringArrayEq(size_t size1, CharType** array1,
5660 size_t size2, CharType** array2) {
5661 ASSERT_EQ(size1, size2) << " Array sizes different.";
5663 for (size_t i = 0; i != size1; i++) {
5664 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5668 // Verifies that the flag values match the expected values.
5669 static void CheckFlags(const Flags& expected) {
5670 EXPECT_EQ(expected.also_run_disabled_tests,
5671 GTEST_FLAG(also_run_disabled_tests));
5672 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5673 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
5674 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
5675 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5676 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5677 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
5678 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
5679 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
5680 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
5681 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
5682 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
5683 EXPECT_STREQ(expected.stream_result_to,
5684 GTEST_FLAG(stream_result_to).c_str());
5685 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
5688 // Parses a command line (specified by argc1 and argv1), then
5689 // verifies that the flag values are expected and that the
5690 // recognized flags are removed from the command line.
5691 template <typename CharType>
5692 static void TestParsingFlags(int argc1, const CharType** argv1,
5693 int argc2, const CharType** argv2,
5694 const Flags& expected, bool should_print_help) {
5695 const bool saved_help_flag = ::testing::internal::g_help_flag;
5696 ::testing::internal::g_help_flag = false;
5698 # if GTEST_HAS_STREAM_REDIRECTION
5702 // Parses the command line.
5703 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5705 # if GTEST_HAS_STREAM_REDIRECTION
5706 const std::string captured_stdout = GetCapturedStdout();
5709 // Verifies the flag values.
5710 CheckFlags(expected);
5712 // Verifies that the recognized flags are removed from the command
5714 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5716 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5717 // help message for the flags it recognizes.
5718 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5720 # if GTEST_HAS_STREAM_REDIRECTION
5721 const char* const expected_help_fragment =
5722 "This program contains tests written using";
5723 if (should_print_help) {
5724 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5726 EXPECT_PRED_FORMAT2(IsNotSubstring,
5727 expected_help_fragment, captured_stdout);
5729 # endif // GTEST_HAS_STREAM_REDIRECTION
5731 ::testing::internal::g_help_flag = saved_help_flag;
5734 // This macro wraps TestParsingFlags s.t. the user doesn't need
5735 // to specify the array sizes.
5737 # define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5738 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5739 sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5740 expected, should_print_help)
5743 // Tests parsing an empty command line.
5744 TEST_F(ParseFlagsTest, Empty) {
5745 const char* argv[] = {
5749 const char* argv2[] = {
5753 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5756 // Tests parsing a command line that has no flag.
5757 TEST_F(ParseFlagsTest, NoFlag) {
5758 const char* argv[] = {
5763 const char* argv2[] = {
5768 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5771 // Tests parsing a bad --gtest_filter flag.
5772 TEST_F(ParseFlagsTest, FilterBad) {
5773 const char* argv[] = {
5779 const char* argv2[] = {
5785 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
5788 // Tests parsing an empty --gtest_filter flag.
5789 TEST_F(ParseFlagsTest, FilterEmpty) {
5790 const char* argv[] = {
5796 const char* argv2[] = {
5801 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5804 // Tests parsing a non-empty --gtest_filter flag.
5805 TEST_F(ParseFlagsTest, FilterNonEmpty) {
5806 const char* argv[] = {
5808 "--gtest_filter=abc",
5812 const char* argv2[] = {
5817 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5820 // Tests parsing --gtest_break_on_failure.
5821 TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {
5822 const char* argv[] = {
5824 "--gtest_break_on_failure",
5828 const char* argv2[] = {
5833 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5836 // Tests parsing --gtest_break_on_failure=0.
5837 TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {
5838 const char* argv[] = {
5840 "--gtest_break_on_failure=0",
5844 const char* argv2[] = {
5849 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5852 // Tests parsing --gtest_break_on_failure=f.
5853 TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {
5854 const char* argv[] = {
5856 "--gtest_break_on_failure=f",
5860 const char* argv2[] = {
5865 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5868 // Tests parsing --gtest_break_on_failure=F.
5869 TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {
5870 const char* argv[] = {
5872 "--gtest_break_on_failure=F",
5876 const char* argv2[] = {
5881 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5884 // Tests parsing a --gtest_break_on_failure flag that has a "true"
5886 TEST_F(ParseFlagsTest, BreakOnFailureTrue) {
5887 const char* argv[] = {
5889 "--gtest_break_on_failure=1",
5893 const char* argv2[] = {
5898 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5901 // Tests parsing --gtest_catch_exceptions.
5902 TEST_F(ParseFlagsTest, CatchExceptions) {
5903 const char* argv[] = {
5905 "--gtest_catch_exceptions",
5909 const char* argv2[] = {
5914 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5917 // Tests parsing --gtest_death_test_use_fork.
5918 TEST_F(ParseFlagsTest, DeathTestUseFork) {
5919 const char* argv[] = {
5921 "--gtest_death_test_use_fork",
5925 const char* argv2[] = {
5930 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5933 // Tests having the same flag twice with different values. The
5934 // expected behavior is that the one coming last takes precedence.
5935 TEST_F(ParseFlagsTest, DuplicatedFlags) {
5936 const char* argv[] = {
5943 const char* argv2[] = {
5948 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5951 // Tests having an unrecognized flag on the command line.
5952 TEST_F(ParseFlagsTest, UnrecognizedFlag) {
5953 const char* argv[] = {
5955 "--gtest_break_on_failure",
5956 "bar", // Unrecognized by Google Test.
5961 const char* argv2[] = {
5968 flags.break_on_failure = true;
5970 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5973 // Tests having a --gtest_list_tests flag
5974 TEST_F(ParseFlagsTest, ListTestsFlag) {
5975 const char* argv[] = {
5977 "--gtest_list_tests",
5981 const char* argv2[] = {
5986 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5989 // Tests having a --gtest_list_tests flag with a "true" value
5990 TEST_F(ParseFlagsTest, ListTestsTrue) {
5991 const char* argv[] = {
5993 "--gtest_list_tests=1",
5997 const char* argv2[] = {
6002 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
6005 // Tests having a --gtest_list_tests flag with a "false" value
6006 TEST_F(ParseFlagsTest, ListTestsFalse) {
6007 const char* argv[] = {
6009 "--gtest_list_tests=0",
6013 const char* argv2[] = {
6018 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6021 // Tests parsing --gtest_list_tests=f.
6022 TEST_F(ParseFlagsTest, ListTestsFalse_f) {
6023 const char* argv[] = {
6025 "--gtest_list_tests=f",
6029 const char* argv2[] = {
6034 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6037 // Tests parsing --gtest_list_tests=F.
6038 TEST_F(ParseFlagsTest, ListTestsFalse_F) {
6039 const char* argv[] = {
6041 "--gtest_list_tests=F",
6045 const char* argv2[] = {
6050 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6053 // Tests parsing --gtest_output (invalid).
6054 TEST_F(ParseFlagsTest, OutputEmpty) {
6055 const char* argv[] = {
6061 const char* argv2[] = {
6067 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
6070 // Tests parsing --gtest_output=xml
6071 TEST_F(ParseFlagsTest, OutputXml) {
6072 const char* argv[] = {
6074 "--gtest_output=xml",
6078 const char* argv2[] = {
6083 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
6086 // Tests parsing --gtest_output=xml:file
6087 TEST_F(ParseFlagsTest, OutputXmlFile) {
6088 const char* argv[] = {
6090 "--gtest_output=xml:file",
6094 const char* argv2[] = {
6099 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
6102 // Tests parsing --gtest_output=xml:directory/path/
6103 TEST_F(ParseFlagsTest, OutputXmlDirectory) {
6104 const char* argv[] = {
6106 "--gtest_output=xml:directory/path/",
6110 const char* argv2[] = {
6115 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6116 Flags::Output("xml:directory/path/"), false);
6119 // Tests having a --gtest_print_time flag
6120 TEST_F(ParseFlagsTest, PrintTimeFlag) {
6121 const char* argv[] = {
6123 "--gtest_print_time",
6127 const char* argv2[] = {
6132 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6135 // Tests having a --gtest_print_time flag with a "true" value
6136 TEST_F(ParseFlagsTest, PrintTimeTrue) {
6137 const char* argv[] = {
6139 "--gtest_print_time=1",
6143 const char* argv2[] = {
6148 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6151 // Tests having a --gtest_print_time flag with a "false" value
6152 TEST_F(ParseFlagsTest, PrintTimeFalse) {
6153 const char* argv[] = {
6155 "--gtest_print_time=0",
6159 const char* argv2[] = {
6164 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6167 // Tests parsing --gtest_print_time=f.
6168 TEST_F(ParseFlagsTest, PrintTimeFalse_f) {
6169 const char* argv[] = {
6171 "--gtest_print_time=f",
6175 const char* argv2[] = {
6180 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6183 // Tests parsing --gtest_print_time=F.
6184 TEST_F(ParseFlagsTest, PrintTimeFalse_F) {
6185 const char* argv[] = {
6187 "--gtest_print_time=F",
6191 const char* argv2[] = {
6196 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6199 // Tests parsing --gtest_random_seed=number
6200 TEST_F(ParseFlagsTest, RandomSeed) {
6201 const char* argv[] = {
6203 "--gtest_random_seed=1000",
6207 const char* argv2[] = {
6212 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6215 // Tests parsing --gtest_repeat=number
6216 TEST_F(ParseFlagsTest, Repeat) {
6217 const char* argv[] = {
6219 "--gtest_repeat=1000",
6223 const char* argv2[] = {
6228 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
6231 // Tests having a --gtest_also_run_disabled_tests flag
6232 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
6233 const char* argv[] = {
6235 "--gtest_also_run_disabled_tests",
6239 const char* argv2[] = {
6244 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6245 Flags::AlsoRunDisabledTests(true), false);
6248 // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6249 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {
6250 const char* argv[] = {
6252 "--gtest_also_run_disabled_tests=1",
6256 const char* argv2[] = {
6261 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6262 Flags::AlsoRunDisabledTests(true), false);
6265 // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6266 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {
6267 const char* argv[] = {
6269 "--gtest_also_run_disabled_tests=0",
6273 const char* argv2[] = {
6278 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6279 Flags::AlsoRunDisabledTests(false), false);
6282 // Tests parsing --gtest_shuffle.
6283 TEST_F(ParseFlagsTest, ShuffleWithoutValue) {
6284 const char* argv[] = {
6290 const char* argv2[] = {
6295 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6298 // Tests parsing --gtest_shuffle=0.
6299 TEST_F(ParseFlagsTest, ShuffleFalse_0) {
6300 const char* argv[] = {
6302 "--gtest_shuffle=0",
6306 const char* argv2[] = {
6311 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6314 // Tests parsing a --gtest_shuffle flag that has a "true" definition.
6315 TEST_F(ParseFlagsTest, ShuffleTrue) {
6316 const char* argv[] = {
6318 "--gtest_shuffle=1",
6322 const char* argv2[] = {
6327 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6330 // Tests parsing --gtest_stack_trace_depth=number.
6331 TEST_F(ParseFlagsTest, StackTraceDepth) {
6332 const char* argv[] = {
6334 "--gtest_stack_trace_depth=5",
6338 const char* argv2[] = {
6343 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6346 TEST_F(ParseFlagsTest, StreamResultTo) {
6347 const char* argv[] = {
6349 "--gtest_stream_result_to=localhost:1234",
6353 const char* argv2[] = {
6358 GTEST_TEST_PARSING_FLAGS_(
6359 argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
6362 // Tests parsing --gtest_throw_on_failure.
6363 TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
6364 const char* argv[] = {
6366 "--gtest_throw_on_failure",
6370 const char* argv2[] = {
6375 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6378 // Tests parsing --gtest_throw_on_failure=0.
6379 TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {
6380 const char* argv[] = {
6382 "--gtest_throw_on_failure=0",
6386 const char* argv2[] = {
6391 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
6394 // Tests parsing a --gtest_throw_on_failure flag that has a "true"
6396 TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
6397 const char* argv[] = {
6399 "--gtest_throw_on_failure=1",
6403 const char* argv2[] = {
6408 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6411 # if GTEST_OS_WINDOWS
6412 // Tests parsing wide strings.
6413 TEST_F(ParseFlagsTest, WideStrings) {
6414 const wchar_t* argv[] = {
6416 L"--gtest_filter=Foo*",
6417 L"--gtest_list_tests=1",
6418 L"--gtest_break_on_failure",
6419 L"--non_gtest_flag",
6423 const wchar_t* argv2[] = {
6425 L"--non_gtest_flag",
6429 Flags expected_flags;
6430 expected_flags.break_on_failure = true;
6431 expected_flags.filter = "Foo*";
6432 expected_flags.list_tests = true;
6434 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6436 # endif // GTEST_OS_WINDOWS
6438 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6439 class FlagfileTest : public ParseFlagsTest {
6441 virtual void SetUp() {
6442 ParseFlagsTest::SetUp();
6444 testdata_path_.Set(internal::FilePath(
6445 testing::TempDir() + internal::GetCurrentExecutableName().string() +
6447 testing::internal::posix::RmDir(testdata_path_.c_str());
6448 EXPECT_TRUE(testdata_path_.CreateFolder());
6451 virtual void TearDown() {
6452 testing::internal::posix::RmDir(testdata_path_.c_str());
6453 ParseFlagsTest::TearDown();
6456 internal::FilePath CreateFlagfile(const char* contents) {
6457 internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
6458 testdata_path_, internal::FilePath("unique"), "txt"));
6459 FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
6460 fprintf(f, "%s", contents);
6466 internal::FilePath testdata_path_;
6469 // Tests an empty flagfile.
6470 TEST_F(FlagfileTest, Empty) {
6471 internal::FilePath flagfile_path(CreateFlagfile(""));
6472 std::string flagfile_flag =
6473 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6475 const char* argv[] = {
6477 flagfile_flag.c_str(),
6481 const char* argv2[] = {
6486 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
6489 // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
6490 TEST_F(FlagfileTest, FilterNonEmpty) {
6491 internal::FilePath flagfile_path(CreateFlagfile(
6492 "--" GTEST_FLAG_PREFIX_ "filter=abc"));
6493 std::string flagfile_flag =
6494 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6496 const char* argv[] = {
6498 flagfile_flag.c_str(),
6502 const char* argv2[] = {
6507 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
6510 // Tests passing several flags via --gtest_flagfile.
6511 TEST_F(FlagfileTest, SeveralFlags) {
6512 internal::FilePath flagfile_path(CreateFlagfile(
6513 "--" GTEST_FLAG_PREFIX_ "filter=abc\n"
6514 "--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
6515 "--" GTEST_FLAG_PREFIX_ "list_tests"));
6516 std::string flagfile_flag =
6517 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6519 const char* argv[] = {
6521 flagfile_flag.c_str(),
6525 const char* argv2[] = {
6530 Flags expected_flags;
6531 expected_flags.break_on_failure = true;
6532 expected_flags.filter = "abc";
6533 expected_flags.list_tests = true;
6535 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6537 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6539 // Tests current_test_info() in UnitTest.
6540 class CurrentTestInfoTest : public Test {
6542 // Tests that current_test_info() returns NULL before the first test in
6543 // the test case is run.
6544 static void SetUpTestCase() {
6545 // There should be no tests running at this point.
6546 const TestInfo* test_info =
6547 UnitTest::GetInstance()->current_test_info();
6548 EXPECT_TRUE(test_info == NULL)
6549 << "There should be no tests running at this point.";
6552 // Tests that current_test_info() returns NULL after the last test in
6553 // the test case has run.
6554 static void TearDownTestCase() {
6555 const TestInfo* test_info =
6556 UnitTest::GetInstance()->current_test_info();
6557 EXPECT_TRUE(test_info == NULL)
6558 << "There should be no tests running at this point.";
6562 // Tests that current_test_info() returns TestInfo for currently running
6563 // test by checking the expected test name against the actual one.
6564 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
6565 const TestInfo* test_info =
6566 UnitTest::GetInstance()->current_test_info();
6567 ASSERT_TRUE(NULL != test_info)
6568 << "There is a test running so we should have a valid TestInfo.";
6569 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6570 << "Expected the name of the currently running test case.";
6571 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
6572 << "Expected the name of the currently running test.";
6575 // Tests that current_test_info() returns TestInfo for currently running
6576 // test by checking the expected test name against the actual one. We
6577 // use this test to see that the TestInfo object actually changed from
6578 // the previous invocation.
6579 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
6580 const TestInfo* test_info =
6581 UnitTest::GetInstance()->current_test_info();
6582 ASSERT_TRUE(NULL != test_info)
6583 << "There is a test running so we should have a valid TestInfo.";
6584 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6585 << "Expected the name of the currently running test case.";
6586 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
6587 << "Expected the name of the currently running test.";
6590 } // namespace testing
6593 // These two lines test that we can define tests in a namespace that
6594 // has the name "testing" and is nested in another namespace.
6595 namespace my_namespace {
6598 // Makes sure that TEST knows to use ::testing::Test instead of
6599 // ::my_namespace::testing::Test.
6602 // Makes sure that an assertion knows to use ::testing::Message instead of
6603 // ::my_namespace::testing::Message.
6606 // Makes sure that an assertion knows to use
6607 // ::testing::AssertionResult instead of
6608 // ::my_namespace::testing::AssertionResult.
6609 class AssertionResult {};
6611 // Tests that an assertion that should succeed works as expected.
6612 TEST(NestedTestingNamespaceTest, Success) {
6613 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6616 // Tests that an assertion that should fail works as expected.
6617 TEST(NestedTestingNamespaceTest, Failure) {
6618 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6619 "This failure is expected.");
6622 } // namespace testing
6623 } // namespace my_namespace
6625 // Tests that one can call superclass SetUp and TearDown methods--
6626 // that is, that they are not private.
6627 // No tests are based on this fixture; the test "passes" if it compiles
6629 class ProtectedFixtureMethodsTest : public Test {
6631 virtual void SetUp() {
6634 virtual void TearDown() {
6639 // StreamingAssertionsTest tests the streaming versions of a representative
6640 // sample of assertions.
6641 TEST(StreamingAssertionsTest, Unconditional) {
6642 SUCCEED() << "expected success";
6643 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6644 "expected failure");
6645 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6646 "expected failure");
6650 // Silences warnings: "Condition is always true", "Unreachable code"
6651 # pragma option push -w-ccc -w-rch
6654 TEST(StreamingAssertionsTest, Truth) {
6655 EXPECT_TRUE(true) << "unexpected failure";
6656 ASSERT_TRUE(true) << "unexpected failure";
6657 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6658 "expected failure");
6659 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6660 "expected failure");
6663 TEST(StreamingAssertionsTest, Truth2) {
6664 EXPECT_FALSE(false) << "unexpected failure";
6665 ASSERT_FALSE(false) << "unexpected failure";
6666 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6667 "expected failure");
6668 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6669 "expected failure");
6673 // Restores warnings after previous "#pragma option push" suppressed them
6677 TEST(StreamingAssertionsTest, IntegerEquals) {
6678 EXPECT_EQ(1, 1) << "unexpected failure";
6679 ASSERT_EQ(1, 1) << "unexpected failure";
6680 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6681 "expected failure");
6682 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6683 "expected failure");
6686 TEST(StreamingAssertionsTest, IntegerLessThan) {
6687 EXPECT_LT(1, 2) << "unexpected failure";
6688 ASSERT_LT(1, 2) << "unexpected failure";
6689 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6690 "expected failure");
6691 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6692 "expected failure");
6695 TEST(StreamingAssertionsTest, StringsEqual) {
6696 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6697 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6698 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6699 "expected failure");
6700 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6701 "expected failure");
6704 TEST(StreamingAssertionsTest, StringsNotEqual) {
6705 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6706 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6707 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6708 "expected failure");
6709 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6710 "expected failure");
6713 TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6714 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6715 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6716 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6717 "expected failure");
6718 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6719 "expected failure");
6722 TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6723 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6724 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6725 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6726 "expected failure");
6727 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6728 "expected failure");
6731 TEST(StreamingAssertionsTest, FloatingPointEquals) {
6732 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6733 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6734 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6735 "expected failure");
6736 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6737 "expected failure");
6740 #if GTEST_HAS_EXCEPTIONS
6742 TEST(StreamingAssertionsTest, Throw) {
6743 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6744 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6745 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6746 "expected failure", "expected failure");
6747 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6748 "expected failure", "expected failure");
6751 TEST(StreamingAssertionsTest, NoThrow) {
6752 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6753 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6754 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6755 "expected failure", "expected failure");
6756 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6757 "expected failure", "expected failure");
6760 TEST(StreamingAssertionsTest, AnyThrow) {
6761 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6762 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6763 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
6764 "expected failure", "expected failure");
6765 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
6766 "expected failure", "expected failure");
6769 #endif // GTEST_HAS_EXCEPTIONS
6771 // Tests that Google Test correctly decides whether to use colors in the output.
6773 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6774 GTEST_FLAG(color) = "yes";
6776 SetEnv("TERM", "xterm"); // TERM supports colors.
6777 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6778 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6780 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6781 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6782 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6785 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6786 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6788 GTEST_FLAG(color) = "True";
6789 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6791 GTEST_FLAG(color) = "t";
6792 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6794 GTEST_FLAG(color) = "1";
6795 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6798 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6799 GTEST_FLAG(color) = "no";
6801 SetEnv("TERM", "xterm"); // TERM supports colors.
6802 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6803 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6805 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6806 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6807 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6810 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6811 SetEnv("TERM", "xterm"); // TERM supports colors.
6813 GTEST_FLAG(color) = "F";
6814 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6816 GTEST_FLAG(color) = "0";
6817 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6819 GTEST_FLAG(color) = "unknown";
6820 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6823 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6824 GTEST_FLAG(color) = "auto";
6826 SetEnv("TERM", "xterm"); // TERM supports colors.
6827 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6828 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6831 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6832 GTEST_FLAG(color) = "auto";
6834 #if GTEST_OS_WINDOWS
6835 // On Windows, we ignore the TERM variable as it's usually not set.
6837 SetEnv("TERM", "dumb");
6838 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6841 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6843 SetEnv("TERM", "xterm");
6844 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6846 // On non-Windows platforms, we rely on TERM to determine if the
6847 // terminal supports colors.
6849 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6850 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6852 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6853 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6855 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6856 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6858 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6859 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6861 SetEnv("TERM", "xterm"); // TERM supports colors.
6862 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6864 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6865 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6867 SetEnv("TERM", "xterm-256color"); // TERM supports colors.
6868 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6870 SetEnv("TERM", "screen"); // TERM supports colors.
6871 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6873 SetEnv("TERM", "screen-256color"); // TERM supports colors.
6874 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6876 SetEnv("TERM", "tmux"); // TERM supports colors.
6877 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6879 SetEnv("TERM", "tmux-256color"); // TERM supports colors.
6880 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6882 SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
6883 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6885 SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
6886 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6888 SetEnv("TERM", "linux"); // TERM supports colors.
6889 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6891 SetEnv("TERM", "cygwin"); // TERM supports colors.
6892 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6893 #endif // GTEST_OS_WINDOWS
6896 // Verifies that StaticAssertTypeEq works in a namespace scope.
6898 static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6899 static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6900 StaticAssertTypeEq<const int, const int>();
6902 // Verifies that StaticAssertTypeEq works in a class.
6904 template <typename T>
6905 class StaticAssertTypeEqTestHelper {
6907 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6910 TEST(StaticAssertTypeEqTest, WorksInClass) {
6911 StaticAssertTypeEqTestHelper<bool>();
6914 // Verifies that StaticAssertTypeEq works inside a function.
6916 typedef int IntAlias;
6918 TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6919 StaticAssertTypeEq<int, IntAlias>();
6920 StaticAssertTypeEq<int*, IntAlias*>();
6923 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6924 EXPECT_FALSE(HasNonfatalFailure());
6927 static void FailFatally() { FAIL(); }
6929 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6931 const bool has_nonfatal_failure = HasNonfatalFailure();
6932 ClearCurrentTestPartResults();
6933 EXPECT_FALSE(has_nonfatal_failure);
6936 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6938 const bool has_nonfatal_failure = HasNonfatalFailure();
6939 ClearCurrentTestPartResults();
6940 EXPECT_TRUE(has_nonfatal_failure);
6943 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6946 const bool has_nonfatal_failure = HasNonfatalFailure();
6947 ClearCurrentTestPartResults();
6948 EXPECT_TRUE(has_nonfatal_failure);
6951 // A wrapper for calling HasNonfatalFailure outside of a test body.
6952 static bool HasNonfatalFailureHelper() {
6953 return testing::Test::HasNonfatalFailure();
6956 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6957 EXPECT_FALSE(HasNonfatalFailureHelper());
6960 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6962 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6963 ClearCurrentTestPartResults();
6964 EXPECT_TRUE(has_nonfatal_failure);
6967 TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6968 EXPECT_FALSE(HasFailure());
6971 TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6973 const bool has_failure = HasFailure();
6974 ClearCurrentTestPartResults();
6975 EXPECT_TRUE(has_failure);
6978 TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6980 const bool has_failure = HasFailure();
6981 ClearCurrentTestPartResults();
6982 EXPECT_TRUE(has_failure);
6985 TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6988 const bool has_failure = HasFailure();
6989 ClearCurrentTestPartResults();
6990 EXPECT_TRUE(has_failure);
6993 // A wrapper for calling HasFailure outside of a test body.
6994 static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6996 TEST(HasFailureTest, WorksOutsideOfTestBody) {
6997 EXPECT_FALSE(HasFailureHelper());
7000 TEST(HasFailureTest, WorksOutsideOfTestBody2) {
7002 const bool has_failure = HasFailureHelper();
7003 ClearCurrentTestPartResults();
7004 EXPECT_TRUE(has_failure);
7007 class TestListener : public EmptyTestEventListener {
7009 TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
7010 TestListener(int* on_start_counter, bool* is_destroyed)
7011 : on_start_counter_(on_start_counter),
7012 is_destroyed_(is_destroyed) {}
7014 virtual ~TestListener() {
7016 *is_destroyed_ = true;
7020 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
7021 if (on_start_counter_ != NULL)
7022 (*on_start_counter_)++;
7026 int* on_start_counter_;
7027 bool* is_destroyed_;
7030 // Tests the constructor.
7031 TEST(TestEventListenersTest, ConstructionWorks) {
7032 TestEventListeners listeners;
7034 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
7035 EXPECT_TRUE(listeners.default_result_printer() == NULL);
7036 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7039 // Tests that the TestEventListeners destructor deletes all the listeners it
7041 TEST(TestEventListenersTest, DestructionWorks) {
7042 bool default_result_printer_is_destroyed = false;
7043 bool default_xml_printer_is_destroyed = false;
7044 bool extra_listener_is_destroyed = false;
7045 TestListener* default_result_printer = new TestListener(
7046 NULL, &default_result_printer_is_destroyed);
7047 TestListener* default_xml_printer = new TestListener(
7048 NULL, &default_xml_printer_is_destroyed);
7049 TestListener* extra_listener = new TestListener(
7050 NULL, &extra_listener_is_destroyed);
7053 TestEventListeners listeners;
7054 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
7055 default_result_printer);
7056 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
7057 default_xml_printer);
7058 listeners.Append(extra_listener);
7060 EXPECT_TRUE(default_result_printer_is_destroyed);
7061 EXPECT_TRUE(default_xml_printer_is_destroyed);
7062 EXPECT_TRUE(extra_listener_is_destroyed);
7065 // Tests that a listener Append'ed to a TestEventListeners list starts
7066 // receiving events.
7067 TEST(TestEventListenersTest, Append) {
7068 int on_start_counter = 0;
7069 bool is_destroyed = false;
7070 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7072 TestEventListeners listeners;
7073 listeners.Append(listener);
7074 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7075 *UnitTest::GetInstance());
7076 EXPECT_EQ(1, on_start_counter);
7078 EXPECT_TRUE(is_destroyed);
7081 // Tests that listeners receive events in the order they were appended to
7082 // the list, except for *End requests, which must be received in the reverse
7084 class SequenceTestingListener : public EmptyTestEventListener {
7086 SequenceTestingListener(std::vector<std::string>* vector, const char* id)
7087 : vector_(vector), id_(id) {}
7090 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
7091 vector_->push_back(GetEventDescription("OnTestProgramStart"));
7094 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
7095 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
7098 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
7099 int /*iteration*/) {
7100 vector_->push_back(GetEventDescription("OnTestIterationStart"));
7103 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
7104 int /*iteration*/) {
7105 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
7109 std::string GetEventDescription(const char* method) {
7111 message << id_ << "." << method;
7112 return message.GetString();
7115 std::vector<std::string>* vector_;
7116 const char* const id_;
7118 GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
7121 TEST(EventListenerTest, AppendKeepsOrder) {
7122 std::vector<std::string> vec;
7123 TestEventListeners listeners;
7124 listeners.Append(new SequenceTestingListener(&vec, "1st"));
7125 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
7126 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
7128 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7129 *UnitTest::GetInstance());
7130 ASSERT_EQ(3U, vec.size());
7131 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
7132 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
7133 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
7136 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
7137 *UnitTest::GetInstance());
7138 ASSERT_EQ(3U, vec.size());
7139 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
7140 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
7141 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
7144 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
7145 *UnitTest::GetInstance(), 0);
7146 ASSERT_EQ(3U, vec.size());
7147 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
7148 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
7149 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
7152 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
7153 *UnitTest::GetInstance(), 0);
7154 ASSERT_EQ(3U, vec.size());
7155 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
7156 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
7157 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
7160 // Tests that a listener removed from a TestEventListeners list stops receiving
7161 // events and is not deleted when the list is destroyed.
7162 TEST(TestEventListenersTest, Release) {
7163 int on_start_counter = 0;
7164 bool is_destroyed = false;
7165 // Although Append passes the ownership of this object to the list,
7166 // the following calls release it, and we need to delete it before the
7168 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7170 TestEventListeners listeners;
7171 listeners.Append(listener);
7172 EXPECT_EQ(listener, listeners.Release(listener));
7173 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7174 *UnitTest::GetInstance());
7175 EXPECT_TRUE(listeners.Release(listener) == NULL);
7177 EXPECT_EQ(0, on_start_counter);
7178 EXPECT_FALSE(is_destroyed);
7182 // Tests that no events are forwarded when event forwarding is disabled.
7183 TEST(EventListenerTest, SuppressEventForwarding) {
7184 int on_start_counter = 0;
7185 TestListener* listener = new TestListener(&on_start_counter, NULL);
7187 TestEventListeners listeners;
7188 listeners.Append(listener);
7189 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7190 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
7191 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7192 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7193 *UnitTest::GetInstance());
7194 EXPECT_EQ(0, on_start_counter);
7197 // Tests that events generated by Google Test are not forwarded in
7198 // death test subprocesses.
7199 TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
7200 EXPECT_DEATH_IF_SUPPORTED({
7201 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
7202 *GetUnitTestImpl()->listeners())) << "expected failure";},
7203 "expected failure");
7206 // Tests that a listener installed via SetDefaultResultPrinter() starts
7207 // receiving events and is returned via default_result_printer() and that
7208 // the previous default_result_printer is removed from the list and deleted.
7209 TEST(EventListenerTest, default_result_printer) {
7210 int on_start_counter = 0;
7211 bool is_destroyed = false;
7212 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7214 TestEventListeners listeners;
7215 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7217 EXPECT_EQ(listener, listeners.default_result_printer());
7219 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7220 *UnitTest::GetInstance());
7222 EXPECT_EQ(1, on_start_counter);
7224 // Replacing default_result_printer with something else should remove it
7225 // from the list and destroy it.
7226 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
7228 EXPECT_TRUE(listeners.default_result_printer() == NULL);
7229 EXPECT_TRUE(is_destroyed);
7231 // After broadcasting an event the counter is still the same, indicating
7232 // the listener is not in the list anymore.
7233 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7234 *UnitTest::GetInstance());
7235 EXPECT_EQ(1, on_start_counter);
7238 // Tests that the default_result_printer listener stops receiving events
7239 // when removed via Release and that is not owned by the list anymore.
7240 TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
7241 int on_start_counter = 0;
7242 bool is_destroyed = false;
7243 // Although Append passes the ownership of this object to the list,
7244 // the following calls release it, and we need to delete it before the
7246 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7248 TestEventListeners listeners;
7249 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7251 EXPECT_EQ(listener, listeners.Release(listener));
7252 EXPECT_TRUE(listeners.default_result_printer() == NULL);
7253 EXPECT_FALSE(is_destroyed);
7255 // Broadcasting events now should not affect default_result_printer.
7256 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7257 *UnitTest::GetInstance());
7258 EXPECT_EQ(0, on_start_counter);
7260 // Destroying the list should not affect the listener now, too.
7261 EXPECT_FALSE(is_destroyed);
7265 // Tests that a listener installed via SetDefaultXmlGenerator() starts
7266 // receiving events and is returned via default_xml_generator() and that
7267 // the previous default_xml_generator is removed from the list and deleted.
7268 TEST(EventListenerTest, default_xml_generator) {
7269 int on_start_counter = 0;
7270 bool is_destroyed = false;
7271 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7273 TestEventListeners listeners;
7274 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7276 EXPECT_EQ(listener, listeners.default_xml_generator());
7278 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7279 *UnitTest::GetInstance());
7281 EXPECT_EQ(1, on_start_counter);
7283 // Replacing default_xml_generator with something else should remove it
7284 // from the list and destroy it.
7285 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
7287 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7288 EXPECT_TRUE(is_destroyed);
7290 // After broadcasting an event the counter is still the same, indicating
7291 // the listener is not in the list anymore.
7292 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7293 *UnitTest::GetInstance());
7294 EXPECT_EQ(1, on_start_counter);
7297 // Tests that the default_xml_generator listener stops receiving events
7298 // when removed via Release and that is not owned by the list anymore.
7299 TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
7300 int on_start_counter = 0;
7301 bool is_destroyed = false;
7302 // Although Append passes the ownership of this object to the list,
7303 // the following calls release it, and we need to delete it before the
7305 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7307 TestEventListeners listeners;
7308 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7310 EXPECT_EQ(listener, listeners.Release(listener));
7311 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7312 EXPECT_FALSE(is_destroyed);
7314 // Broadcasting events now should not affect default_xml_generator.
7315 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7316 *UnitTest::GetInstance());
7317 EXPECT_EQ(0, on_start_counter);
7319 // Destroying the list should not affect the listener now, too.
7320 EXPECT_FALSE(is_destroyed);
7324 // Sanity tests to ensure that the alternative, verbose spellings of
7325 // some of the macros work. We don't test them thoroughly as that
7326 // would be quite involved. Since their implementations are
7327 // straightforward, and they are rarely used, we'll just rely on the
7328 // users to tell us when they are broken.
7329 GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
7330 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
7332 // GTEST_FAIL is the same as FAIL.
7333 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
7334 "An expected failure");
7336 // GTEST_ASSERT_XY is the same as ASSERT_XY.
7338 GTEST_ASSERT_EQ(0, 0);
7339 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
7340 "An expected failure");
7341 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
7342 "An expected failure");
7344 GTEST_ASSERT_NE(0, 1);
7345 GTEST_ASSERT_NE(1, 0);
7346 EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
7347 "An expected failure");
7349 GTEST_ASSERT_LE(0, 0);
7350 GTEST_ASSERT_LE(0, 1);
7351 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
7352 "An expected failure");
7354 GTEST_ASSERT_LT(0, 1);
7355 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
7356 "An expected failure");
7357 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
7358 "An expected failure");
7360 GTEST_ASSERT_GE(0, 0);
7361 GTEST_ASSERT_GE(1, 0);
7362 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
7363 "An expected failure");
7365 GTEST_ASSERT_GT(1, 0);
7366 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
7367 "An expected failure");
7368 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
7369 "An expected failure");
7372 // Tests for internal utilities necessary for implementation of the universal
7374 // FIXME: Find a better home for them.
7376 class ConversionHelperBase {};
7377 class ConversionHelperDerived : public ConversionHelperBase {};
7379 // Tests that IsAProtocolMessage<T>::value is a compile-time constant.
7380 TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
7381 GTEST_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value,
7383 GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
7386 // Tests that IsAProtocolMessage<T>::value is true when T is
7387 // proto2::Message or a sub-class of it.
7388 TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
7389 EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
7390 EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value);
7393 // Tests that IsAProtocolMessage<T>::value is false when T is neither
7394 // ProtocolMessage nor a sub-class of it.
7395 TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7396 EXPECT_FALSE(IsAProtocolMessage<int>::value);
7397 EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
7400 // Tests that CompileAssertTypesEqual compiles when the type arguments are
7402 TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) {
7403 CompileAssertTypesEqual<void, void>();
7404 CompileAssertTypesEqual<int*, int*>();
7407 // Tests that RemoveReference does not affect non-reference types.
7408 TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) {
7409 CompileAssertTypesEqual<int, RemoveReference<int>::type>();
7410 CompileAssertTypesEqual<const char, RemoveReference<const char>::type>();
7413 // Tests that RemoveReference removes reference from reference types.
7414 TEST(RemoveReferenceTest, RemovesReference) {
7415 CompileAssertTypesEqual<int, RemoveReference<int&>::type>();
7416 CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>();
7419 // Tests GTEST_REMOVE_REFERENCE_.
7421 template <typename T1, typename T2>
7422 void TestGTestRemoveReference() {
7423 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>();
7426 TEST(RemoveReferenceTest, MacroVersion) {
7427 TestGTestRemoveReference<int, int>();
7428 TestGTestRemoveReference<const char, const char&>();
7432 // Tests that RemoveConst does not affect non-const types.
7433 TEST(RemoveConstTest, DoesNotAffectNonConstType) {
7434 CompileAssertTypesEqual<int, RemoveConst<int>::type>();
7435 CompileAssertTypesEqual<char&, RemoveConst<char&>::type>();
7438 // Tests that RemoveConst removes const from const types.
7439 TEST(RemoveConstTest, RemovesConst) {
7440 CompileAssertTypesEqual<int, RemoveConst<const int>::type>();
7441 CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>();
7442 CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>();
7445 // Tests GTEST_REMOVE_CONST_.
7447 template <typename T1, typename T2>
7448 void TestGTestRemoveConst() {
7449 CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>();
7452 TEST(RemoveConstTest, MacroVersion) {
7453 TestGTestRemoveConst<int, int>();
7454 TestGTestRemoveConst<double&, double&>();
7455 TestGTestRemoveConst<char, const char>();
7458 // Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7460 template <typename T1, typename T2>
7461 void TestGTestRemoveReferenceAndConst() {
7462 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>();
7465 TEST(RemoveReferenceToConstTest, Works) {
7466 TestGTestRemoveReferenceAndConst<int, int>();
7467 TestGTestRemoveReferenceAndConst<double, double&>();
7468 TestGTestRemoveReferenceAndConst<char, const char>();
7469 TestGTestRemoveReferenceAndConst<char, const char&>();
7470 TestGTestRemoveReferenceAndConst<const char*, const char*>();
7473 // Tests that AddReference does not affect reference types.
7474 TEST(AddReferenceTest, DoesNotAffectReferenceType) {
7475 CompileAssertTypesEqual<int&, AddReference<int&>::type>();
7476 CompileAssertTypesEqual<const char&, AddReference<const char&>::type>();
7479 // Tests that AddReference adds reference to non-reference types.
7480 TEST(AddReferenceTest, AddsReference) {
7481 CompileAssertTypesEqual<int&, AddReference<int>::type>();
7482 CompileAssertTypesEqual<const char&, AddReference<const char>::type>();
7485 // Tests GTEST_ADD_REFERENCE_.
7487 template <typename T1, typename T2>
7488 void TestGTestAddReference() {
7489 CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>();
7492 TEST(AddReferenceTest, MacroVersion) {
7493 TestGTestAddReference<int&, int>();
7494 TestGTestAddReference<const char&, const char&>();
7497 // Tests GTEST_REFERENCE_TO_CONST_.
7499 template <typename T1, typename T2>
7500 void TestGTestReferenceToConst() {
7501 CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>();
7504 TEST(GTestReferenceToConstTest, Works) {
7505 TestGTestReferenceToConst<const char&, char>();
7506 TestGTestReferenceToConst<const int&, const int>();
7507 TestGTestReferenceToConst<const double&, double>();
7508 TestGTestReferenceToConst<const std::string&, const std::string&>();
7511 // Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant.
7512 TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) {
7513 GTEST_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true);
7514 GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value),
7518 // Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can
7519 // be implicitly converted to T2.
7520 TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) {
7521 EXPECT_TRUE((ImplicitlyConvertible<int, double>::value));
7522 EXPECT_TRUE((ImplicitlyConvertible<double, int>::value));
7523 EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value));
7524 EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value));
7525 EXPECT_TRUE((ImplicitlyConvertible<ConversionHelperDerived&,
7526 const ConversionHelperBase&>::value));
7527 EXPECT_TRUE((ImplicitlyConvertible<const ConversionHelperBase,
7528 ConversionHelperBase>::value));
7531 // Tests that ImplicitlyConvertible<T1, T2>::value is false when T1
7532 // cannot be implicitly converted to T2.
7533 TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) {
7534 EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value));
7535 EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value));
7536 EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value));
7537 EXPECT_FALSE((ImplicitlyConvertible<ConversionHelperBase&,
7538 ConversionHelperDerived&>::value));
7541 // Tests IsContainerTest.
7543 class NonContainer {};
7545 TEST(IsContainerTestTest, WorksForNonContainer) {
7546 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7547 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7548 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7551 TEST(IsContainerTestTest, WorksForContainer) {
7552 EXPECT_EQ(sizeof(IsContainer),
7553 sizeof(IsContainerTest<std::vector<bool> >(0)));
7554 EXPECT_EQ(sizeof(IsContainer),
7555 sizeof(IsContainerTest<std::map<int, double> >(0)));
7558 #if GTEST_LANG_CXX11
7559 struct ConstOnlyContainerWithPointerIterator {
7560 using const_iterator = int*;
7561 const_iterator begin() const;
7562 const_iterator end() const;
7565 struct ConstOnlyContainerWithClassIterator {
7566 struct const_iterator {
7567 const int& operator*() const;
7568 const_iterator& operator++(/* pre-increment */);
7570 const_iterator begin() const;
7571 const_iterator end() const;
7574 TEST(IsContainerTestTest, ConstOnlyContainer) {
7575 EXPECT_EQ(sizeof(IsContainer),
7576 sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
7577 EXPECT_EQ(sizeof(IsContainer),
7578 sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
7580 #endif // GTEST_LANG_CXX11
7582 // Tests IsHashTable.
7584 typedef void hasher;
7586 struct NotReallyAHashTable {
7587 typedef void hasher;
7588 typedef void reverse_iterator;
7590 TEST(IsHashTable, Basic) {
7591 EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value);
7592 EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value);
7593 #if GTEST_LANG_CXX11
7594 EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value);
7595 EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value);
7596 #endif // GTEST_LANG_CXX11
7597 #if GTEST_HAS_HASH_SET_
7598 EXPECT_TRUE(testing::internal::IsHashTable<__gnu_cxx::hash_set<int>>::value);
7599 #endif // GTEST_HAS_HASH_SET_
7604 TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7605 EXPECT_TRUE(ArrayEq(5, 5L));
7606 EXPECT_FALSE(ArrayEq('a', 0));
7609 TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7610 // Note that a and b are distinct but compatible types.
7611 const int a[] = { 0, 1 };
7612 long b[] = { 0, 1 };
7613 EXPECT_TRUE(ArrayEq(a, b));
7614 EXPECT_TRUE(ArrayEq(a, 2, b));
7617 EXPECT_FALSE(ArrayEq(a, b));
7618 EXPECT_FALSE(ArrayEq(a, 1, b));
7621 TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7622 const char a[][3] = { "hi", "lo" };
7623 const char b[][3] = { "hi", "lo" };
7624 const char c[][3] = { "hi", "li" };
7626 EXPECT_TRUE(ArrayEq(a, b));
7627 EXPECT_TRUE(ArrayEq(a, 2, b));
7629 EXPECT_FALSE(ArrayEq(a, c));
7630 EXPECT_FALSE(ArrayEq(a, 2, c));
7633 // Tests ArrayAwareFind().
7635 TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7636 const char a[] = "hello";
7637 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7638 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7641 TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7642 int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
7643 const int b[2] = { 2, 3 };
7644 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7646 const int c[2] = { 6, 7 };
7647 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7650 // Tests CopyArray().
7652 TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7658 TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7659 const char a[3] = "hi";
7661 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7663 EXPECT_TRUE(ArrayEq(a, b));
7668 EXPECT_TRUE(ArrayEq(a, c));
7671 TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7672 const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
7674 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7676 EXPECT_TRUE(ArrayEq(a, b));
7681 EXPECT_TRUE(ArrayEq(a, c));
7684 // Tests NativeArray.
7686 TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7687 const int a[3] = { 0, 1, 2 };
7688 NativeArray<int> na(a, 3, RelationToSourceReference());
7689 EXPECT_EQ(3U, na.size());
7690 EXPECT_EQ(a, na.begin());
7693 TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7694 typedef int Array[2];
7695 Array* a = new Array[1];
7698 NativeArray<int> na(*a, 2, RelationToSourceCopy());
7699 EXPECT_NE(*a, na.begin());
7701 EXPECT_EQ(0, na.begin()[0]);
7702 EXPECT_EQ(1, na.begin()[1]);
7704 // We rely on the heap checker to verify that na deletes the copy of
7708 TEST(NativeArrayTest, TypeMembersAreCorrect) {
7709 StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7710 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7712 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7713 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7716 TEST(NativeArrayTest, MethodsWork) {
7717 const int a[3] = { 0, 1, 2 };
7718 NativeArray<int> na(a, 3, RelationToSourceCopy());
7719 ASSERT_EQ(3U, na.size());
7720 EXPECT_EQ(3, na.end() - na.begin());
7722 NativeArray<int>::const_iterator it = na.begin();
7729 EXPECT_EQ(na.end(), it);
7731 EXPECT_TRUE(na == na);
7733 NativeArray<int> na2(a, 3, RelationToSourceReference());
7734 EXPECT_TRUE(na == na2);
7736 const int b1[3] = { 0, 1, 1 };
7737 const int b2[4] = { 0, 1, 2, 3 };
7738 EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
7739 EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
7742 TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7743 const char a[2][3] = { "hi", "lo" };
7744 NativeArray<char[3]> na(a, 2, RelationToSourceReference());
7745 ASSERT_EQ(2U, na.size());
7746 EXPECT_EQ(a, na.begin());
7749 // Tests SkipPrefix().
7751 TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7752 const char* const str = "hello";
7754 const char* p = str;
7755 EXPECT_TRUE(SkipPrefix("", &p));
7759 EXPECT_TRUE(SkipPrefix("hell", &p));
7760 EXPECT_EQ(str + 4, p);
7763 TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7764 const char* const str = "world";
7766 const char* p = str;
7767 EXPECT_FALSE(SkipPrefix("W", &p));
7771 EXPECT_FALSE(SkipPrefix("world!", &p));
7775 // Tests ad_hoc_test_result().
7777 class AdHocTestResultTest : public testing::Test {
7779 static void SetUpTestCase() {
7780 FAIL() << "A failure happened inside SetUpTestCase().";
7784 TEST_F(AdHocTestResultTest, AdHocTestResultForTestCaseShowsFailure) {
7785 const testing::TestResult& test_result = testing::UnitTest::GetInstance()
7786 ->current_test_case()
7787 ->ad_hoc_test_result();
7788 EXPECT_TRUE(test_result.Failed());
7791 TEST_F(AdHocTestResultTest, AdHocTestResultTestForUnitTestDoesNotShowFailure) {
7792 const testing::TestResult& test_result =
7793 testing::UnitTest::GetInstance()->ad_hoc_test_result();
7794 EXPECT_FALSE(test_result.Failed());