1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: wan@google.com (Zhanyong Wan)
32 // Tests for Google Test itself. This verifies that the basic constructs of
35 #include "gtest/gtest.h"
37 // Verifies that the command line flag variables can be accessed
38 // in code once <gtest/gtest.h> has been #included.
39 // Do not move it after other #includes.
40 TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
41 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
42 || testing::GTEST_FLAG(break_on_failure)
43 || testing::GTEST_FLAG(catch_exceptions)
44 || testing::GTEST_FLAG(color) != "unknown"
45 || testing::GTEST_FLAG(filter) != "unknown"
46 || testing::GTEST_FLAG(list_tests)
47 || testing::GTEST_FLAG(output) != "unknown"
48 || testing::GTEST_FLAG(print_time)
49 || testing::GTEST_FLAG(random_seed)
50 || testing::GTEST_FLAG(repeat) > 0
51 || testing::GTEST_FLAG(show_internal_stack_frames)
52 || testing::GTEST_FLAG(shuffle)
53 || testing::GTEST_FLAG(stack_trace_depth) > 0
54 || testing::GTEST_FLAG(stream_result_to) != "unknown"
55 || testing::GTEST_FLAG(throw_on_failure);
56 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
59 #include <limits.h> // For INT_MAX.
68 #include "gtest/gtest-spi.h"
70 // Indicates that this translation unit is part of Google Test's
71 // implementation. It must come before gtest-internal-inl.h is
72 // included, or there will be a compiler error. This trick is to
73 // prevent a user from accidentally including gtest-internal-inl.h in
75 #define GTEST_IMPLEMENTATION_ 1
76 #include "src/gtest-internal-inl.h"
77 #undef GTEST_IMPLEMENTATION_
82 #if GTEST_CAN_STREAM_RESULTS_
84 class StreamingListenerTest : public Test {
86 class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
88 // Sends a string to the socket.
89 virtual void Send(const string& message) { output_ += message; }
94 StreamingListenerTest()
95 : fake_sock_writer_(new FakeSocketWriter),
96 streamer_(fake_sock_writer_),
97 test_info_obj_("FooTest", "Bar", NULL, NULL,
98 CodeLocation(__FILE__, __LINE__), 0, NULL) {}
101 string* output() { return &(fake_sock_writer_->output_); }
103 FakeSocketWriter* const fake_sock_writer_;
104 StreamingListener streamer_;
106 TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test.
109 TEST_F(StreamingListenerTest, OnTestProgramEnd) {
111 streamer_.OnTestProgramEnd(unit_test_);
112 EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
115 TEST_F(StreamingListenerTest, OnTestIterationEnd) {
117 streamer_.OnTestIterationEnd(unit_test_, 42);
118 EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
121 TEST_F(StreamingListenerTest, OnTestCaseStart) {
123 streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", NULL, NULL));
124 EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
127 TEST_F(StreamingListenerTest, OnTestCaseEnd) {
129 streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", NULL, NULL));
130 EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
133 TEST_F(StreamingListenerTest, OnTestStart) {
135 streamer_.OnTestStart(test_info_obj_);
136 EXPECT_EQ("event=TestStart&name=Bar\n", *output());
139 TEST_F(StreamingListenerTest, OnTestEnd) {
141 streamer_.OnTestEnd(test_info_obj_);
142 EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
145 TEST_F(StreamingListenerTest, OnTestPartResult) {
147 streamer_.OnTestPartResult(TestPartResult(
148 TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
150 // Meta characters in the failure message should be properly escaped.
152 "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
156 #endif // GTEST_CAN_STREAM_RESULTS_
158 // Provides access to otherwise private parts of the TestEventListeners class
159 // that are needed to test it.
160 class TestEventListenersAccessor {
162 static TestEventListener* GetRepeater(TestEventListeners* listeners) {
163 return listeners->repeater();
166 static void SetDefaultResultPrinter(TestEventListeners* listeners,
167 TestEventListener* listener) {
168 listeners->SetDefaultResultPrinter(listener);
170 static void SetDefaultXmlGenerator(TestEventListeners* listeners,
171 TestEventListener* listener) {
172 listeners->SetDefaultXmlGenerator(listener);
175 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
176 return listeners.EventForwardingEnabled();
179 static void SuppressEventForwarding(TestEventListeners* listeners) {
180 listeners->SuppressEventForwarding();
184 class UnitTestRecordPropertyTestHelper : public Test {
186 UnitTestRecordPropertyTestHelper() {}
188 // Forwards to UnitTest::RecordProperty() to bypass access controls.
189 void UnitTestRecordProperty(const char* key, const std::string& value) {
190 unit_test_.RecordProperty(key, value);
196 } // namespace internal
197 } // namespace testing
199 using testing::AssertionFailure;
200 using testing::AssertionResult;
201 using testing::AssertionSuccess;
202 using testing::DoubleLE;
203 using testing::EmptyTestEventListener;
204 using testing::Environment;
205 using testing::FloatLE;
206 using testing::GTEST_FLAG(also_run_disabled_tests);
207 using testing::GTEST_FLAG(break_on_failure);
208 using testing::GTEST_FLAG(catch_exceptions);
209 using testing::GTEST_FLAG(color);
210 using testing::GTEST_FLAG(death_test_use_fork);
211 using testing::GTEST_FLAG(filter);
212 using testing::GTEST_FLAG(list_tests);
213 using testing::GTEST_FLAG(output);
214 using testing::GTEST_FLAG(print_time);
215 using testing::GTEST_FLAG(random_seed);
216 using testing::GTEST_FLAG(repeat);
217 using testing::GTEST_FLAG(show_internal_stack_frames);
218 using testing::GTEST_FLAG(shuffle);
219 using testing::GTEST_FLAG(stack_trace_depth);
220 using testing::GTEST_FLAG(stream_result_to);
221 using testing::GTEST_FLAG(throw_on_failure);
222 using testing::IsNotSubstring;
223 using testing::IsSubstring;
224 using testing::Message;
225 using testing::ScopedFakeTestPartResultReporter;
226 using testing::StaticAssertTypeEq;
228 using testing::TestCase;
229 using testing::TestEventListeners;
230 using testing::TestInfo;
231 using testing::TestPartResult;
232 using testing::TestPartResultArray;
233 using testing::TestProperty;
234 using testing::TestResult;
235 using testing::TimeInMillis;
236 using testing::UnitTest;
237 using testing::internal::AddReference;
238 using testing::internal::AlwaysFalse;
239 using testing::internal::AlwaysTrue;
240 using testing::internal::AppendUserMessage;
241 using testing::internal::ArrayAwareFind;
242 using testing::internal::ArrayEq;
243 using testing::internal::CodePointToUtf8;
244 using testing::internal::CompileAssertTypesEqual;
245 using testing::internal::CopyArray;
246 using testing::internal::CountIf;
247 using testing::internal::EqFailure;
248 using testing::internal::FloatingPoint;
249 using testing::internal::ForEach;
250 using testing::internal::FormatEpochTimeInMillisAsIso8601;
251 using testing::internal::FormatTimeInMillisAsSeconds;
252 using testing::internal::GTestFlagSaver;
253 using testing::internal::GetCurrentOsStackTraceExceptTop;
254 using testing::internal::GetElementOr;
255 using testing::internal::GetNextRandomSeed;
256 using testing::internal::GetRandomSeedFromFlag;
257 using testing::internal::GetTestTypeId;
258 using testing::internal::GetTimeInMillis;
259 using testing::internal::GetTypeId;
260 using testing::internal::GetUnitTestImpl;
261 using testing::internal::ImplicitlyConvertible;
262 using testing::internal::Int32;
263 using testing::internal::Int32FromEnvOrDie;
264 using testing::internal::IsAProtocolMessage;
265 using testing::internal::IsContainer;
266 using testing::internal::IsContainerTest;
267 using testing::internal::IsNotContainer;
268 using testing::internal::NativeArray;
269 using testing::internal::ParseInt32Flag;
270 using testing::internal::RelationToSourceCopy;
271 using testing::internal::RelationToSourceReference;
272 using testing::internal::RemoveConst;
273 using testing::internal::RemoveReference;
274 using testing::internal::ShouldRunTestOnShard;
275 using testing::internal::ShouldShard;
276 using testing::internal::ShouldUseColor;
277 using testing::internal::Shuffle;
278 using testing::internal::ShuffleRange;
279 using testing::internal::SkipPrefix;
280 using testing::internal::StreamableToString;
281 using testing::internal::String;
282 using testing::internal::TestEventListenersAccessor;
283 using testing::internal::TestResultAccessor;
284 using testing::internal::UInt32;
285 using testing::internal::WideStringToUtf8;
286 using testing::internal::edit_distance::CalculateOptimalEdits;
287 using testing::internal::edit_distance::CreateUnifiedDiff;
288 using testing::internal::edit_distance::EditType;
289 using testing::internal::kMaxRandomSeed;
290 using testing::internal::kTestTypeIdInGoogleTest;
291 using testing::kMaxStackTraceDepth;
293 #if GTEST_HAS_STREAM_REDIRECTION
294 using testing::internal::CaptureStdout;
295 using testing::internal::GetCapturedStdout;
298 #if GTEST_IS_THREADSAFE
299 using testing::internal::ThreadWithParam;
302 class TestingVector : public std::vector<int> {
305 ::std::ostream& operator<<(::std::ostream& os,
306 const TestingVector& vector) {
308 for (size_t i = 0; i < vector.size(); i++) {
309 os << vector[i] << " ";
315 // This line tests that we can define tests in an unnamed namespace.
318 TEST(GetRandomSeedFromFlagTest, HandlesZero) {
319 const int seed = GetRandomSeedFromFlag(0);
321 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
324 TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
325 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
326 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
327 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
328 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
329 GetRandomSeedFromFlag(kMaxRandomSeed));
332 TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
333 const int seed1 = GetRandomSeedFromFlag(-1);
335 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
337 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
339 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
342 TEST(GetNextRandomSeedTest, WorksForValidInput) {
343 EXPECT_EQ(2, GetNextRandomSeed(1));
344 EXPECT_EQ(3, GetNextRandomSeed(2));
345 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
346 GetNextRandomSeed(kMaxRandomSeed - 1));
347 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
349 // We deliberately don't test GetNextRandomSeed() with invalid
350 // inputs, as that requires death tests, which are expensive. This
351 // is fine as GetNextRandomSeed() is internal and has a
352 // straightforward definition.
355 static void ClearCurrentTestPartResults() {
356 TestResultAccessor::ClearTestPartResults(
357 GetUnitTestImpl()->current_test_result());
362 TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
363 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
364 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
367 class SubClassOfTest : public Test {};
368 class AnotherSubClassOfTest : public Test {};
370 TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
371 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
372 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
373 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
374 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
375 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
376 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
379 // Verifies that GetTestTypeId() returns the same value, no matter it
380 // is called from inside Google Test or outside of it.
381 TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
382 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
385 // Tests FormatTimeInMillisAsSeconds().
387 TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
388 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
391 TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
392 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
393 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
394 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
395 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
396 EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
399 TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
400 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
401 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
402 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
403 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
404 EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
407 // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
408 // for particular dates below was verified in Python using
409 // datetime.datetime.fromutctimestamp(<timetamp>/1000).
411 // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
412 // have to set up a particular timezone to obtain predictable results.
413 class FormatEpochTimeInMillisAsIso8601Test : public Test {
415 // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
416 // 32 bits, even when 64-bit integer types are available. We have to
417 // force the constants to have a 64-bit type here.
418 static const TimeInMillis kMillisPerSec = 1000;
421 virtual void SetUp() {
424 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* getenv, strdup: deprecated */)
426 saved_tz_ = strdup(getenv("TZ"));
427 GTEST_DISABLE_MSC_WARNINGS_POP_()
429 // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
430 // cannot use the local time zone because the function's output depends
432 SetTimeZone("UTC+00");
435 virtual void TearDown() {
436 SetTimeZone(saved_tz_);
437 free(const_cast<char*>(saved_tz_));
441 static void SetTimeZone(const char* time_zone) {
442 // tzset() distinguishes between the TZ variable being present and empty
443 // and not being present, so we have to consider the case of time_zone
446 // ...Unless it's MSVC, whose standard library's _putenv doesn't
447 // distinguish between an empty and a missing variable.
448 const std::string env_var =
449 std::string("TZ=") + (time_zone ? time_zone : "");
450 _putenv(env_var.c_str());
451 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
453 GTEST_DISABLE_MSC_WARNINGS_POP_()
456 setenv(("TZ"), time_zone, 1);
464 const char* saved_tz_;
467 const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
469 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
470 EXPECT_EQ("2011-10-31T18:52:42",
471 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
474 TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) {
476 "2011-10-31T18:52:42",
477 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
480 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
481 EXPECT_EQ("2011-09-03T05:07:02",
482 FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
485 TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
486 EXPECT_EQ("2011-09-28T17:08:22",
487 FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
490 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
491 EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0));
494 #if GTEST_CAN_COMPARE_NULL
497 // Silences warnings: "Condition is always true", "Unreachable code"
498 # pragma option push -w-ccc -w-rch
501 // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
503 TEST(NullLiteralTest, IsTrueForNullLiterals) {
504 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
505 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
506 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
507 EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
510 // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
512 TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
513 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
514 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
515 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
516 EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
520 // Restores warnings after previous "#pragma option push" suppressed them.
524 #endif // GTEST_CAN_COMPARE_NULL
526 // Tests CodePointToUtf8().
528 // Tests that the NUL character L'\0' is encoded correctly.
529 TEST(CodePointToUtf8Test, CanEncodeNul) {
530 EXPECT_EQ("", CodePointToUtf8(L'\0'));
533 // Tests that ASCII characters are encoded correctly.
534 TEST(CodePointToUtf8Test, CanEncodeAscii) {
535 EXPECT_EQ("a", CodePointToUtf8(L'a'));
536 EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
537 EXPECT_EQ("&", CodePointToUtf8(L'&'));
538 EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
541 // Tests that Unicode code-points that have 8 to 11 bits are encoded
542 // as 110xxxxx 10xxxxxx.
543 TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
544 // 000 1101 0011 => 110-00011 10-010011
545 EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
547 // 101 0111 0110 => 110-10101 10-110110
548 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
549 // in wide strings and wide chars. In order to accomodate them, we have to
550 // introduce such character constants as integers.
551 EXPECT_EQ("\xD5\xB6",
552 CodePointToUtf8(static_cast<wchar_t>(0x576)));
555 // Tests that Unicode code-points that have 12 to 16 bits are encoded
556 // as 1110xxxx 10xxxxxx 10xxxxxx.
557 TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
558 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
559 EXPECT_EQ("\xE0\xA3\x93",
560 CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
562 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
563 EXPECT_EQ("\xEC\x9D\x8D",
564 CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
567 #if !GTEST_WIDE_STRING_USES_UTF16_
568 // Tests in this group require a wchar_t to hold > 16 bits, and thus
569 // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
570 // 16-bit wide. This code may not compile on those systems.
572 // Tests that Unicode code-points that have 17 to 21 bits are encoded
573 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
574 TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
575 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
576 EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
578 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
579 EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
581 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
582 EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
585 // Tests that encoding an invalid code-point generates the expected result.
586 TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
587 EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
590 #endif // !GTEST_WIDE_STRING_USES_UTF16_
592 // Tests WideStringToUtf8().
594 // Tests that the NUL character L'\0' is encoded correctly.
595 TEST(WideStringToUtf8Test, CanEncodeNul) {
596 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
597 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
600 // Tests that ASCII strings are encoded correctly.
601 TEST(WideStringToUtf8Test, CanEncodeAscii) {
602 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
603 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
604 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
605 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
608 // Tests that Unicode code-points that have 8 to 11 bits are encoded
609 // as 110xxxxx 10xxxxxx.
610 TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
611 // 000 1101 0011 => 110-00011 10-010011
612 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
613 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
615 // 101 0111 0110 => 110-10101 10-110110
616 const wchar_t s[] = { 0x576, '\0' };
617 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
618 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
621 // Tests that Unicode code-points that have 12 to 16 bits are encoded
622 // as 1110xxxx 10xxxxxx 10xxxxxx.
623 TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
624 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
625 const wchar_t s1[] = { 0x8D3, '\0' };
626 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
627 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
629 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
630 const wchar_t s2[] = { 0xC74D, '\0' };
631 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
632 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
635 // Tests that the conversion stops when the function encounters \0 character.
636 TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
637 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
640 // Tests that the conversion stops when the function reaches the limit
641 // specified by the 'length' parameter.
642 TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
643 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
646 #if !GTEST_WIDE_STRING_USES_UTF16_
647 // Tests that Unicode code-points that have 17 to 21 bits are encoded
648 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
649 // on the systems using UTF-16 encoding.
650 TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
651 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
652 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
653 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
655 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
656 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
657 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
660 // Tests that encoding an invalid code-point generates the expected result.
661 TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
662 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
663 WideStringToUtf8(L"\xABCDFF", -1).c_str());
665 #else // !GTEST_WIDE_STRING_USES_UTF16_
666 // Tests that surrogate pairs are encoded correctly on the systems using
667 // UTF-16 encoding in the wide strings.
668 TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
669 const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
670 EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
673 // Tests that encoding an invalid UTF-16 surrogate pair
674 // generates the expected result.
675 TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
676 // Leading surrogate is at the end of the string.
677 const wchar_t s1[] = { 0xD800, '\0' };
678 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
679 // Leading surrogate is not followed by the trailing surrogate.
680 const wchar_t s2[] = { 0xD800, 'M', '\0' };
681 EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
682 // Trailing surrogate appearas without a leading surrogate.
683 const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
684 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
686 #endif // !GTEST_WIDE_STRING_USES_UTF16_
688 // Tests that codepoint concatenation works correctly.
689 #if !GTEST_WIDE_STRING_USES_UTF16_
690 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
691 const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
699 WideStringToUtf8(s, -1).c_str());
702 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
703 const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
705 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
706 WideStringToUtf8(s, -1).c_str());
708 #endif // !GTEST_WIDE_STRING_USES_UTF16_
710 // Tests the Random class.
712 TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
713 testing::internal::Random random(42);
714 EXPECT_DEATH_IF_SUPPORTED(
716 "Cannot generate a number in the range \\[0, 0\\)");
717 EXPECT_DEATH_IF_SUPPORTED(
718 random.Generate(testing::internal::Random::kMaxRange + 1),
719 "Generation of a number in \\[0, 2147483649\\) was requested, "
720 "but this can only generate numbers in \\[0, 2147483648\\)");
723 TEST(RandomTest, GeneratesNumbersWithinRange) {
724 const UInt32 kRange = 10000;
725 testing::internal::Random random(12345);
726 for (int i = 0; i < 10; i++) {
727 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
730 testing::internal::Random random2(testing::internal::Random::kMaxRange);
731 for (int i = 0; i < 10; i++) {
732 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
736 TEST(RandomTest, RepeatsWhenReseeded) {
737 const int kSeed = 123;
738 const int kArraySize = 10;
739 const UInt32 kRange = 10000;
740 UInt32 values[kArraySize];
742 testing::internal::Random random(kSeed);
743 for (int i = 0; i < kArraySize; i++) {
744 values[i] = random.Generate(kRange);
747 random.Reseed(kSeed);
748 for (int i = 0; i < kArraySize; i++) {
749 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
753 // Tests STL container utilities.
757 static bool IsPositive(int n) { return n > 0; }
759 TEST(ContainerUtilityTest, CountIf) {
761 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
765 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
770 EXPECT_EQ(2, CountIf(v, IsPositive));
775 static int g_sum = 0;
776 static void Accumulate(int n) { g_sum += n; }
778 TEST(ContainerUtilityTest, ForEach) {
781 ForEach(v, Accumulate);
782 EXPECT_EQ(0, g_sum); // Works for an empty container;
786 ForEach(v, Accumulate);
787 EXPECT_EQ(1, g_sum); // Works for a container with one element.
792 ForEach(v, Accumulate);
793 EXPECT_EQ(321, g_sum);
796 // Tests GetElementOr().
797 TEST(ContainerUtilityTest, GetElementOr) {
799 EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
803 EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
804 EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
805 EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
806 EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
809 TEST(ContainerUtilityDeathTest, ShuffleRange) {
814 testing::internal::Random random(1);
816 EXPECT_DEATH_IF_SUPPORTED(
817 ShuffleRange(&random, -1, 1, &a),
818 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
819 EXPECT_DEATH_IF_SUPPORTED(
820 ShuffleRange(&random, 4, 4, &a),
821 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
822 EXPECT_DEATH_IF_SUPPORTED(
823 ShuffleRange(&random, 3, 2, &a),
824 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
825 EXPECT_DEATH_IF_SUPPORTED(
826 ShuffleRange(&random, 3, 4, &a),
827 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
830 class VectorShuffleTest : public Test {
832 static const int kVectorSize = 20;
834 VectorShuffleTest() : random_(1) {
835 for (int i = 0; i < kVectorSize; i++) {
836 vector_.push_back(i);
840 static bool VectorIsCorrupt(const TestingVector& vector) {
841 if (kVectorSize != static_cast<int>(vector.size())) {
845 bool found_in_vector[kVectorSize] = { false };
846 for (size_t i = 0; i < vector.size(); i++) {
847 const int e = vector[i];
848 if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
851 found_in_vector[e] = true;
854 // Vector size is correct, elements' range is correct, no
855 // duplicate elements. Therefore no corruption has occurred.
859 static bool VectorIsNotCorrupt(const TestingVector& vector) {
860 return !VectorIsCorrupt(vector);
863 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
864 for (int i = begin; i < end; i++) {
865 if (i != vector[i]) {
872 static bool RangeIsUnshuffled(
873 const TestingVector& vector, int begin, int end) {
874 return !RangeIsShuffled(vector, begin, end);
877 static bool VectorIsShuffled(const TestingVector& vector) {
878 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
881 static bool VectorIsUnshuffled(const TestingVector& vector) {
882 return !VectorIsShuffled(vector);
885 testing::internal::Random random_;
886 TestingVector vector_;
887 }; // class VectorShuffleTest
889 const int VectorShuffleTest::kVectorSize;
891 TEST_F(VectorShuffleTest, HandlesEmptyRange) {
892 // Tests an empty range at the beginning...
893 ShuffleRange(&random_, 0, 0, &vector_);
894 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
895 ASSERT_PRED1(VectorIsUnshuffled, vector_);
897 // ...in the middle...
898 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
899 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
900 ASSERT_PRED1(VectorIsUnshuffled, vector_);
903 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
904 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
905 ASSERT_PRED1(VectorIsUnshuffled, vector_);
907 // ...and past the end.
908 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
909 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
910 ASSERT_PRED1(VectorIsUnshuffled, vector_);
913 TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
914 // Tests a size one range at the beginning...
915 ShuffleRange(&random_, 0, 1, &vector_);
916 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
917 ASSERT_PRED1(VectorIsUnshuffled, vector_);
919 // ...in the middle...
920 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
921 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
922 ASSERT_PRED1(VectorIsUnshuffled, vector_);
924 // ...and at the end.
925 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
926 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
927 ASSERT_PRED1(VectorIsUnshuffled, vector_);
930 // Because we use our own random number generator and a fixed seed,
931 // we can guarantee that the following "random" tests will succeed.
933 TEST_F(VectorShuffleTest, ShufflesEntireVector) {
934 Shuffle(&random_, &vector_);
935 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
936 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
938 // Tests the first and last elements in particular to ensure that
939 // there are no off-by-one problems in our shuffle algorithm.
940 EXPECT_NE(0, vector_[0]);
941 EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
944 TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
945 const int kRangeSize = kVectorSize/2;
947 ShuffleRange(&random_, 0, kRangeSize, &vector_);
949 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
950 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
951 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
954 TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
955 const int kRangeSize = kVectorSize / 2;
956 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
958 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
959 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
960 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
963 TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
964 int kRangeSize = kVectorSize/3;
965 ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
967 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
968 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
969 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
970 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
973 TEST_F(VectorShuffleTest, ShufflesRepeatably) {
974 TestingVector vector2;
975 for (int i = 0; i < kVectorSize; i++) {
976 vector2.push_back(i);
979 random_.Reseed(1234);
980 Shuffle(&random_, &vector_);
981 random_.Reseed(1234);
982 Shuffle(&random_, &vector2);
984 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
985 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
987 for (int i = 0; i < kVectorSize; i++) {
988 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
992 // Tests the size of the AssertHelper class.
994 TEST(AssertHelperTest, AssertHelperIsSmall) {
995 // To avoid breaking clients that use lots of assertions in one
996 // function, we cannot grow the size of AssertHelper.
997 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
1000 // Tests String::EndsWithCaseInsensitive().
1001 TEST(StringTest, EndsWithCaseInsensitive) {
1002 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
1003 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
1004 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
1005 EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
1007 EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
1008 EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
1009 EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
1012 // C++Builder's preprocessor is buggy; it fails to expand macros that
1013 // appear in macro parameters after wide char literals. Provide an alias
1014 // for NULL as a workaround.
1015 static const wchar_t* const kNull = NULL;
1017 // Tests String::CaseInsensitiveWideCStringEquals
1018 TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1019 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
1020 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1021 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1022 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1023 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
1024 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1025 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1026 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1029 #if GTEST_OS_WINDOWS
1031 // Tests String::ShowWideCString().
1032 TEST(StringTest, ShowWideCString) {
1033 EXPECT_STREQ("(null)",
1034 String::ShowWideCString(NULL).c_str());
1035 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1036 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1039 # if GTEST_OS_WINDOWS_MOBILE
1040 TEST(StringTest, AnsiAndUtf16Null) {
1041 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1042 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1045 TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1046 const char* ansi = String::Utf16ToAnsi(L"str");
1047 EXPECT_STREQ("str", ansi);
1049 const WCHAR* utf16 = String::AnsiToUtf16("str");
1050 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
1054 TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1055 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1056 EXPECT_STREQ(".:\\ \"*?", ansi);
1058 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
1059 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
1062 # endif // GTEST_OS_WINDOWS_MOBILE
1064 #endif // GTEST_OS_WINDOWS
1066 // Tests TestProperty construction.
1067 TEST(TestPropertyTest, StringValue) {
1068 TestProperty property("key", "1");
1069 EXPECT_STREQ("key", property.key());
1070 EXPECT_STREQ("1", property.value());
1073 // Tests TestProperty replacing a value.
1074 TEST(TestPropertyTest, ReplaceStringValue) {
1075 TestProperty property("key", "1");
1076 EXPECT_STREQ("1", property.value());
1077 property.SetValue("2");
1078 EXPECT_STREQ("2", property.value());
1081 // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1082 // functions (i.e. their definitions cannot be inlined at the call
1083 // sites), or C++Builder won't compile the code.
1084 static void AddFatalFailure() {
1085 FAIL() << "Expected fatal failure.";
1088 static void AddNonfatalFailure() {
1089 ADD_FAILURE() << "Expected non-fatal failure.";
1092 class ScopedFakeTestPartResultReporterTest : public Test {
1093 public: // Must be public and not protected due to a bug in g++ 3.4.2.
1098 static void AddFailure(FailureMode failure) {
1099 if (failure == FATAL_FAILURE) {
1102 AddNonfatalFailure();
1107 // Tests that ScopedFakeTestPartResultReporter intercepts test
1109 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
1110 TestPartResultArray results;
1112 ScopedFakeTestPartResultReporter reporter(
1113 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1115 AddFailure(NONFATAL_FAILURE);
1116 AddFailure(FATAL_FAILURE);
1119 EXPECT_EQ(2, results.size());
1120 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1121 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1124 TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1125 TestPartResultArray results;
1127 // Tests, that the deprecated constructor still works.
1128 ScopedFakeTestPartResultReporter reporter(&results);
1129 AddFailure(NONFATAL_FAILURE);
1131 EXPECT_EQ(1, results.size());
1134 #if GTEST_IS_THREADSAFE
1136 class ScopedFakeTestPartResultReporterWithThreadsTest
1137 : public ScopedFakeTestPartResultReporterTest {
1139 static void AddFailureInOtherThread(FailureMode failure) {
1140 ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
1145 TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1146 InterceptsTestFailuresInAllThreads) {
1147 TestPartResultArray results;
1149 ScopedFakeTestPartResultReporter reporter(
1150 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1151 AddFailure(NONFATAL_FAILURE);
1152 AddFailure(FATAL_FAILURE);
1153 AddFailureInOtherThread(NONFATAL_FAILURE);
1154 AddFailureInOtherThread(FATAL_FAILURE);
1157 EXPECT_EQ(4, results.size());
1158 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1159 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1160 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1161 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1164 #endif // GTEST_IS_THREADSAFE
1166 // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1167 // work even if the failure is generated in a called function rather than
1168 // the current context.
1170 typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
1172 TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1173 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
1176 #if GTEST_HAS_GLOBAL_STRING
1177 TEST_F(ExpectFatalFailureTest, AcceptsStringObject) {
1178 EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure."));
1182 TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1183 EXPECT_FATAL_FAILURE(AddFatalFailure(),
1184 ::std::string("Expected fatal failure."));
1187 TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1188 // We have another test below to verify that the macro catches fatal
1189 // failures generated on another thread.
1190 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
1191 "Expected fatal failure.");
1195 // Silences warnings: "Condition is always true"
1196 # pragma option push -w-ccc
1199 // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1200 // function even when the statement in it contains ASSERT_*.
1202 int NonVoidFunction() {
1203 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1204 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1208 TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1212 // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1213 // current function even though 'statement' generates a fatal failure.
1215 void DoesNotAbortHelper(bool* aborted) {
1216 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1217 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1223 // Restores warnings after previous "#pragma option push" suppressed them.
1227 TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1228 bool aborted = true;
1229 DoesNotAbortHelper(&aborted);
1230 EXPECT_FALSE(aborted);
1233 // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1234 // statement that contains a macro which expands to code containing an
1235 // unprotected comma.
1237 static int global_var = 0;
1238 #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1240 TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1241 #ifndef __BORLANDC__
1242 // ICE's in C++Builder.
1243 EXPECT_FATAL_FAILURE({
1244 GTEST_USE_UNPROTECTED_COMMA_;
1249 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1250 GTEST_USE_UNPROTECTED_COMMA_;
1255 // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1257 typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1259 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1260 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1261 "Expected non-fatal failure.");
1264 #if GTEST_HAS_GLOBAL_STRING
1265 TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) {
1266 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1267 ::string("Expected non-fatal failure."));
1271 TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1272 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1273 ::std::string("Expected non-fatal failure."));
1276 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1277 // We have another test below to verify that the macro catches
1278 // non-fatal failures generated on another thread.
1279 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
1280 "Expected non-fatal failure.");
1283 // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1284 // statement that contains a macro which expands to code containing an
1285 // unprotected comma.
1286 TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1287 EXPECT_NONFATAL_FAILURE({
1288 GTEST_USE_UNPROTECTED_COMMA_;
1289 AddNonfatalFailure();
1292 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1293 GTEST_USE_UNPROTECTED_COMMA_;
1294 AddNonfatalFailure();
1298 #if GTEST_IS_THREADSAFE
1300 typedef ScopedFakeTestPartResultReporterWithThreadsTest
1301 ExpectFailureWithThreadsTest;
1303 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1304 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1305 "Expected fatal failure.");
1308 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1309 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1310 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1313 #endif // GTEST_IS_THREADSAFE
1315 // Tests the TestProperty class.
1317 TEST(TestPropertyTest, ConstructorWorks) {
1318 const TestProperty property("key", "value");
1319 EXPECT_STREQ("key", property.key());
1320 EXPECT_STREQ("value", property.value());
1323 TEST(TestPropertyTest, SetValue) {
1324 TestProperty property("key", "value_1");
1325 EXPECT_STREQ("key", property.key());
1326 property.SetValue("value_2");
1327 EXPECT_STREQ("key", property.key());
1328 EXPECT_STREQ("value_2", property.value());
1331 // Tests the TestResult class
1333 // The test fixture for testing TestResult.
1334 class TestResultTest : public Test {
1336 typedef std::vector<TestPartResult> TPRVector;
1338 // We make use of 2 TestPartResult objects,
1339 TestPartResult * pr1, * pr2;
1341 // ... and 3 TestResult objects.
1342 TestResult * r0, * r1, * r2;
1344 virtual void SetUp() {
1345 // pr1 is for success.
1346 pr1 = new TestPartResult(TestPartResult::kSuccess,
1351 // pr2 is for fatal failure.
1352 pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1354 -1, // This line number means "unknown"
1357 // Creates the TestResult objects.
1358 r0 = new TestResult();
1359 r1 = new TestResult();
1360 r2 = new TestResult();
1362 // In order to test TestResult, we need to modify its internal
1363 // state, in particular the TestPartResult vector it holds.
1364 // test_part_results() returns a const reference to this vector.
1365 // We cast it to a non-const object s.t. it can be modified (yes,
1367 TPRVector* results1 = const_cast<TPRVector*>(
1368 &TestResultAccessor::test_part_results(*r1));
1369 TPRVector* results2 = const_cast<TPRVector*>(
1370 &TestResultAccessor::test_part_results(*r2));
1372 // r0 is an empty TestResult.
1374 // r1 contains a single SUCCESS TestPartResult.
1375 results1->push_back(*pr1);
1377 // r2 contains a SUCCESS, and a FAILURE.
1378 results2->push_back(*pr1);
1379 results2->push_back(*pr2);
1382 virtual void TearDown() {
1391 // Helper that compares two two TestPartResults.
1392 static void CompareTestPartResult(const TestPartResult& expected,
1393 const TestPartResult& actual) {
1394 EXPECT_EQ(expected.type(), actual.type());
1395 EXPECT_STREQ(expected.file_name(), actual.file_name());
1396 EXPECT_EQ(expected.line_number(), actual.line_number());
1397 EXPECT_STREQ(expected.summary(), actual.summary());
1398 EXPECT_STREQ(expected.message(), actual.message());
1399 EXPECT_EQ(expected.passed(), actual.passed());
1400 EXPECT_EQ(expected.failed(), actual.failed());
1401 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1402 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
1406 // Tests TestResult::total_part_count().
1407 TEST_F(TestResultTest, total_part_count) {
1408 ASSERT_EQ(0, r0->total_part_count());
1409 ASSERT_EQ(1, r1->total_part_count());
1410 ASSERT_EQ(2, r2->total_part_count());
1413 // Tests TestResult::Passed().
1414 TEST_F(TestResultTest, Passed) {
1415 ASSERT_TRUE(r0->Passed());
1416 ASSERT_TRUE(r1->Passed());
1417 ASSERT_FALSE(r2->Passed());
1420 // Tests TestResult::Failed().
1421 TEST_F(TestResultTest, Failed) {
1422 ASSERT_FALSE(r0->Failed());
1423 ASSERT_FALSE(r1->Failed());
1424 ASSERT_TRUE(r2->Failed());
1427 // Tests TestResult::GetTestPartResult().
1429 typedef TestResultTest TestResultDeathTest;
1431 TEST_F(TestResultDeathTest, GetTestPartResult) {
1432 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1433 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1434 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1435 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
1438 // Tests TestResult has no properties when none are added.
1439 TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1440 TestResult test_result;
1441 ASSERT_EQ(0, test_result.test_property_count());
1444 // Tests TestResult has the expected property when added.
1445 TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1446 TestResult test_result;
1447 TestProperty property("key_1", "1");
1448 TestResultAccessor::RecordProperty(&test_result, "testcase", property);
1449 ASSERT_EQ(1, test_result.test_property_count());
1450 const TestProperty& actual_property = test_result.GetTestProperty(0);
1451 EXPECT_STREQ("key_1", actual_property.key());
1452 EXPECT_STREQ("1", actual_property.value());
1455 // Tests TestResult has multiple properties when added.
1456 TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1457 TestResult test_result;
1458 TestProperty property_1("key_1", "1");
1459 TestProperty property_2("key_2", "2");
1460 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1461 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1462 ASSERT_EQ(2, test_result.test_property_count());
1463 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1464 EXPECT_STREQ("key_1", actual_property_1.key());
1465 EXPECT_STREQ("1", actual_property_1.value());
1467 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1468 EXPECT_STREQ("key_2", actual_property_2.key());
1469 EXPECT_STREQ("2", actual_property_2.value());
1472 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
1473 TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1474 TestResult test_result;
1475 TestProperty property_1_1("key_1", "1");
1476 TestProperty property_2_1("key_2", "2");
1477 TestProperty property_1_2("key_1", "12");
1478 TestProperty property_2_2("key_2", "22");
1479 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
1480 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
1481 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
1482 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
1484 ASSERT_EQ(2, test_result.test_property_count());
1485 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1486 EXPECT_STREQ("key_1", actual_property_1.key());
1487 EXPECT_STREQ("12", actual_property_1.value());
1489 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1490 EXPECT_STREQ("key_2", actual_property_2.key());
1491 EXPECT_STREQ("22", actual_property_2.value());
1494 // Tests TestResult::GetTestProperty().
1495 TEST(TestResultPropertyTest, GetTestProperty) {
1496 TestResult test_result;
1497 TestProperty property_1("key_1", "1");
1498 TestProperty property_2("key_2", "2");
1499 TestProperty property_3("key_3", "3");
1500 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1501 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1502 TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
1504 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1505 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1506 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
1508 EXPECT_STREQ("key_1", fetched_property_1.key());
1509 EXPECT_STREQ("1", fetched_property_1.value());
1511 EXPECT_STREQ("key_2", fetched_property_2.key());
1512 EXPECT_STREQ("2", fetched_property_2.value());
1514 EXPECT_STREQ("key_3", fetched_property_3.key());
1515 EXPECT_STREQ("3", fetched_property_3.value());
1517 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1518 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
1521 // Tests the Test class.
1523 // It's difficult to test every public method of this class (we are
1524 // already stretching the limit of Google Test by using it to test itself!).
1525 // Fortunately, we don't have to do that, as we are already testing
1526 // the functionalities of the Test class extensively by using Google Test
1529 // Therefore, this section only contains one test.
1531 // Tests that GTestFlagSaver works on Windows and Mac.
1533 class GTestFlagSaverTest : public Test {
1535 // Saves the Google Test flags such that we can restore them later, and
1536 // then sets them to their default values. This will be called
1537 // before the first test in this test case is run.
1538 static void SetUpTestCase() {
1539 saver_ = new GTestFlagSaver;
1541 GTEST_FLAG(also_run_disabled_tests) = false;
1542 GTEST_FLAG(break_on_failure) = false;
1543 GTEST_FLAG(catch_exceptions) = false;
1544 GTEST_FLAG(death_test_use_fork) = false;
1545 GTEST_FLAG(color) = "auto";
1546 GTEST_FLAG(filter) = "";
1547 GTEST_FLAG(list_tests) = false;
1548 GTEST_FLAG(output) = "";
1549 GTEST_FLAG(print_time) = true;
1550 GTEST_FLAG(random_seed) = 0;
1551 GTEST_FLAG(repeat) = 1;
1552 GTEST_FLAG(shuffle) = false;
1553 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
1554 GTEST_FLAG(stream_result_to) = "";
1555 GTEST_FLAG(throw_on_failure) = false;
1558 // Restores the Google Test flags that the tests have modified. This will
1559 // be called after the last test in this test case is run.
1560 static void TearDownTestCase() {
1565 // Verifies that the Google Test flags have their default values, and then
1566 // modifies each of them.
1567 void VerifyAndModifyFlags() {
1568 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
1569 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1570 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1571 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
1572 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
1573 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1574 EXPECT_FALSE(GTEST_FLAG(list_tests));
1575 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
1576 EXPECT_TRUE(GTEST_FLAG(print_time));
1577 EXPECT_EQ(0, GTEST_FLAG(random_seed));
1578 EXPECT_EQ(1, GTEST_FLAG(repeat));
1579 EXPECT_FALSE(GTEST_FLAG(shuffle));
1580 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
1581 EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
1582 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
1584 GTEST_FLAG(also_run_disabled_tests) = true;
1585 GTEST_FLAG(break_on_failure) = true;
1586 GTEST_FLAG(catch_exceptions) = true;
1587 GTEST_FLAG(color) = "no";
1588 GTEST_FLAG(death_test_use_fork) = true;
1589 GTEST_FLAG(filter) = "abc";
1590 GTEST_FLAG(list_tests) = true;
1591 GTEST_FLAG(output) = "xml:foo.xml";
1592 GTEST_FLAG(print_time) = false;
1593 GTEST_FLAG(random_seed) = 1;
1594 GTEST_FLAG(repeat) = 100;
1595 GTEST_FLAG(shuffle) = true;
1596 GTEST_FLAG(stack_trace_depth) = 1;
1597 GTEST_FLAG(stream_result_to) = "localhost:1234";
1598 GTEST_FLAG(throw_on_failure) = true;
1602 // For saving Google Test flags during this test case.
1603 static GTestFlagSaver* saver_;
1606 GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
1608 // Google Test doesn't guarantee the order of tests. The following two
1609 // tests are designed to work regardless of their order.
1611 // Modifies the Google Test flags in the test body.
1612 TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1613 VerifyAndModifyFlags();
1616 // Verifies that the Google Test flags in the body of the previous test were
1617 // restored to their original values.
1618 TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1619 VerifyAndModifyFlags();
1622 // Sets an environment variable with the given name to the given
1623 // value. If the value argument is "", unsets the environment
1624 // variable. The caller must ensure that both arguments are not NULL.
1625 static void SetEnv(const char* name, const char* value) {
1626 #if GTEST_OS_WINDOWS_MOBILE
1627 // Environment variables are not supported on Windows CE.
1629 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1630 // C++Builder's putenv only stores a pointer to its parameter; we have to
1631 // ensure that the string remains valid as long as it might be needed.
1632 // We use an std::map to do so.
1633 static std::map<std::string, std::string*> added_env;
1635 // Because putenv stores a pointer to the string buffer, we can't delete the
1636 // previous string (if present) until after it's replaced.
1637 std::string *prev_env = NULL;
1638 if (added_env.find(name) != added_env.end()) {
1639 prev_env = added_env[name];
1641 added_env[name] = new std::string(
1642 (Message() << name << "=" << value).GetString());
1644 // The standard signature of putenv accepts a 'char*' argument. Other
1645 // implementations, like C++Builder's, accept a 'const char*'.
1646 // We cast away the 'const' since that would work for both variants.
1647 putenv(const_cast<char*>(added_env[name]->c_str()));
1649 #elif GTEST_OS_WINDOWS // If we are on Windows proper.
1650 _putenv((Message() << name << "=" << value).GetString().c_str());
1652 if (*value == '\0') {
1655 setenv(name, value, 1);
1657 #endif // GTEST_OS_WINDOWS_MOBILE
1660 #if !GTEST_OS_WINDOWS_MOBILE
1661 // Environment variables are not supported on Windows CE.
1663 using testing::internal::Int32FromGTestEnv;
1665 // Tests Int32FromGTestEnv().
1667 // Tests that Int32FromGTestEnv() returns the default value when the
1668 // environment variable is not set.
1669 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1670 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1671 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1674 # if !defined(GTEST_GET_INT32_FROM_ENV_)
1676 // Tests that Int32FromGTestEnv() returns the default value when the
1677 // environment variable overflows as an Int32.
1678 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1679 printf("(expecting 2 warnings)\n");
1681 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1682 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1684 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1685 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1688 // Tests that Int32FromGTestEnv() returns the default value when the
1689 // environment variable does not represent a valid decimal integer.
1690 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1691 printf("(expecting 2 warnings)\n");
1693 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1694 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1696 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1697 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1700 # endif // !defined(GTEST_GET_INT32_FROM_ENV_)
1702 // Tests that Int32FromGTestEnv() parses and returns the value of the
1703 // environment variable when it represents a valid decimal integer in
1704 // the range of an Int32.
1705 TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1706 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1707 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1709 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1710 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1712 #endif // !GTEST_OS_WINDOWS_MOBILE
1714 // Tests ParseInt32Flag().
1716 // Tests that ParseInt32Flag() returns false and doesn't change the
1717 // output value when the flag has wrong format
1718 TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1720 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1721 EXPECT_EQ(123, value);
1723 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1724 EXPECT_EQ(123, value);
1727 // Tests that ParseInt32Flag() returns false and doesn't change the
1728 // output value when the flag overflows as an Int32.
1729 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1730 printf("(expecting 2 warnings)\n");
1733 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1734 EXPECT_EQ(123, value);
1736 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1737 EXPECT_EQ(123, value);
1740 // Tests that ParseInt32Flag() returns false and doesn't change the
1741 // output value when the flag does not represent a valid decimal
1743 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1744 printf("(expecting 2 warnings)\n");
1747 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1748 EXPECT_EQ(123, value);
1750 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1751 EXPECT_EQ(123, value);
1754 // Tests that ParseInt32Flag() parses the value of the flag and
1755 // returns true when the flag represents a valid decimal integer in
1756 // the range of an Int32.
1757 TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1759 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1760 EXPECT_EQ(456, value);
1762 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1764 EXPECT_EQ(-789, value);
1767 // Tests that Int32FromEnvOrDie() parses the value of the var or
1768 // returns the correct default.
1769 // Environment variables are not supported on Windows CE.
1770 #if !GTEST_OS_WINDOWS_MOBILE
1771 TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1772 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1773 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1774 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1775 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1776 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1778 #endif // !GTEST_OS_WINDOWS_MOBILE
1780 // Tests that Int32FromEnvOrDie() aborts with an error message
1781 // if the variable is not an Int32.
1782 TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1783 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1784 EXPECT_DEATH_IF_SUPPORTED(
1785 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1789 // Tests that Int32FromEnvOrDie() aborts with an error message
1790 // if the variable cannot be represnted by an Int32.
1791 TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1792 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1793 EXPECT_DEATH_IF_SUPPORTED(
1794 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1798 // Tests that ShouldRunTestOnShard() selects all tests
1799 // where there is 1 shard.
1800 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1801 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1802 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1803 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1804 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1805 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1808 class ShouldShardTest : public testing::Test {
1810 virtual void SetUp() {
1811 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1812 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1815 virtual void TearDown() {
1816 SetEnv(index_var_, "");
1817 SetEnv(total_var_, "");
1820 const char* index_var_;
1821 const char* total_var_;
1824 // Tests that sharding is disabled if neither of the environment variables
1826 TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1827 SetEnv(index_var_, "");
1828 SetEnv(total_var_, "");
1830 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1831 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1834 // Tests that sharding is not enabled if total_shards == 1.
1835 TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1836 SetEnv(index_var_, "0");
1837 SetEnv(total_var_, "1");
1838 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1839 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1842 // Tests that sharding is enabled if total_shards > 1 and
1843 // we are not in a death test subprocess.
1844 // Environment variables are not supported on Windows CE.
1845 #if !GTEST_OS_WINDOWS_MOBILE
1846 TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1847 SetEnv(index_var_, "4");
1848 SetEnv(total_var_, "22");
1849 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1850 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1852 SetEnv(index_var_, "8");
1853 SetEnv(total_var_, "9");
1854 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1855 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1857 SetEnv(index_var_, "0");
1858 SetEnv(total_var_, "9");
1859 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1860 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1862 #endif // !GTEST_OS_WINDOWS_MOBILE
1864 // Tests that we exit in error if the sharding values are not valid.
1866 typedef ShouldShardTest ShouldShardDeathTest;
1868 TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
1869 SetEnv(index_var_, "4");
1870 SetEnv(total_var_, "4");
1871 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1873 SetEnv(index_var_, "4");
1874 SetEnv(total_var_, "-2");
1875 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1877 SetEnv(index_var_, "5");
1878 SetEnv(total_var_, "");
1879 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1881 SetEnv(index_var_, "");
1882 SetEnv(total_var_, "5");
1883 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1886 // Tests that ShouldRunTestOnShard is a partition when 5
1888 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1889 // Choose an arbitrary number of tests and shards.
1890 const int num_tests = 17;
1891 const int num_shards = 5;
1893 // Check partitioning: each test should be on exactly 1 shard.
1894 for (int test_id = 0; test_id < num_tests; test_id++) {
1895 int prev_selected_shard_index = -1;
1896 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1897 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1898 if (prev_selected_shard_index < 0) {
1899 prev_selected_shard_index = shard_index;
1901 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1902 << shard_index << " are both selected to run test " << test_id;
1908 // Check balance: This is not required by the sharding protocol, but is a
1909 // desirable property for performance.
1910 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1911 int num_tests_on_shard = 0;
1912 for (int test_id = 0; test_id < num_tests; test_id++) {
1913 num_tests_on_shard +=
1914 ShouldRunTestOnShard(num_shards, shard_index, test_id);
1916 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1920 // For the same reason we are not explicitly testing everything in the
1921 // Test class, there are no separate tests for the following classes
1922 // (except for some trivial cases):
1924 // TestCase, UnitTest, UnitTestResultPrinter.
1926 // Similarly, there are no separate tests for the following macros:
1928 // TEST, TEST_F, RUN_ALL_TESTS
1930 TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1931 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
1932 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1935 TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
1936 EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
1937 EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
1940 // When a property using a reserved key is supplied to this function, it
1941 // tests that a non-fatal failure is added, a fatal failure is not added,
1942 // and that the property is not recorded.
1943 void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1944 const TestResult& test_result, const char* key) {
1945 EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
1946 ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
1947 << "' recorded unexpectedly.";
1950 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
1952 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
1953 ASSERT_TRUE(test_info != NULL);
1954 ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
1958 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1960 const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
1961 ASSERT_TRUE(test_case != NULL);
1962 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1963 test_case->ad_hoc_test_result(), key);
1966 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
1968 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1969 UnitTest::GetInstance()->ad_hoc_test_result(), key);
1972 // Tests that property recording functions in UnitTest outside of tests
1973 // functions correcly. Creating a separate instance of UnitTest ensures it
1974 // is in a state similar to the UnitTest's singleton's between tests.
1975 class UnitTestRecordPropertyTest :
1976 public testing::internal::UnitTestRecordPropertyTestHelper {
1978 static void SetUpTestCase() {
1979 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1981 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1983 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1985 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1987 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1989 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase(
1992 Test::RecordProperty("test_case_key_1", "1");
1993 const TestCase* test_case = UnitTest::GetInstance()->current_test_case();
1994 ASSERT_TRUE(test_case != NULL);
1996 ASSERT_EQ(1, test_case->ad_hoc_test_result().test_property_count());
1997 EXPECT_STREQ("test_case_key_1",
1998 test_case->ad_hoc_test_result().GetTestProperty(0).key());
2000 test_case->ad_hoc_test_result().GetTestProperty(0).value());
2004 // Tests TestResult has the expected property when added.
2005 TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
2006 UnitTestRecordProperty("key_1", "1");
2008 ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
2010 EXPECT_STREQ("key_1",
2011 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2013 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2016 // Tests TestResult has multiple properties when added.
2017 TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
2018 UnitTestRecordProperty("key_1", "1");
2019 UnitTestRecordProperty("key_2", "2");
2021 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2023 EXPECT_STREQ("key_1",
2024 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2025 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2027 EXPECT_STREQ("key_2",
2028 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2029 EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2032 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
2033 TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
2034 UnitTestRecordProperty("key_1", "1");
2035 UnitTestRecordProperty("key_2", "2");
2036 UnitTestRecordProperty("key_1", "12");
2037 UnitTestRecordProperty("key_2", "22");
2039 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2041 EXPECT_STREQ("key_1",
2042 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2044 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2046 EXPECT_STREQ("key_2",
2047 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2049 unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2052 TEST_F(UnitTestRecordPropertyTest,
2053 AddFailureInsideTestsWhenUsingTestCaseReservedKeys) {
2054 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2056 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2058 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2060 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2062 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2064 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2068 TEST_F(UnitTestRecordPropertyTest,
2069 AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
2070 EXPECT_NONFATAL_FAILURE(
2071 Test::RecordProperty("name", "1"),
2072 "'classname', 'name', 'status', 'time', 'type_param', and 'value_param'"
2076 class UnitTestRecordPropertyTestEnvironment : public Environment {
2078 virtual void TearDown() {
2079 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2081 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2083 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2085 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2087 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2089 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2091 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2093 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase(
2098 // This will test property recording outside of any test or test case.
2099 static Environment* record_property_env =
2100 AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
2102 // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2103 // of various arities. They do not attempt to be exhaustive. Rather,
2104 // view them as smoke tests that can be easily reviewed and verified.
2105 // A more complete set of tests for predicate assertions can be found
2106 // in gtest_pred_impl_unittest.cc.
2108 // First, some predicates and predicate-formatters needed by the tests.
2110 // Returns true iff the argument is an even number.
2111 bool IsEven(int n) {
2112 return (n % 2) == 0;
2115 // A functor that returns true iff the argument is an even number.
2116 struct IsEvenFunctor {
2117 bool operator()(int n) { return IsEven(n); }
2120 // A predicate-formatter function that asserts the argument is an even
2122 AssertionResult AssertIsEven(const char* expr, int n) {
2124 return AssertionSuccess();
2128 msg << expr << " evaluates to " << n << ", which is not even.";
2129 return AssertionFailure(msg);
2132 // A predicate function that returns AssertionResult for use in
2133 // EXPECT/ASSERT_TRUE/FALSE.
2134 AssertionResult ResultIsEven(int n) {
2136 return AssertionSuccess() << n << " is even";
2138 return AssertionFailure() << n << " is odd";
2141 // A predicate function that returns AssertionResult but gives no
2142 // explanation why it succeeds. Needed for testing that
2143 // EXPECT/ASSERT_FALSE handles such functions correctly.
2144 AssertionResult ResultIsEvenNoExplanation(int n) {
2146 return AssertionSuccess();
2148 return AssertionFailure() << n << " is odd";
2151 // A predicate-formatter functor that asserts the argument is an even
2153 struct AssertIsEvenFunctor {
2154 AssertionResult operator()(const char* expr, int n) {
2155 return AssertIsEven(expr, n);
2159 // Returns true iff the sum of the arguments is an even number.
2160 bool SumIsEven2(int n1, int n2) {
2161 return IsEven(n1 + n2);
2164 // A functor that returns true iff the sum of the arguments is an even
2166 struct SumIsEven3Functor {
2167 bool operator()(int n1, int n2, int n3) {
2168 return IsEven(n1 + n2 + n3);
2172 // A predicate-formatter function that asserts the sum of the
2173 // arguments is an even number.
2174 AssertionResult AssertSumIsEven4(
2175 const char* e1, const char* e2, const char* e3, const char* e4,
2176 int n1, int n2, int n3, int n4) {
2177 const int sum = n1 + n2 + n3 + n4;
2179 return AssertionSuccess();
2183 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2184 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2185 << ") evaluates to " << sum << ", which is not even.";
2186 return AssertionFailure(msg);
2189 // A predicate-formatter functor that asserts the sum of the arguments
2190 // is an even number.
2191 struct AssertSumIsEven5Functor {
2192 AssertionResult operator()(
2193 const char* e1, const char* e2, const char* e3, const char* e4,
2194 const char* e5, int n1, int n2, int n3, int n4, int n5) {
2195 const int sum = n1 + n2 + n3 + n4 + n5;
2197 return AssertionSuccess();
2201 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2203 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2204 << ") evaluates to " << sum << ", which is not even.";
2205 return AssertionFailure(msg);
2210 // Tests unary predicate assertions.
2212 // Tests unary predicate assertions that don't use a custom formatter.
2213 TEST(Pred1Test, WithoutFormat) {
2215 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2216 ASSERT_PRED1(IsEven, 4);
2219 EXPECT_NONFATAL_FAILURE({ // NOLINT
2220 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2221 }, "This failure is expected.");
2222 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2223 "evaluates to false");
2226 // Tests unary predicate assertions that use a custom formatter.
2227 TEST(Pred1Test, WithFormat) {
2229 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2230 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2231 << "This failure is UNEXPECTED!";
2235 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2236 "n evaluates to 5, which is not even.");
2237 EXPECT_FATAL_FAILURE({ // NOLINT
2238 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2239 }, "This failure is expected.");
2242 // Tests that unary predicate assertions evaluates their arguments
2244 TEST(Pred1Test, SingleEvaluationOnFailure) {
2247 EXPECT_PRED1(IsEven, n++);
2248 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2251 EXPECT_FATAL_FAILURE({ // NOLINT
2252 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2253 << "This failure is expected.";
2254 }, "This failure is expected.");
2255 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2259 // Tests predicate assertions whose arity is >= 2.
2261 // Tests predicate assertions that don't use a custom formatter.
2262 TEST(PredTest, WithoutFormat) {
2264 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2265 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2270 EXPECT_NONFATAL_FAILURE({ // NOLINT
2271 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2272 }, "This failure is expected.");
2273 EXPECT_FATAL_FAILURE({ // NOLINT
2274 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2275 }, "evaluates to false");
2278 // Tests predicate assertions that use a custom formatter.
2279 TEST(PredTest, WithFormat) {
2281 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2282 "This failure is UNEXPECTED!";
2283 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2290 EXPECT_NONFATAL_FAILURE({ // NOLINT
2291 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2292 }, "evaluates to 13, which is not even.");
2293 EXPECT_FATAL_FAILURE({ // NOLINT
2294 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2295 << "This failure is expected.";
2296 }, "This failure is expected.");
2299 // Tests that predicate assertions evaluates their arguments
2301 TEST(PredTest, SingleEvaluationOnFailure) {
2305 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2306 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2307 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2309 // Another success case.
2314 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2315 n1++, n2++, n3++, n4++, n5++)
2316 << "This failure is UNEXPECTED!";
2317 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2318 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2319 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2320 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2321 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2325 EXPECT_NONFATAL_FAILURE({ // NOLINT
2326 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2327 << "This failure is expected.";
2328 }, "This failure is expected.");
2329 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2330 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2331 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2333 // Another failure case.
2334 n1 = n2 = n3 = n4 = 0;
2335 EXPECT_NONFATAL_FAILURE({ // NOLINT
2336 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2337 }, "evaluates to 1, which is not even.");
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.";
2345 // Some helper functions for testing using overloaded/template
2346 // functions with ASSERT_PREDn and EXPECT_PREDn.
2348 bool IsPositive(double x) {
2352 template <typename T>
2353 bool IsNegative(T x) {
2357 template <typename T1, typename T2>
2358 bool GreaterThan(T1 x1, T2 x2) {
2362 // Tests that overloaded functions can be used in *_PRED* as long as
2363 // their types are explicitly specified.
2364 TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2365 // C++Builder requires C-style casts rather than static_cast.
2366 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2367 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
2370 // Tests that template functions can be used in *_PRED* as long as
2371 // their types are explicitly specified.
2372 TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2373 EXPECT_PRED1(IsNegative<int>, -5);
2374 // Makes sure that we can handle templates with more than one
2376 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2380 // Some helper functions for testing using overloaded/template
2381 // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2383 AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2384 return n > 0 ? AssertionSuccess() :
2385 AssertionFailure(Message() << "Failure");
2388 AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2389 return x > 0 ? AssertionSuccess() :
2390 AssertionFailure(Message() << "Failure");
2393 template <typename T>
2394 AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2395 return x < 0 ? AssertionSuccess() :
2396 AssertionFailure(Message() << "Failure");
2399 template <typename T1, typename T2>
2400 AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2401 const T1& x1, const T2& x2) {
2402 return x1 == x2 ? AssertionSuccess() :
2403 AssertionFailure(Message() << "Failure");
2406 // Tests that overloaded functions can be used in *_PRED_FORMAT*
2407 // without explicitly specifying their types.
2408 TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2409 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2410 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2413 // Tests that template functions can be used in *_PRED_FORMAT* without
2414 // explicitly specifying their types.
2415 TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2416 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2417 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2421 // Tests string assertions.
2423 // Tests ASSERT_STREQ with non-NULL arguments.
2424 TEST(StringAssertionTest, ASSERT_STREQ) {
2425 const char * const p1 = "good";
2426 ASSERT_STREQ(p1, p1);
2428 // Let p2 have the same content as p1, but be at a different address.
2429 const char p2[] = "good";
2430 ASSERT_STREQ(p1, p2);
2432 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2433 "Expected: \"bad\"");
2436 // Tests ASSERT_STREQ with NULL arguments.
2437 TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2438 ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
2439 EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
2443 // Tests ASSERT_STREQ with NULL arguments.
2444 TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2445 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
2449 // Tests ASSERT_STRNE.
2450 TEST(StringAssertionTest, ASSERT_STRNE) {
2451 ASSERT_STRNE("hi", "Hi");
2452 ASSERT_STRNE("Hi", NULL);
2453 ASSERT_STRNE(NULL, "Hi");
2454 ASSERT_STRNE("", NULL);
2455 ASSERT_STRNE(NULL, "");
2456 ASSERT_STRNE("", "Hi");
2457 ASSERT_STRNE("Hi", "");
2458 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2459 "\"Hi\" vs \"Hi\"");
2462 // Tests ASSERT_STRCASEEQ.
2463 TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2464 ASSERT_STRCASEEQ("hi", "Hi");
2465 ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
2467 ASSERT_STRCASEEQ("", "");
2468 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2472 // Tests ASSERT_STRCASENE.
2473 TEST(StringAssertionTest, ASSERT_STRCASENE) {
2474 ASSERT_STRCASENE("hi1", "Hi2");
2475 ASSERT_STRCASENE("Hi", NULL);
2476 ASSERT_STRCASENE(NULL, "Hi");
2477 ASSERT_STRCASENE("", NULL);
2478 ASSERT_STRCASENE(NULL, "");
2479 ASSERT_STRCASENE("", "Hi");
2480 ASSERT_STRCASENE("Hi", "");
2481 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2485 // Tests *_STREQ on wide strings.
2486 TEST(StringAssertionTest, STREQ_Wide) {
2488 ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
2491 ASSERT_STREQ(L"", L"");
2493 // Non-null vs NULL.
2494 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
2498 EXPECT_STREQ(L"Hi", L"Hi");
2501 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2504 // Strings containing wide characters.
2505 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2508 // The streaming variation.
2509 EXPECT_NONFATAL_FAILURE({ // NOLINT
2510 EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
2511 }, "Expected failure");
2514 // Tests *_STRNE on wide strings.
2515 TEST(StringAssertionTest, STRNE_Wide) {
2517 EXPECT_NONFATAL_FAILURE({ // NOLINT
2518 EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
2522 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2525 // Non-null vs NULL.
2526 ASSERT_STRNE(L"non-null", NULL);
2529 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2533 EXPECT_STRNE(L"abc", L"Abc");
2535 // Strings containing wide characters.
2536 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2539 // The streaming variation.
2540 ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
2543 // Tests for ::testing::IsSubstring().
2545 // Tests that IsSubstring() returns the correct result when the input
2546 // argument type is const char*.
2547 TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2548 EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
2549 EXPECT_FALSE(IsSubstring("", "", "b", NULL));
2550 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2552 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
2553 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2556 // Tests that IsSubstring() returns the correct result when the input
2557 // argument type is const wchar_t*.
2558 TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2559 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2560 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
2561 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2563 EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
2564 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2567 // Tests that IsSubstring() generates the correct message when the input
2568 // argument type is const char*.
2569 TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2570 EXPECT_STREQ("Value of: needle_expr\n"
2571 " Actual: \"needle\"\n"
2572 "Expected: a substring of haystack_expr\n"
2573 "Which is: \"haystack\"",
2574 IsSubstring("needle_expr", "haystack_expr",
2575 "needle", "haystack").failure_message());
2578 // Tests that IsSubstring returns the correct result when the input
2579 // argument type is ::std::string.
2580 TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2581 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2582 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2585 #if GTEST_HAS_STD_WSTRING
2586 // Tests that IsSubstring returns the correct result when the input
2587 // argument type is ::std::wstring.
2588 TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2589 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2590 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2593 // Tests that IsSubstring() generates the correct message when the input
2594 // argument type is ::std::wstring.
2595 TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2596 EXPECT_STREQ("Value of: needle_expr\n"
2597 " Actual: L\"needle\"\n"
2598 "Expected: a substring of haystack_expr\n"
2599 "Which is: L\"haystack\"",
2601 "needle_expr", "haystack_expr",
2602 ::std::wstring(L"needle"), L"haystack").failure_message());
2605 #endif // GTEST_HAS_STD_WSTRING
2607 // Tests for ::testing::IsNotSubstring().
2609 // Tests that IsNotSubstring() returns the correct result when the input
2610 // argument type is const char*.
2611 TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2612 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2613 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2616 // Tests that IsNotSubstring() returns the correct result when the input
2617 // argument type is const wchar_t*.
2618 TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2619 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2620 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2623 // Tests that IsNotSubstring() generates the correct message when the input
2624 // argument type is const wchar_t*.
2625 TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2626 EXPECT_STREQ("Value of: needle_expr\n"
2627 " Actual: L\"needle\"\n"
2628 "Expected: not a substring of haystack_expr\n"
2629 "Which is: L\"two needles\"",
2631 "needle_expr", "haystack_expr",
2632 L"needle", L"two needles").failure_message());
2635 // Tests that IsNotSubstring returns the correct result when the input
2636 // argument type is ::std::string.
2637 TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2638 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2639 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2642 // Tests that IsNotSubstring() generates the correct message when the input
2643 // argument type is ::std::string.
2644 TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2645 EXPECT_STREQ("Value of: needle_expr\n"
2646 " Actual: \"needle\"\n"
2647 "Expected: not a substring of haystack_expr\n"
2648 "Which is: \"two needles\"",
2650 "needle_expr", "haystack_expr",
2651 ::std::string("needle"), "two needles").failure_message());
2654 #if GTEST_HAS_STD_WSTRING
2656 // Tests that IsNotSubstring returns the correct result when the input
2657 // argument type is ::std::wstring.
2658 TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2660 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2661 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2664 #endif // GTEST_HAS_STD_WSTRING
2666 // Tests floating-point assertions.
2668 template <typename RawType>
2669 class FloatingPointTest : public Test {
2671 // Pre-calculated numbers to be used by the tests.
2673 RawType close_to_positive_zero;
2674 RawType close_to_negative_zero;
2675 RawType further_from_negative_zero;
2677 RawType close_to_one;
2678 RawType further_from_one;
2681 RawType close_to_infinity;
2682 RawType further_from_infinity;
2688 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2689 typedef typename Floating::Bits Bits;
2691 virtual void SetUp() {
2692 const size_t max_ulps = Floating::kMaxUlps;
2694 // The bits that represent 0.0.
2695 const Bits zero_bits = Floating(0).bits();
2697 // Makes some numbers close to 0.0.
2698 values_.close_to_positive_zero = Floating::ReinterpretBits(
2699 zero_bits + max_ulps/2);
2700 values_.close_to_negative_zero = -Floating::ReinterpretBits(
2701 zero_bits + max_ulps - max_ulps/2);
2702 values_.further_from_negative_zero = -Floating::ReinterpretBits(
2703 zero_bits + max_ulps + 1 - max_ulps/2);
2705 // The bits that represent 1.0.
2706 const Bits one_bits = Floating(1).bits();
2708 // Makes some numbers close to 1.0.
2709 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2710 values_.further_from_one = Floating::ReinterpretBits(
2711 one_bits + max_ulps + 1);
2714 values_.infinity = Floating::Infinity();
2716 // The bits that represent +infinity.
2717 const Bits infinity_bits = Floating(values_.infinity).bits();
2719 // Makes some numbers close to infinity.
2720 values_.close_to_infinity = Floating::ReinterpretBits(
2721 infinity_bits - max_ulps);
2722 values_.further_from_infinity = Floating::ReinterpretBits(
2723 infinity_bits - max_ulps - 1);
2725 // Makes some NAN's. Sets the most significant bit of the fraction so that
2726 // our NaN's are quiet; trying to process a signaling NaN would raise an
2727 // exception if our environment enables floating point exceptions.
2728 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2729 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2730 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2731 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
2735 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2738 static TestValues values_;
2741 template <typename RawType>
2742 typename FloatingPointTest<RawType>::TestValues
2743 FloatingPointTest<RawType>::values_;
2745 // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2746 typedef FloatingPointTest<float> FloatTest;
2748 // Tests that the size of Float::Bits matches the size of float.
2749 TEST_F(FloatTest, Size) {
2753 // Tests comparing with +0 and -0.
2754 TEST_F(FloatTest, Zeros) {
2755 EXPECT_FLOAT_EQ(0.0, -0.0);
2756 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2758 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2762 // Tests comparing numbers close to 0.
2764 // This ensures that *_FLOAT_EQ handles the sign correctly and no
2765 // overflow occurs when comparing numbers whose absolute value is very
2767 TEST_F(FloatTest, AlmostZeros) {
2768 // In C++Builder, names within local classes (such as used by
2769 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2770 // scoping class. Use a static local alias as a workaround.
2771 // We use the assignment syntax since some compilers, like Sun Studio,
2772 // don't allow initializing references using construction syntax
2774 static const FloatTest::TestValues& v = this->values_;
2776 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2777 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2778 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2780 EXPECT_FATAL_FAILURE({ // NOLINT
2781 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2782 v.further_from_negative_zero);
2783 }, "v.further_from_negative_zero");
2786 // Tests comparing numbers close to each other.
2787 TEST_F(FloatTest, SmallDiff) {
2788 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2789 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2790 "values_.further_from_one");
2793 // Tests comparing numbers far apart.
2794 TEST_F(FloatTest, LargeDiff) {
2795 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2799 // Tests comparing with infinity.
2801 // This ensures that no overflow occurs when comparing numbers whose
2802 // absolute value is very large.
2803 TEST_F(FloatTest, Infinity) {
2804 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2805 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
2806 #if !GTEST_OS_SYMBIAN
2807 // Nokia's STLport crashes if we try to output infinity or NaN.
2808 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2809 "-values_.infinity");
2811 // This is interesting as the representations of infinity and nan1
2812 // are only 1 DLP apart.
2813 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2815 #endif // !GTEST_OS_SYMBIAN
2818 // Tests that comparing with NAN always returns false.
2819 TEST_F(FloatTest, NaN) {
2820 #if !GTEST_OS_SYMBIAN
2821 // Nokia's STLport crashes if we try to output infinity or NaN.
2823 // In C++Builder, names within local classes (such as used by
2824 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2825 // scoping class. Use a static local alias as a workaround.
2826 // We use the assignment syntax since some compilers, like Sun Studio,
2827 // don't allow initializing references using construction syntax
2829 static const FloatTest::TestValues& v = this->values_;
2831 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2833 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2835 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2838 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2840 #endif // !GTEST_OS_SYMBIAN
2843 // Tests that *_FLOAT_EQ are reflexive.
2844 TEST_F(FloatTest, Reflexive) {
2845 EXPECT_FLOAT_EQ(0.0, 0.0);
2846 EXPECT_FLOAT_EQ(1.0, 1.0);
2847 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
2850 // Tests that *_FLOAT_EQ are commutative.
2851 TEST_F(FloatTest, Commutative) {
2852 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2853 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2855 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2856 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2860 // Tests EXPECT_NEAR.
2861 TEST_F(FloatTest, EXPECT_NEAR) {
2862 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2863 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2864 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2865 "The difference between 1.0f and 1.5f is 0.5, "
2866 "which exceeds 0.25f");
2867 // To work around a bug in gcc 2.95.0, there is intentionally no
2868 // space after the first comma in the previous line.
2871 // Tests ASSERT_NEAR.
2872 TEST_F(FloatTest, ASSERT_NEAR) {
2873 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2874 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2875 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
2876 "The difference between 1.0f and 1.5f is 0.5, "
2877 "which exceeds 0.25f");
2878 // To work around a bug in gcc 2.95.0, there is intentionally no
2879 // space after the first comma in the previous line.
2882 // Tests the cases where FloatLE() should succeed.
2883 TEST_F(FloatTest, FloatLESucceeds) {
2884 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2885 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
2887 // or when val1 is greater than, but almost equals to, val2.
2888 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2891 // Tests the cases where FloatLE() should fail.
2892 TEST_F(FloatTest, FloatLEFails) {
2893 // When val1 is greater than val2 by a large margin,
2894 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2895 "(2.0f) <= (1.0f)");
2897 // or by a small yet non-negligible margin,
2898 EXPECT_NONFATAL_FAILURE({ // NOLINT
2899 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2900 }, "(values_.further_from_one) <= (1.0f)");
2902 #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2903 // Nokia's STLport crashes if we try to output infinity or NaN.
2904 // C++Builder gives bad results for ordered comparisons involving NaNs
2905 // due to compiler bugs.
2906 EXPECT_NONFATAL_FAILURE({ // NOLINT
2907 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2908 }, "(values_.nan1) <= (values_.infinity)");
2909 EXPECT_NONFATAL_FAILURE({ // NOLINT
2910 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2911 }, "(-values_.infinity) <= (values_.nan1)");
2912 EXPECT_FATAL_FAILURE({ // NOLINT
2913 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2914 }, "(values_.nan1) <= (values_.nan1)");
2915 #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
2918 // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2919 typedef FloatingPointTest<double> DoubleTest;
2921 // Tests that the size of Double::Bits matches the size of double.
2922 TEST_F(DoubleTest, Size) {
2926 // Tests comparing with +0 and -0.
2927 TEST_F(DoubleTest, Zeros) {
2928 EXPECT_DOUBLE_EQ(0.0, -0.0);
2929 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2931 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2935 // Tests comparing numbers close to 0.
2937 // This ensures that *_DOUBLE_EQ handles the sign correctly and no
2938 // overflow occurs when comparing numbers whose absolute value is very
2940 TEST_F(DoubleTest, AlmostZeros) {
2941 // In C++Builder, names within local classes (such as used by
2942 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2943 // scoping class. Use a static local alias as a workaround.
2944 // We use the assignment syntax since some compilers, like Sun Studio,
2945 // don't allow initializing references using construction syntax
2947 static const DoubleTest::TestValues& v = this->values_;
2949 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2950 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2951 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2953 EXPECT_FATAL_FAILURE({ // NOLINT
2954 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2955 v.further_from_negative_zero);
2956 }, "v.further_from_negative_zero");
2959 // Tests comparing numbers close to each other.
2960 TEST_F(DoubleTest, SmallDiff) {
2961 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2962 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2963 "values_.further_from_one");
2966 // Tests comparing numbers far apart.
2967 TEST_F(DoubleTest, LargeDiff) {
2968 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
2972 // Tests comparing with infinity.
2974 // This ensures that no overflow occurs when comparing numbers whose
2975 // absolute value is very large.
2976 TEST_F(DoubleTest, Infinity) {
2977 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
2978 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
2979 #if !GTEST_OS_SYMBIAN
2980 // Nokia's STLport crashes if we try to output infinity or NaN.
2981 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
2982 "-values_.infinity");
2984 // This is interesting as the representations of infinity_ and nan1_
2985 // are only 1 DLP apart.
2986 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
2988 #endif // !GTEST_OS_SYMBIAN
2991 // Tests that comparing with NAN always returns false.
2992 TEST_F(DoubleTest, NaN) {
2993 #if !GTEST_OS_SYMBIAN
2994 // In C++Builder, names within local classes (such as used by
2995 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2996 // scoping class. Use a static local alias as a workaround.
2997 // We use the assignment syntax since some compilers, like Sun Studio,
2998 // don't allow initializing references using construction syntax
3000 static const DoubleTest::TestValues& v = this->values_;
3002 // Nokia's STLport crashes if we try to output infinity or NaN.
3003 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
3005 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
3006 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3007 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
3009 #endif // !GTEST_OS_SYMBIAN
3012 // Tests that *_DOUBLE_EQ are reflexive.
3013 TEST_F(DoubleTest, Reflexive) {
3014 EXPECT_DOUBLE_EQ(0.0, 0.0);
3015 EXPECT_DOUBLE_EQ(1.0, 1.0);
3016 #if !GTEST_OS_SYMBIAN
3017 // Nokia's STLport crashes if we try to output infinity or NaN.
3018 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
3019 #endif // !GTEST_OS_SYMBIAN
3022 // Tests that *_DOUBLE_EQ are commutative.
3023 TEST_F(DoubleTest, Commutative) {
3024 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3025 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
3027 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3028 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3032 // Tests EXPECT_NEAR.
3033 TEST_F(DoubleTest, EXPECT_NEAR) {
3034 EXPECT_NEAR(-1.0, -1.1, 0.2);
3035 EXPECT_NEAR(2.0, 3.0, 1.0);
3036 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3037 "The difference between 1.0 and 1.5 is 0.5, "
3038 "which exceeds 0.25");
3039 // To work around a bug in gcc 2.95.0, there is intentionally no
3040 // space after the first comma in the previous statement.
3043 // Tests ASSERT_NEAR.
3044 TEST_F(DoubleTest, ASSERT_NEAR) {
3045 ASSERT_NEAR(-1.0, -1.1, 0.2);
3046 ASSERT_NEAR(2.0, 3.0, 1.0);
3047 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3048 "The difference between 1.0 and 1.5 is 0.5, "
3049 "which exceeds 0.25");
3050 // To work around a bug in gcc 2.95.0, there is intentionally no
3051 // space after the first comma in the previous statement.
3054 // Tests the cases where DoubleLE() should succeed.
3055 TEST_F(DoubleTest, DoubleLESucceeds) {
3056 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3057 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
3059 // or when val1 is greater than, but almost equals to, val2.
3060 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3063 // Tests the cases where DoubleLE() should fail.
3064 TEST_F(DoubleTest, DoubleLEFails) {
3065 // When val1 is greater than val2 by a large margin,
3066 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
3069 // or by a small yet non-negligible margin,
3070 EXPECT_NONFATAL_FAILURE({ // NOLINT
3071 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3072 }, "(values_.further_from_one) <= (1.0)");
3074 #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3075 // Nokia's STLport crashes if we try to output infinity or NaN.
3076 // C++Builder gives bad results for ordered comparisons involving NaNs
3077 // due to compiler bugs.
3078 EXPECT_NONFATAL_FAILURE({ // NOLINT
3079 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3080 }, "(values_.nan1) <= (values_.infinity)");
3081 EXPECT_NONFATAL_FAILURE({ // NOLINT
3082 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3083 }, " (-values_.infinity) <= (values_.nan1)");
3084 EXPECT_FATAL_FAILURE({ // NOLINT
3085 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3086 }, "(values_.nan1) <= (values_.nan1)");
3087 #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
3091 // Verifies that a test or test case whose name starts with DISABLED_ is
3094 // A test whose name starts with DISABLED_.
3096 TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3097 FAIL() << "Unexpected failure: Disabled test should not be run.";
3100 // A test whose name does not start with DISABLED_.
3102 TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3106 // A test case whose name starts with DISABLED_.
3108 TEST(DISABLED_TestCase, TestShouldNotRun) {
3109 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3112 // A test case and test whose names start with DISABLED_.
3114 TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
3115 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3118 // Check that when all tests in a test case are disabled, SetupTestCase() and
3119 // TearDownTestCase() are not called.
3120 class DisabledTestsTest : public Test {
3122 static void SetUpTestCase() {
3123 FAIL() << "Unexpected failure: All tests disabled in test case. "
3124 "SetupTestCase() should not be called.";
3127 static void TearDownTestCase() {
3128 FAIL() << "Unexpected failure: All tests disabled in test case. "
3129 "TearDownTestCase() should not be called.";
3133 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3134 FAIL() << "Unexpected failure: Disabled test should not be run.";
3137 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3138 FAIL() << "Unexpected failure: Disabled test should not be run.";
3141 // Tests that disabled typed tests aren't run.
3143 #if GTEST_HAS_TYPED_TEST
3145 template <typename T>
3146 class TypedTest : public Test {
3149 typedef testing::Types<int, double> NumericTypes;
3150 TYPED_TEST_CASE(TypedTest, NumericTypes);
3152 TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3153 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3156 template <typename T>
3157 class DISABLED_TypedTest : public Test {
3160 TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
3162 TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3163 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3166 #endif // GTEST_HAS_TYPED_TEST
3168 // Tests that disabled type-parameterized tests aren't run.
3170 #if GTEST_HAS_TYPED_TEST_P
3172 template <typename T>
3173 class TypedTestP : public Test {
3176 TYPED_TEST_CASE_P(TypedTestP);
3178 TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3179 FAIL() << "Unexpected failure: "
3180 << "Disabled type-parameterized test should not run.";
3183 REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
3185 INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
3187 template <typename T>
3188 class DISABLED_TypedTestP : public Test {
3191 TYPED_TEST_CASE_P(DISABLED_TypedTestP);
3193 TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3194 FAIL() << "Unexpected failure: "
3195 << "Disabled type-parameterized test should not run.";
3198 REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
3200 INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
3202 #endif // GTEST_HAS_TYPED_TEST_P
3204 // Tests that assertion macros evaluate their arguments exactly once.
3206 class SingleEvaluationTest : public Test {
3207 public: // Must be public and not protected due to a bug in g++ 3.4.2.
3208 // This helper function is needed by the FailedASSERT_STREQ test
3209 // below. It's public to work around C++Builder's bug with scoping local
3211 static void CompareAndIncrementCharPtrs() {
3212 ASSERT_STREQ(p1_++, p2_++);
3215 // This helper function is needed by the FailedASSERT_NE test below. It's
3216 // public to work around C++Builder's bug with scoping local classes.
3217 static void CompareAndIncrementInts() {
3218 ASSERT_NE(a_++, b_++);
3222 SingleEvaluationTest() {
3229 static const char* const s1_;
3230 static const char* const s2_;
3231 static const char* p1_;
3232 static const char* p2_;
3238 const char* const SingleEvaluationTest::s1_ = "01234";
3239 const char* const SingleEvaluationTest::s2_ = "abcde";
3240 const char* SingleEvaluationTest::p1_;
3241 const char* SingleEvaluationTest::p2_;
3242 int SingleEvaluationTest::a_;
3243 int SingleEvaluationTest::b_;
3245 // Tests that when ASSERT_STREQ fails, it evaluates its arguments
3247 TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3248 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3250 EXPECT_EQ(s1_ + 1, p1_);
3251 EXPECT_EQ(s2_ + 1, p2_);
3254 // Tests that string assertion arguments are evaluated exactly once.
3255 TEST_F(SingleEvaluationTest, ASSERT_STR) {
3256 // successful EXPECT_STRNE
3257 EXPECT_STRNE(p1_++, p2_++);
3258 EXPECT_EQ(s1_ + 1, p1_);
3259 EXPECT_EQ(s2_ + 1, p2_);
3261 // failed EXPECT_STRCASEEQ
3262 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3264 EXPECT_EQ(s1_ + 2, p1_);
3265 EXPECT_EQ(s2_ + 2, p2_);
3268 // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3270 TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3271 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3272 "(a_++) != (b_++)");
3277 // Tests that assertion arguments are evaluated exactly once.
3278 TEST_F(SingleEvaluationTest, OtherCases) {
3279 // successful EXPECT_TRUE
3280 EXPECT_TRUE(0 == a_++); // NOLINT
3283 // failed EXPECT_TRUE
3284 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3287 // successful EXPECT_GT
3288 EXPECT_GT(a_++, b_++);
3293 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3297 // successful ASSERT_TRUE
3298 ASSERT_TRUE(0 < a_++); // NOLINT
3301 // successful ASSERT_GT
3302 ASSERT_GT(a_++, b_++);
3307 #if GTEST_HAS_EXCEPTIONS
3309 void ThrowAnInteger() {
3313 // Tests that assertion arguments are evaluated exactly once.
3314 TEST_F(SingleEvaluationTest, ExceptionTests) {
3315 // successful EXPECT_THROW
3316 EXPECT_THROW({ // NOLINT
3322 // failed EXPECT_THROW, throws different
3323 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3326 }, bool), "throws a different type");
3329 // failed EXPECT_THROW, throws nothing
3330 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3333 // successful EXPECT_NO_THROW
3334 EXPECT_NO_THROW(a_++);
3337 // failed EXPECT_NO_THROW
3338 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3344 // successful EXPECT_ANY_THROW
3345 EXPECT_ANY_THROW({ // NOLINT
3351 // failed EXPECT_ANY_THROW
3352 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3356 #endif // GTEST_HAS_EXCEPTIONS
3358 // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3359 class NoFatalFailureTest : public Test {
3362 void FailsNonFatal() {
3363 ADD_FAILURE() << "some non-fatal failure";
3366 FAIL() << "some fatal failure";
3369 void DoAssertNoFatalFailureOnFails() {
3370 ASSERT_NO_FATAL_FAILURE(Fails());
3371 ADD_FAILURE() << "shold not reach here.";
3374 void DoExpectNoFatalFailureOnFails() {
3375 EXPECT_NO_FATAL_FAILURE(Fails());
3376 ADD_FAILURE() << "other failure";
3380 TEST_F(NoFatalFailureTest, NoFailure) {
3381 EXPECT_NO_FATAL_FAILURE(Succeeds());
3382 ASSERT_NO_FATAL_FAILURE(Succeeds());
3385 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3386 EXPECT_NONFATAL_FAILURE(
3387 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3388 "some non-fatal failure");
3389 EXPECT_NONFATAL_FAILURE(
3390 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3391 "some non-fatal failure");
3394 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3395 TestPartResultArray gtest_failures;
3397 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3398 DoAssertNoFatalFailureOnFails();
3400 ASSERT_EQ(2, gtest_failures.size());
3401 EXPECT_EQ(TestPartResult::kFatalFailure,
3402 gtest_failures.GetTestPartResult(0).type());
3403 EXPECT_EQ(TestPartResult::kFatalFailure,
3404 gtest_failures.GetTestPartResult(1).type());
3405 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3406 gtest_failures.GetTestPartResult(0).message());
3407 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3408 gtest_failures.GetTestPartResult(1).message());
3411 TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3412 TestPartResultArray gtest_failures;
3414 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3415 DoExpectNoFatalFailureOnFails();
3417 ASSERT_EQ(3, gtest_failures.size());
3418 EXPECT_EQ(TestPartResult::kFatalFailure,
3419 gtest_failures.GetTestPartResult(0).type());
3420 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3421 gtest_failures.GetTestPartResult(1).type());
3422 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3423 gtest_failures.GetTestPartResult(2).type());
3424 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3425 gtest_failures.GetTestPartResult(0).message());
3426 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3427 gtest_failures.GetTestPartResult(1).message());
3428 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3429 gtest_failures.GetTestPartResult(2).message());
3432 TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3433 TestPartResultArray gtest_failures;
3435 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3436 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3438 ASSERT_EQ(2, gtest_failures.size());
3439 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3440 gtest_failures.GetTestPartResult(0).type());
3441 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3442 gtest_failures.GetTestPartResult(1).type());
3443 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3444 gtest_failures.GetTestPartResult(0).message());
3445 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3446 gtest_failures.GetTestPartResult(1).message());
3449 // Tests non-string assertions.
3451 std::string EditsToString(const std::vector<EditType>& edits) {
3453 for (size_t i = 0; i < edits.size(); ++i) {
3454 static const char kEdits[] = " +-/";
3455 out.append(1, kEdits[edits[i]]);
3460 std::vector<size_t> CharsToIndices(const std::string& str) {
3461 std::vector<size_t> out;
3462 for (size_t i = 0; i < str.size(); ++i) {
3463 out.push_back(str[i]);
3468 std::vector<std::string> CharsToLines(const std::string& str) {
3469 std::vector<std::string> out;
3470 for (size_t i = 0; i < str.size(); ++i) {
3471 out.push_back(str.substr(i, 1));
3476 TEST(EditDistance, TestCases) {
3481 const char* expected_edits;
3482 const char* expected_diff;
3484 static const Case kCases[] = {
3486 {__LINE__, "A", "A", " ", ""},
3487 {__LINE__, "ABCDE", "ABCDE", " ", ""},
3489 {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
3490 {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
3492 {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
3493 {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
3495 {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
3496 {__LINE__, "ABCD", "abcd", "////",
3497 "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
3499 {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
3500 "@@ -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"},
3501 {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
3502 "@@ -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"},
3503 {__LINE__, "ABCDE", "BCDCD", "- +/",
3504 "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
3505 {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
3506 "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
3507 "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
3509 for (const Case* c = kCases; c->left; ++c) {
3510 EXPECT_TRUE(c->expected_edits ==
3511 EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3512 CharsToIndices(c->right))))
3513 << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
3514 << EditsToString(CalculateOptimalEdits(
3515 CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
3516 EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
3517 CharsToLines(c->right)))
3518 << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
3519 << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
3524 // Tests EqFailure(), used for implementing *EQ* assertions.
3525 TEST(AssertionTest, EqFailure) {
3526 const std::string foo_val("5"), bar_val("6");
3527 const std::string msg1(
3528 EqFailure("foo", "bar", foo_val, bar_val, false)
3529 .failure_message());
3533 "To be equal to: bar\n"
3537 const std::string msg2(
3538 EqFailure("foo", "6", foo_val, bar_val, false)
3539 .failure_message());
3543 "To be equal to: 6",
3546 const std::string msg3(
3547 EqFailure("5", "bar", foo_val, bar_val, false)
3548 .failure_message());
3551 "To be equal to: bar\n"
3555 const std::string msg4(
3556 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3559 "To be equal to: 6",
3562 const std::string msg5(
3563 EqFailure("foo", "bar",
3564 std::string("\"x\""), std::string("\"y\""),
3565 true).failure_message());
3568 " Which is: \"x\"\n"
3569 "To be equal to: bar\n"
3570 " Which is: \"y\"\n"
3575 TEST(AssertionTest, EqFailureWithDiff) {
3576 const std::string left(
3577 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
3578 const std::string right(
3579 "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
3580 const std::string msg1(
3581 EqFailure("left", "right", left, right, false).failure_message());
3585 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3586 "To be equal to: right\n"
3587 " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3588 "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
3589 "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
3593 // Tests AppendUserMessage(), used for implementing the *EQ* macros.
3594 TEST(AssertionTest, AppendUserMessage) {
3595 const std::string foo("foo");
3599 AppendUserMessage(foo, msg).c_str());
3602 EXPECT_STREQ("foo\nbar",
3603 AppendUserMessage(foo, msg).c_str());
3607 // Silences warnings: "Condition is always true", "Unreachable code"
3608 # pragma option push -w-ccc -w-rch
3611 // Tests ASSERT_TRUE.
3612 TEST(AssertionTest, ASSERT_TRUE) {
3613 ASSERT_TRUE(2 > 1); // NOLINT
3614 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3618 // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3619 TEST(AssertionTest, AssertTrueWithAssertionResult) {
3620 ASSERT_TRUE(ResultIsEven(2));
3621 #ifndef __BORLANDC__
3622 // ICE's in C++Builder.
3623 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3624 "Value of: ResultIsEven(3)\n"
3625 " Actual: false (3 is odd)\n"
3628 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3629 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3630 "Value of: ResultIsEvenNoExplanation(3)\n"
3631 " Actual: false (3 is odd)\n"
3635 // Tests ASSERT_FALSE.
3636 TEST(AssertionTest, ASSERT_FALSE) {
3637 ASSERT_FALSE(2 < 1); // NOLINT
3638 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3644 // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3645 TEST(AssertionTest, AssertFalseWithAssertionResult) {
3646 ASSERT_FALSE(ResultIsEven(3));
3647 #ifndef __BORLANDC__
3648 // ICE's in C++Builder.
3649 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3650 "Value of: ResultIsEven(2)\n"
3651 " Actual: true (2 is even)\n"
3654 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3655 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3656 "Value of: ResultIsEvenNoExplanation(2)\n"
3662 // Restores warnings after previous "#pragma option push" supressed them
3666 // Tests using ASSERT_EQ on double values. The purpose is to make
3667 // sure that the specialization we did for integer and anonymous enums
3668 // isn't used for double arguments.
3669 TEST(ExpectTest, ASSERT_EQ_Double) {
3671 ASSERT_EQ(5.6, 5.6);
3674 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3679 TEST(AssertionTest, ASSERT_EQ) {
3680 ASSERT_EQ(5, 2 + 3);
3681 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3683 "To be equal to: 2*3\n"
3687 // Tests ASSERT_EQ(NULL, pointer).
3688 #if GTEST_CAN_COMPARE_NULL
3689 TEST(AssertionTest, ASSERT_EQ_NULL) {
3691 const char* p = NULL;
3692 // Some older GCC versions may issue a spurious waring in this or the next
3693 // assertion statement. This warning should not be suppressed with
3694 // static_cast since the test verifies the ability to use bare NULL as the
3695 // expected parameter to the macro.
3700 EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
3701 "To be equal to: &n\n");
3703 #endif // GTEST_CAN_COMPARE_NULL
3705 // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3706 // treated as a null pointer by the compiler, we need to make sure
3707 // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3708 // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3709 TEST(ExpectTest, ASSERT_EQ_0) {
3716 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3721 TEST(AssertionTest, ASSERT_NE) {
3723 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3724 "Expected: ('a') != ('a'), "
3725 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3729 TEST(AssertionTest, ASSERT_LE) {
3732 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3733 "Expected: (2) <= (0), actual: 2 vs 0");
3737 TEST(AssertionTest, ASSERT_LT) {
3739 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3740 "Expected: (2) < (2), actual: 2 vs 2");
3744 TEST(AssertionTest, ASSERT_GE) {
3747 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3748 "Expected: (2) >= (3), actual: 2 vs 3");
3752 TEST(AssertionTest, ASSERT_GT) {
3754 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3755 "Expected: (2) > (2), actual: 2 vs 2");
3758 #if GTEST_HAS_EXCEPTIONS
3760 void ThrowNothing() {}
3762 // Tests ASSERT_THROW.
3763 TEST(AssertionTest, ASSERT_THROW) {
3764 ASSERT_THROW(ThrowAnInteger(), int);
3766 # ifndef __BORLANDC__
3768 // ICE's in C++Builder 2007 and 2009.
3769 EXPECT_FATAL_FAILURE(
3770 ASSERT_THROW(ThrowAnInteger(), bool),
3771 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3772 " Actual: it throws a different type.");
3775 EXPECT_FATAL_FAILURE(
3776 ASSERT_THROW(ThrowNothing(), bool),
3777 "Expected: ThrowNothing() throws an exception of type bool.\n"
3778 " Actual: it throws nothing.");
3781 // Tests ASSERT_NO_THROW.
3782 TEST(AssertionTest, ASSERT_NO_THROW) {
3783 ASSERT_NO_THROW(ThrowNothing());
3784 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3785 "Expected: ThrowAnInteger() doesn't throw an exception."
3786 "\n Actual: it throws.");
3789 // Tests ASSERT_ANY_THROW.
3790 TEST(AssertionTest, ASSERT_ANY_THROW) {
3791 ASSERT_ANY_THROW(ThrowAnInteger());
3792 EXPECT_FATAL_FAILURE(
3793 ASSERT_ANY_THROW(ThrowNothing()),
3794 "Expected: ThrowNothing() throws an exception.\n"
3795 " Actual: it doesn't.");
3798 #endif // GTEST_HAS_EXCEPTIONS
3800 // Makes sure we deal with the precedence of <<. This test should
3802 TEST(AssertionTest, AssertPrecedence) {
3803 ASSERT_EQ(1 < 2, true);
3804 bool false_value = false;
3805 ASSERT_EQ(true && false_value, false);
3808 // A subroutine used by the following test.
3809 void TestEq1(int x) {
3813 // Tests calling a test subroutine that's not part of a fixture.
3814 TEST(AssertionTest, NonFixtureSubroutine) {
3815 EXPECT_FATAL_FAILURE(TestEq1(2),
3816 "To be equal to: x");
3819 // An uncopyable class.
3822 explicit Uncopyable(int a_value) : value_(a_value) {}
3824 int value() const { return value_; }
3825 bool operator==(const Uncopyable& rhs) const {
3826 return value() == rhs.value();
3829 // This constructor deliberately has no implementation, as we don't
3830 // want this class to be copyable.
3831 Uncopyable(const Uncopyable&); // NOLINT
3836 ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3837 return os << value.value();
3841 bool IsPositiveUncopyable(const Uncopyable& x) {
3842 return x.value() > 0;
3845 // A subroutine used by the following test.
3846 void TestAssertNonPositive() {
3848 ASSERT_PRED1(IsPositiveUncopyable, y);
3850 // A subroutine used by the following test.
3851 void TestAssertEqualsUncopyable() {
3857 // Tests that uncopyable objects can be used in assertions.
3858 TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3860 ASSERT_PRED1(IsPositiveUncopyable, x);
3862 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3863 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3864 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3865 "Expected: x\n Which is: 5\nTo be equal to: y\n Which is: -1");
3868 // Tests that uncopyable objects can be used in expects.
3869 TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3871 EXPECT_PRED1(IsPositiveUncopyable, x);
3873 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3874 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3876 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3877 "Expected: x\n Which is: 5\nTo be equal to: y\n Which is: -1");
3885 TEST(AssertionTest, NamedEnum) {
3886 EXPECT_EQ(kE1, kE1);
3887 EXPECT_LT(kE1, kE2);
3888 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3889 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
3892 // The version of gcc used in XCode 2.2 has a bug and doesn't allow
3893 // anonymous enums in assertions. Therefore the following test is not
3895 // Sun Studio and HP aCC also reject this code.
3896 #if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3898 // Tests using assertions with anonymous enums.
3904 // We want to test the case where the size of the anonymous enum is
3905 // larger than sizeof(int), to make sure our implementation of the
3906 // assertions doesn't truncate the enums. However, MSVC
3907 // (incorrectly) doesn't allow an enum value to exceed the range of
3908 // an int, so this has to be conditionally compiled.
3910 // On Linux, kCaseB and kCaseA have the same value when truncated to
3911 // int size. We want to test whether this will confuse the
3913 kCaseB = testing::internal::kMaxBiggestInt,
3919 # endif // GTEST_OS_LINUX
3924 TEST(AssertionTest, AnonymousEnum) {
3927 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
3929 # endif // GTEST_OS_LINUX
3931 EXPECT_EQ(kCaseA, kCaseA);
3932 EXPECT_NE(kCaseA, kCaseB);
3933 EXPECT_LT(kCaseA, kCaseB);
3934 EXPECT_LE(kCaseA, kCaseB);
3935 EXPECT_GT(kCaseB, kCaseA);
3936 EXPECT_GE(kCaseA, kCaseA);
3937 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
3938 "(kCaseA) >= (kCaseB)");
3939 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
3942 ASSERT_EQ(kCaseA, kCaseA);
3943 ASSERT_NE(kCaseA, kCaseB);
3944 ASSERT_LT(kCaseA, kCaseB);
3945 ASSERT_LE(kCaseA, kCaseB);
3946 ASSERT_GT(kCaseB, kCaseA);
3947 ASSERT_GE(kCaseA, kCaseA);
3949 # ifndef __BORLANDC__
3951 // ICE's in C++Builder.
3952 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
3953 "To be equal to: kCaseB");
3954 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3958 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
3962 #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
3964 #if GTEST_OS_WINDOWS
3966 static HRESULT UnexpectedHRESULTFailure() {
3967 return E_UNEXPECTED;
3970 static HRESULT OkHRESULTSuccess() {
3974 static HRESULT FalseHRESULTSuccess() {
3978 // HRESULT assertion tests test both zero and non-zero
3979 // success codes as well as failure message for each.
3981 // Windows CE doesn't support message texts.
3982 TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3983 EXPECT_HRESULT_SUCCEEDED(S_OK);
3984 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3986 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3987 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3988 " Actual: 0x8000FFFF");
3991 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3992 ASSERT_HRESULT_SUCCEEDED(S_OK);
3993 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
3995 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3996 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3997 " Actual: 0x8000FFFF");
4000 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
4001 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
4003 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
4004 "Expected: (OkHRESULTSuccess()) fails.\n"
4006 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
4007 "Expected: (FalseHRESULTSuccess()) fails.\n"
4011 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4012 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
4014 # ifndef __BORLANDC__
4016 // ICE's in C++Builder 2007 and 2009.
4017 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4018 "Expected: (OkHRESULTSuccess()) fails.\n"
4022 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4023 "Expected: (FalseHRESULTSuccess()) fails.\n"
4027 // Tests that streaming to the HRESULT macros works.
4028 TEST(HRESULTAssertionTest, Streaming) {
4029 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4030 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4031 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4032 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4034 EXPECT_NONFATAL_FAILURE(
4035 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4036 "expected failure");
4038 # ifndef __BORLANDC__
4040 // ICE's in C++Builder 2007 and 2009.
4041 EXPECT_FATAL_FAILURE(
4042 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4043 "expected failure");
4046 EXPECT_NONFATAL_FAILURE(
4047 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4048 "expected failure");
4050 EXPECT_FATAL_FAILURE(
4051 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4052 "expected failure");
4055 #endif // GTEST_OS_WINDOWS
4058 // Silences warnings: "Condition is always true", "Unreachable code"
4059 # pragma option push -w-ccc -w-rch
4062 // Tests that the assertion macros behave like single statements.
4063 TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4065 ASSERT_TRUE(false) << "This should never be executed; "
4066 "It's a compilation test only.";
4069 EXPECT_FALSE(false);
4079 EXPECT_GT(3, 2) << "";
4082 #if GTEST_HAS_EXCEPTIONS
4083 // Tests that the compiler will not complain about unreachable code in the
4084 // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4085 TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4088 EXPECT_THROW(throw 1, int);
4089 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4090 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4091 EXPECT_NO_THROW(n++);
4092 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4093 EXPECT_ANY_THROW(throw 1);
4094 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4097 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4099 EXPECT_THROW(ThrowNothing(), bool);
4102 EXPECT_THROW(ThrowAnInteger(), int);
4107 EXPECT_NO_THROW(ThrowAnInteger());
4110 EXPECT_NO_THROW(ThrowNothing());
4115 EXPECT_ANY_THROW(ThrowNothing());
4118 EXPECT_ANY_THROW(ThrowAnInteger());
4122 #endif // GTEST_HAS_EXCEPTIONS
4124 TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4126 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4127 << "It's a compilation test only.";
4132 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4137 EXPECT_NO_FATAL_FAILURE(SUCCEED());
4144 ASSERT_NO_FATAL_FAILURE(SUCCEED());
4147 // Tests that the assertion macros work well with switch statements.
4148 TEST(AssertionSyntaxTest, WorksWithSwitch) {
4158 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4160 // Binary assertions are implemented using a different code path
4161 // than the Boolean assertions. Hence we test them separately.
4165 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4173 #if GTEST_HAS_EXCEPTIONS
4175 void ThrowAString() {
4176 throw "std::string";
4179 // Test that the exception assertion macros compile and work with const
4181 TEST(AssertionSyntaxTest, WorksWithConst) {
4182 ASSERT_THROW(ThrowAString(), const char*);
4184 EXPECT_THROW(ThrowAString(), const char*);
4187 #endif // GTEST_HAS_EXCEPTIONS
4193 // Tests that Google Test tracks SUCCEED*.
4194 TEST(SuccessfulAssertionTest, SUCCEED) {
4197 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4200 // Tests that Google Test doesn't track successful EXPECT_*.
4201 TEST(SuccessfulAssertionTest, EXPECT) {
4203 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4206 // Tests that Google Test doesn't track successful EXPECT_STR*.
4207 TEST(SuccessfulAssertionTest, EXPECT_STR) {
4208 EXPECT_STREQ("", "");
4209 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4212 // Tests that Google Test doesn't track successful ASSERT_*.
4213 TEST(SuccessfulAssertionTest, ASSERT) {
4215 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4218 // Tests that Google Test doesn't track successful ASSERT_STR*.
4219 TEST(SuccessfulAssertionTest, ASSERT_STR) {
4220 ASSERT_STREQ("", "");
4221 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4224 } // namespace testing
4228 // Tests the message streaming variation of assertions.
4230 TEST(AssertionWithMessageTest, EXPECT) {
4231 EXPECT_EQ(1, 1) << "This should succeed.";
4232 EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4233 "Expected failure #1");
4234 EXPECT_LE(1, 2) << "This should succeed.";
4235 EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4236 "Expected failure #2.");
4237 EXPECT_GE(1, 0) << "This should succeed.";
4238 EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4239 "Expected failure #3.");
4241 EXPECT_STREQ("1", "1") << "This should succeed.";
4242 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4243 "Expected failure #4.");
4244 EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4245 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4246 "Expected failure #5.");
4248 EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4249 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4250 "Expected failure #6.");
4251 EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4254 TEST(AssertionWithMessageTest, ASSERT) {
4255 ASSERT_EQ(1, 1) << "This should succeed.";
4256 ASSERT_NE(1, 2) << "This should succeed.";
4257 ASSERT_LE(1, 2) << "This should succeed.";
4258 ASSERT_LT(1, 2) << "This should succeed.";
4259 ASSERT_GE(1, 0) << "This should succeed.";
4260 EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4261 "Expected failure.");
4264 TEST(AssertionWithMessageTest, ASSERT_STR) {
4265 ASSERT_STREQ("1", "1") << "This should succeed.";
4266 ASSERT_STRNE("1", "2") << "This should succeed.";
4267 ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4268 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4269 "Expected failure.");
4272 TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4273 ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4274 ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4275 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.", // NOLINT
4277 // To work around a bug in gcc 2.95.0, there is intentionally no
4278 // space after the first comma in the previous statement.
4281 // Tests using ASSERT_FALSE with a streamed message.
4282 TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4283 ASSERT_FALSE(false) << "This shouldn't fail.";
4284 EXPECT_FATAL_FAILURE({ // NOLINT
4285 ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4286 << " evaluates to " << true;
4287 }, "Expected failure");
4290 // Tests using FAIL with a streamed message.
4291 TEST(AssertionWithMessageTest, FAIL) {
4292 EXPECT_FATAL_FAILURE(FAIL() << 0,
4296 // Tests using SUCCEED with a streamed message.
4297 TEST(AssertionWithMessageTest, SUCCEED) {
4298 SUCCEED() << "Success == " << 1;
4301 // Tests using ASSERT_TRUE with a streamed message.
4302 TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4303 ASSERT_TRUE(true) << "This should succeed.";
4304 ASSERT_TRUE(true) << true;
4305 EXPECT_FATAL_FAILURE({ // NOLINT
4306 ASSERT_TRUE(false) << static_cast<const char *>(NULL)
4307 << static_cast<char *>(NULL);
4311 #if GTEST_OS_WINDOWS
4312 // Tests using wide strings in assertion messages.
4313 TEST(AssertionWithMessageTest, WideStringMessage) {
4314 EXPECT_NONFATAL_FAILURE({ // NOLINT
4315 EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4316 }, "This failure is expected.");
4317 EXPECT_FATAL_FAILURE({ // NOLINT
4318 ASSERT_EQ(1, 2) << "This failure is "
4319 << L"expected too.\x8120";
4320 }, "This failure is expected too.");
4322 #endif // GTEST_OS_WINDOWS
4324 // Tests EXPECT_TRUE.
4325 TEST(ExpectTest, EXPECT_TRUE) {
4326 EXPECT_TRUE(true) << "Intentional success";
4327 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4328 "Intentional failure #1.");
4329 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4330 "Intentional failure #2.");
4331 EXPECT_TRUE(2 > 1); // NOLINT
4332 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4336 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4340 // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4341 TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4342 EXPECT_TRUE(ResultIsEven(2));
4343 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4344 "Value of: ResultIsEven(3)\n"
4345 " Actual: false (3 is odd)\n"
4347 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4348 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4349 "Value of: ResultIsEvenNoExplanation(3)\n"
4350 " Actual: false (3 is odd)\n"
4354 // Tests EXPECT_FALSE with a streamed message.
4355 TEST(ExpectTest, EXPECT_FALSE) {
4356 EXPECT_FALSE(2 < 1); // NOLINT
4357 EXPECT_FALSE(false) << "Intentional success";
4358 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4359 "Intentional failure #1.");
4360 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4361 "Intentional failure #2.");
4362 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4366 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4370 // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4371 TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4372 EXPECT_FALSE(ResultIsEven(3));
4373 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4374 "Value of: ResultIsEven(2)\n"
4375 " Actual: true (2 is even)\n"
4377 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4378 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4379 "Value of: ResultIsEvenNoExplanation(2)\n"
4385 // Restores warnings after previous "#pragma option push" supressed them
4390 TEST(ExpectTest, EXPECT_EQ) {
4391 EXPECT_EQ(5, 2 + 3);
4392 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4394 "To be equal to: 2*3\n"
4396 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4400 // Tests using EXPECT_EQ on double values. The purpose is to make
4401 // sure that the specialization we did for integer and anonymous enums
4402 // isn't used for double arguments.
4403 TEST(ExpectTest, EXPECT_EQ_Double) {
4405 EXPECT_EQ(5.6, 5.6);
4408 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4412 #if GTEST_CAN_COMPARE_NULL
4413 // Tests EXPECT_EQ(NULL, pointer).
4414 TEST(ExpectTest, EXPECT_EQ_NULL) {
4416 const char* p = NULL;
4417 // Some older GCC versions may issue a spurious warning in this or the next
4418 // assertion statement. This warning should not be suppressed with
4419 // static_cast since the test verifies the ability to use bare NULL as the
4420 // expected parameter to the macro.
4425 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
4426 "To be equal to: &n\n");
4428 #endif // GTEST_CAN_COMPARE_NULL
4430 // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4431 // treated as a null pointer by the compiler, we need to make sure
4432 // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4433 // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4434 TEST(ExpectTest, EXPECT_EQ_0) {
4441 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4446 TEST(ExpectTest, EXPECT_NE) {
4449 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4450 "Expected: ('a') != ('a'), "
4451 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4452 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4454 char* const p0 = NULL;
4455 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4457 // Only way to get the Nokia compiler to compile the cast
4458 // is to have a separate void* variable first. Putting
4459 // the two casts on the same line doesn't work, neither does
4460 // a direct C-style to char*.
4461 void* pv1 = (void*)0x1234; // NOLINT
4462 char* const p1 = reinterpret_cast<char*>(pv1);
4463 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4468 TEST(ExpectTest, EXPECT_LE) {
4471 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4472 "Expected: (2) <= (0), actual: 2 vs 0");
4473 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4478 TEST(ExpectTest, EXPECT_LT) {
4480 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4481 "Expected: (2) < (2), actual: 2 vs 2");
4482 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4487 TEST(ExpectTest, EXPECT_GE) {
4490 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4491 "Expected: (2) >= (3), actual: 2 vs 3");
4492 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4497 TEST(ExpectTest, EXPECT_GT) {
4499 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4500 "Expected: (2) > (2), actual: 2 vs 2");
4501 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4505 #if GTEST_HAS_EXCEPTIONS
4507 // Tests EXPECT_THROW.
4508 TEST(ExpectTest, EXPECT_THROW) {
4509 EXPECT_THROW(ThrowAnInteger(), int);
4510 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4511 "Expected: ThrowAnInteger() throws an exception of "
4512 "type bool.\n Actual: it throws a different type.");
4513 EXPECT_NONFATAL_FAILURE(
4514 EXPECT_THROW(ThrowNothing(), bool),
4515 "Expected: ThrowNothing() throws an exception of type bool.\n"
4516 " Actual: it throws nothing.");
4519 // Tests EXPECT_NO_THROW.
4520 TEST(ExpectTest, EXPECT_NO_THROW) {
4521 EXPECT_NO_THROW(ThrowNothing());
4522 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4523 "Expected: ThrowAnInteger() doesn't throw an "
4524 "exception.\n Actual: it throws.");
4527 // Tests EXPECT_ANY_THROW.
4528 TEST(ExpectTest, EXPECT_ANY_THROW) {
4529 EXPECT_ANY_THROW(ThrowAnInteger());
4530 EXPECT_NONFATAL_FAILURE(
4531 EXPECT_ANY_THROW(ThrowNothing()),
4532 "Expected: ThrowNothing() throws an exception.\n"
4533 " Actual: it doesn't.");
4536 #endif // GTEST_HAS_EXCEPTIONS
4538 // Make sure we deal with the precedence of <<.
4539 TEST(ExpectTest, ExpectPrecedence) {
4540 EXPECT_EQ(1 < 2, true);
4541 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4542 "To be equal to: true && false");
4546 // Tests the StreamableToString() function.
4548 // Tests using StreamableToString() on a scalar.
4549 TEST(StreamableToStringTest, Scalar) {
4550 EXPECT_STREQ("5", StreamableToString(5).c_str());
4553 // Tests using StreamableToString() on a non-char pointer.
4554 TEST(StreamableToStringTest, Pointer) {
4557 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4560 // Tests using StreamableToString() on a NULL non-char pointer.
4561 TEST(StreamableToStringTest, NullPointer) {
4563 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4566 // Tests using StreamableToString() on a C string.
4567 TEST(StreamableToStringTest, CString) {
4568 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4571 // Tests using StreamableToString() on a NULL C string.
4572 TEST(StreamableToStringTest, NullCString) {
4574 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4577 // Tests using streamable values as assertion messages.
4579 // Tests using std::string as an assertion message.
4580 TEST(StreamableTest, string) {
4581 static const std::string str(
4582 "This failure message is a std::string, and is expected.");
4583 EXPECT_FATAL_FAILURE(FAIL() << str,
4587 // Tests that we can output strings containing embedded NULs.
4588 // Limited to Linux because we can only do this with std::string's.
4589 TEST(StreamableTest, stringWithEmbeddedNUL) {
4590 static const char char_array_with_nul[] =
4591 "Here's a NUL\0 and some more string";
4592 static const std::string string_with_nul(char_array_with_nul,
4593 sizeof(char_array_with_nul)
4594 - 1); // drops the trailing NUL
4595 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4596 "Here's a NUL\\0 and some more string");
4599 // Tests that we can output a NUL char.
4600 TEST(StreamableTest, NULChar) {
4601 EXPECT_FATAL_FAILURE({ // NOLINT
4602 FAIL() << "A NUL" << '\0' << " and some more string";
4603 }, "A NUL\\0 and some more string");
4606 // Tests using int as an assertion message.
4607 TEST(StreamableTest, int) {
4608 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4612 // Tests using NULL char pointer as an assertion message.
4614 // In MSVC, streaming a NULL char * causes access violation. Google Test
4615 // implemented a workaround (substituting "(null)" for NULL). This
4616 // tests whether the workaround works.
4617 TEST(StreamableTest, NullCharPtr) {
4618 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
4622 // Tests that basic IO manipulators (endl, ends, and flush) can be
4623 // streamed to testing::Message.
4624 TEST(StreamableTest, BasicIoManip) {
4625 EXPECT_FATAL_FAILURE({ // NOLINT
4626 FAIL() << "Line 1." << std::endl
4627 << "A NUL char " << std::ends << std::flush << " in line 2.";
4628 }, "Line 1.\nA NUL char \\0 in line 2.");
4631 // Tests the macros that haven't been covered so far.
4633 void AddFailureHelper(bool* aborted) {
4635 ADD_FAILURE() << "Intentional failure.";
4639 // Tests ADD_FAILURE.
4640 TEST(MacroTest, ADD_FAILURE) {
4641 bool aborted = true;
4642 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4643 "Intentional failure.");
4644 EXPECT_FALSE(aborted);
4647 // Tests ADD_FAILURE_AT.
4648 TEST(MacroTest, ADD_FAILURE_AT) {
4649 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4650 // the failure message contains the user-streamed part.
4651 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4653 // Verifies that the user-streamed part is optional.
4654 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4656 // Unfortunately, we cannot verify that the failure message contains
4657 // the right file path and line number the same way, as
4658 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4659 // line number. Instead, we do that in gtest_output_test_.cc.
4663 TEST(MacroTest, FAIL) {
4664 EXPECT_FATAL_FAILURE(FAIL(),
4666 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4667 "Intentional failure.");
4671 TEST(MacroTest, SUCCEED) {
4673 SUCCEED() << "Explicit success.";
4676 // Tests for EXPECT_EQ() and ASSERT_EQ().
4678 // These tests fail *intentionally*, s.t. the failure messages can be
4679 // generated and tested.
4681 // We have different tests for different argument types.
4683 // Tests using bool values in {EXPECT|ASSERT}_EQ.
4684 TEST(EqAssertionTest, Bool) {
4685 EXPECT_EQ(true, true);
4686 EXPECT_FATAL_FAILURE({
4687 bool false_value = false;
4688 ASSERT_EQ(false_value, true);
4689 }, "To be equal to: true");
4692 // Tests using int values in {EXPECT|ASSERT}_EQ.
4693 TEST(EqAssertionTest, Int) {
4695 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4699 // Tests using time_t values in {EXPECT|ASSERT}_EQ.
4700 TEST(EqAssertionTest, Time_T) {
4701 EXPECT_EQ(static_cast<time_t>(0),
4702 static_cast<time_t>(0));
4703 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4704 static_cast<time_t>(1234)),
4708 // Tests using char values in {EXPECT|ASSERT}_EQ.
4709 TEST(EqAssertionTest, Char) {
4710 ASSERT_EQ('z', 'z');
4711 const char ch = 'b';
4712 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4714 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4718 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4719 TEST(EqAssertionTest, WideChar) {
4720 EXPECT_EQ(L'b', L'b');
4722 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4723 " Expected: L'\0'\n"
4724 " Which is: L'\0' (0, 0x0)\n"
4725 "To be equal to: L'x'\n"
4726 " Which is: L'x' (120, 0x78)");
4728 static wchar_t wchar;
4730 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4733 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
4734 "To be equal to: wchar");
4737 // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4738 TEST(EqAssertionTest, StdString) {
4739 // Compares a const char* to an std::string that has identical
4741 ASSERT_EQ("Test", ::std::string("Test"));
4743 // Compares two identical std::strings.
4744 static const ::std::string str1("A * in the middle");
4745 static const ::std::string str2(str1);
4746 EXPECT_EQ(str1, str2);
4748 // Compares a const char* to an std::string that has different
4750 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4753 // Compares an std::string to a char* that has different content.
4754 char* const p1 = const_cast<char*>("foo");
4755 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4758 // Compares two std::strings that have different contents, one of
4759 // which having a NUL character in the middle. This should fail.
4760 static ::std::string str3(str1);
4762 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4763 "To be equal to: str3\n"
4764 " Which is: \"A \\0 in the middle\"");
4767 #if GTEST_HAS_STD_WSTRING
4769 // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4770 TEST(EqAssertionTest, StdWideString) {
4771 // Compares two identical std::wstrings.
4772 const ::std::wstring wstr1(L"A * in the middle");
4773 const ::std::wstring wstr2(wstr1);
4774 ASSERT_EQ(wstr1, wstr2);
4776 // Compares an std::wstring to a const wchar_t* that has identical
4778 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4779 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4781 // Compares an std::wstring to a const wchar_t* that has different
4783 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4784 EXPECT_NONFATAL_FAILURE({ // NOLINT
4785 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4788 // Compares two std::wstrings that have different contents, one of
4789 // which having a NUL character in the middle.
4790 ::std::wstring wstr3(wstr1);
4791 wstr3.at(2) = L'\0';
4792 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4795 // Compares a wchar_t* to an std::wstring that has different
4797 EXPECT_FATAL_FAILURE({ // NOLINT
4798 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4802 #endif // GTEST_HAS_STD_WSTRING
4804 #if GTEST_HAS_GLOBAL_STRING
4805 // Tests using ::string values in {EXPECT|ASSERT}_EQ.
4806 TEST(EqAssertionTest, GlobalString) {
4807 // Compares a const char* to a ::string that has identical content.
4808 EXPECT_EQ("Test", ::string("Test"));
4810 // Compares two identical ::strings.
4811 const ::string str1("A * in the middle");
4812 const ::string str2(str1);
4813 ASSERT_EQ(str1, str2);
4815 // Compares a ::string to a const char* that has different content.
4816 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
4819 // Compares two ::strings that have different contents, one of which
4820 // having a NUL character in the middle.
4821 ::string str3(str1);
4823 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
4826 // Compares a ::string to a char* that has different content.
4827 EXPECT_FATAL_FAILURE({ // NOLINT
4828 ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
4832 #endif // GTEST_HAS_GLOBAL_STRING
4834 #if GTEST_HAS_GLOBAL_WSTRING
4836 // Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
4837 TEST(EqAssertionTest, GlobalWideString) {
4838 // Compares two identical ::wstrings.
4839 static const ::wstring wstr1(L"A * in the middle");
4840 static const ::wstring wstr2(wstr1);
4841 EXPECT_EQ(wstr1, wstr2);
4843 // Compares a const wchar_t* to a ::wstring that has identical content.
4844 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4845 ASSERT_EQ(kTestX8119, ::wstring(kTestX8119));
4847 // Compares a const wchar_t* to a ::wstring that has different
4849 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4850 EXPECT_NONFATAL_FAILURE({ // NOLINT
4851 EXPECT_EQ(kTestX8120, ::wstring(kTestX8119));
4854 // Compares a wchar_t* to a ::wstring that has different content.
4855 wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
4856 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
4859 // Compares two ::wstrings that have different contents, one of which
4860 // having a NUL character in the middle.
4861 static ::wstring wstr3;
4863 wstr3.at(2) = L'\0';
4864 EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
4868 #endif // GTEST_HAS_GLOBAL_WSTRING
4870 // Tests using char pointers in {EXPECT|ASSERT}_EQ.
4871 TEST(EqAssertionTest, CharPointer) {
4872 char* const p0 = NULL;
4873 // Only way to get the Nokia compiler to compile the cast
4874 // is to have a separate void* variable first. Putting
4875 // the two casts on the same line doesn't work, neither does
4876 // a direct C-style to char*.
4877 void* pv1 = (void*)0x1234; // NOLINT
4878 void* pv2 = (void*)0xABC0; // NOLINT
4879 char* const p1 = reinterpret_cast<char*>(pv1);
4880 char* const p2 = reinterpret_cast<char*>(pv2);
4883 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4884 "To be equal to: p2");
4885 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4887 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4888 reinterpret_cast<char*>(0xABC0)),
4892 // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4893 TEST(EqAssertionTest, WideCharPointer) {
4894 wchar_t* const p0 = NULL;
4895 // Only way to get the Nokia compiler to compile the cast
4896 // is to have a separate void* variable first. Putting
4897 // the two casts on the same line doesn't work, neither does
4898 // a direct C-style to char*.
4899 void* pv1 = (void*)0x1234; // NOLINT
4900 void* pv2 = (void*)0xABC0; // NOLINT
4901 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4902 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4905 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4906 "To be equal to: p2");
4907 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4909 void* pv3 = (void*)0x1234; // NOLINT
4910 void* pv4 = (void*)0xABC0; // NOLINT
4911 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4912 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4913 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4917 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4918 TEST(EqAssertionTest, OtherPointer) {
4919 ASSERT_EQ(static_cast<const int*>(NULL),
4920 static_cast<const int*>(NULL));
4921 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
4922 reinterpret_cast<const int*>(0x1234)),
4926 // A class that supports binary comparison operators but not streaming.
4927 class UnprintableChar {
4929 explicit UnprintableChar(char ch) : char_(ch) {}
4931 bool operator==(const UnprintableChar& rhs) const {
4932 return char_ == rhs.char_;
4934 bool operator!=(const UnprintableChar& rhs) const {
4935 return char_ != rhs.char_;
4937 bool operator<(const UnprintableChar& rhs) const {
4938 return char_ < rhs.char_;
4940 bool operator<=(const UnprintableChar& rhs) const {
4941 return char_ <= rhs.char_;
4943 bool operator>(const UnprintableChar& rhs) const {
4944 return char_ > rhs.char_;
4946 bool operator>=(const UnprintableChar& rhs) const {
4947 return char_ >= rhs.char_;
4954 // Tests that ASSERT_EQ() and friends don't require the arguments to
4956 TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4957 const UnprintableChar x('x'), y('y');
4965 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
4966 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
4967 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
4968 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
4969 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
4971 // Code tested by EXPECT_FATAL_FAILURE cannot reference local
4972 // variables, so we have to write UnprintableChar('x') instead of x.
4973 #ifndef __BORLANDC__
4974 // ICE's in C++Builder.
4975 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
4976 "1-byte object <78>");
4977 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4978 "1-byte object <78>");
4980 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4981 "1-byte object <79>");
4982 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4983 "1-byte object <78>");
4984 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4985 "1-byte object <79>");
4988 // Tests the FRIEND_TEST macro.
4990 // This class has a private member we want to test. We will test it
4991 // both in a TEST and in a TEST_F.
4997 int Bar() const { return 1; }
4999 // Declares the friend tests that can access the private member
5001 FRIEND_TEST(FRIEND_TEST_Test, TEST);
5002 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
5005 // Tests that the FRIEND_TEST declaration allows a TEST to access a
5006 // class's private members. This should compile.
5007 TEST(FRIEND_TEST_Test, TEST) {
5008 ASSERT_EQ(1, Foo().Bar());
5011 // The fixture needed to test using FRIEND_TEST with TEST_F.
5012 class FRIEND_TEST_Test2 : public Test {
5017 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
5018 // class's private members. This should compile.
5019 TEST_F(FRIEND_TEST_Test2, TEST_F) {
5020 ASSERT_EQ(1, foo.Bar());
5023 // Tests the life cycle of Test objects.
5025 // The test fixture for testing the life cycle of Test objects.
5027 // This class counts the number of live test objects that uses this
5029 class TestLifeCycleTest : public Test {
5031 // Constructor. Increments the number of test objects that uses
5033 TestLifeCycleTest() { count_++; }
5035 // Destructor. Decrements the number of test objects that uses this
5037 ~TestLifeCycleTest() { count_--; }
5039 // Returns the number of live test objects that uses this fixture.
5040 int count() const { return count_; }
5046 int TestLifeCycleTest::count_ = 0;
5048 // Tests the life cycle of test objects.
5049 TEST_F(TestLifeCycleTest, Test1) {
5050 // There should be only one test object in this test case that's
5052 ASSERT_EQ(1, count());
5055 // Tests the life cycle of test objects.
5056 TEST_F(TestLifeCycleTest, Test2) {
5057 // After Test1 is done and Test2 is started, there should still be
5058 // only one live test object, as the object for Test1 should've been
5060 ASSERT_EQ(1, count());
5065 // Tests that the copy constructor works when it is NOT optimized away by
5067 TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5068 // Checks that the copy constructor doesn't try to dereference NULL pointers
5069 // in the source object.
5070 AssertionResult r1 = AssertionSuccess();
5071 AssertionResult r2 = r1;
5072 // The following line is added to prevent the compiler from optimizing
5073 // away the constructor call.
5076 AssertionResult r3 = r1;
5077 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
5078 EXPECT_STREQ("abc", r1.message());
5081 // Tests that AssertionSuccess and AssertionFailure construct
5082 // AssertionResult objects as expected.
5083 TEST(AssertionResultTest, ConstructionWorks) {
5084 AssertionResult r1 = AssertionSuccess();
5086 EXPECT_STREQ("", r1.message());
5088 AssertionResult r2 = AssertionSuccess() << "abc";
5090 EXPECT_STREQ("abc", r2.message());
5092 AssertionResult r3 = AssertionFailure();
5094 EXPECT_STREQ("", r3.message());
5096 AssertionResult r4 = AssertionFailure() << "def";
5098 EXPECT_STREQ("def", r4.message());
5100 AssertionResult r5 = AssertionFailure(Message() << "ghi");
5102 EXPECT_STREQ("ghi", r5.message());
5105 // Tests that the negation flips the predicate result but keeps the message.
5106 TEST(AssertionResultTest, NegationWorks) {
5107 AssertionResult r1 = AssertionSuccess() << "abc";
5109 EXPECT_STREQ("abc", (!r1).message());
5111 AssertionResult r2 = AssertionFailure() << "def";
5113 EXPECT_STREQ("def", (!r2).message());
5116 TEST(AssertionResultTest, StreamingWorks) {
5117 AssertionResult r = AssertionSuccess();
5118 r << "abc" << 'd' << 0 << true;
5119 EXPECT_STREQ("abcd0true", r.message());
5122 TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5123 AssertionResult r = AssertionSuccess();
5124 r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5125 EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5128 // The next test uses explicit conversion operators -- a C++11 feature.
5129 #if GTEST_LANG_CXX11
5131 TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5132 struct ExplicitlyConvertibleToBool {
5133 explicit operator bool() const { return value; }
5136 ExplicitlyConvertibleToBool v1 = {false};
5137 ExplicitlyConvertibleToBool v2 = {true};
5142 #endif // GTEST_LANG_CXX11
5144 struct ConvertibleToAssertionResult {
5145 operator AssertionResult() const { return AssertionResult(true); }
5148 TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5149 ConvertibleToAssertionResult obj;
5153 // Tests streaming a user type whose definition and operator << are
5154 // both in the global namespace.
5157 explicit Base(int an_x) : x_(an_x) {}
5158 int x() const { return x_; }
5162 std::ostream& operator<<(std::ostream& os,
5164 return os << val.x();
5166 std::ostream& operator<<(std::ostream& os,
5167 const Base* pointer) {
5168 return os << "(" << pointer->x() << ")";
5171 TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5175 msg << a << &a; // Uses ::operator<<.
5176 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5179 // Tests streaming a user type whose definition and operator<< are
5180 // both in an unnamed namespace.
5182 class MyTypeInUnnamedNameSpace : public Base {
5184 explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
5186 std::ostream& operator<<(std::ostream& os,
5187 const MyTypeInUnnamedNameSpace& val) {
5188 return os << val.x();
5190 std::ostream& operator<<(std::ostream& os,
5191 const MyTypeInUnnamedNameSpace* pointer) {
5192 return os << "(" << pointer->x() << ")";
5196 TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5198 MyTypeInUnnamedNameSpace a(1);
5200 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
5201 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5204 // Tests streaming a user type whose definition and operator<< are
5205 // both in a user namespace.
5206 namespace namespace1 {
5207 class MyTypeInNameSpace1 : public Base {
5209 explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
5211 std::ostream& operator<<(std::ostream& os,
5212 const MyTypeInNameSpace1& val) {
5213 return os << val.x();
5215 std::ostream& operator<<(std::ostream& os,
5216 const MyTypeInNameSpace1* pointer) {
5217 return os << "(" << pointer->x() << ")";
5219 } // namespace namespace1
5221 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5223 namespace1::MyTypeInNameSpace1 a(1);
5225 msg << a << &a; // Uses namespace1::operator<<.
5226 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5229 // Tests streaming a user type whose definition is in a user namespace
5230 // but whose operator<< is in the global namespace.
5231 namespace namespace2 {
5232 class MyTypeInNameSpace2 : public ::Base {
5234 explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
5236 } // namespace namespace2
5237 std::ostream& operator<<(std::ostream& os,
5238 const namespace2::MyTypeInNameSpace2& val) {
5239 return os << val.x();
5241 std::ostream& operator<<(std::ostream& os,
5242 const namespace2::MyTypeInNameSpace2* pointer) {
5243 return os << "(" << pointer->x() << ")";
5246 TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5248 namespace2::MyTypeInNameSpace2 a(1);
5250 msg << a << &a; // Uses ::operator<<.
5251 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5254 // Tests streaming NULL pointers to testing::Message.
5255 TEST(MessageTest, NullPointers) {
5257 char* const p1 = NULL;
5258 unsigned char* const p2 = NULL;
5264 msg << p1 << p2 << p3 << p4 << p5 << p6;
5265 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5266 msg.GetString().c_str());
5269 // Tests streaming wide strings to testing::Message.
5270 TEST(MessageTest, WideStrings) {
5271 // Streams a NULL of type const wchar_t*.
5272 const wchar_t* const_wstr = NULL;
5273 EXPECT_STREQ("(null)",
5274 (Message() << const_wstr).GetString().c_str());
5276 // Streams a NULL of type wchar_t*.
5277 wchar_t* wstr = NULL;
5278 EXPECT_STREQ("(null)",
5279 (Message() << wstr).GetString().c_str());
5281 // Streams a non-NULL of type const wchar_t*.
5282 const_wstr = L"abc\x8119";
5283 EXPECT_STREQ("abc\xe8\x84\x99",
5284 (Message() << const_wstr).GetString().c_str());
5286 // Streams a non-NULL of type wchar_t*.
5287 wstr = const_cast<wchar_t*>(const_wstr);
5288 EXPECT_STREQ("abc\xe8\x84\x99",
5289 (Message() << wstr).GetString().c_str());
5293 // This line tests that we can define tests in the testing namespace.
5296 // Tests the TestInfo class.
5298 class TestInfoTest : public Test {
5300 static const TestInfo* GetTestInfo(const char* test_name) {
5301 const TestCase* const test_case = GetUnitTestImpl()->
5302 GetTestCase("TestInfoTest", "", NULL, NULL);
5304 for (int i = 0; i < test_case->total_test_count(); ++i) {
5305 const TestInfo* const test_info = test_case->GetTestInfo(i);
5306 if (strcmp(test_name, test_info->name()) == 0)
5312 static const TestResult* GetTestResult(
5313 const TestInfo* test_info) {
5314 return test_info->result();
5318 // Tests TestInfo::test_case_name() and TestInfo::name().
5319 TEST_F(TestInfoTest, Names) {
5320 const TestInfo* const test_info = GetTestInfo("Names");
5322 ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
5323 ASSERT_STREQ("Names", test_info->name());
5326 // Tests TestInfo::result().
5327 TEST_F(TestInfoTest, result) {
5328 const TestInfo* const test_info = GetTestInfo("result");
5330 // Initially, there is no TestPartResult for this test.
5331 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5333 // After the previous assertion, there is still none.
5334 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5337 #define VERIFY_CODE_LOCATION \
5338 const int expected_line = __LINE__ - 1; \
5339 const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
5340 ASSERT_TRUE(test_info); \
5341 EXPECT_STREQ(__FILE__, test_info->file()); \
5342 EXPECT_EQ(expected_line, test_info->line())
5344 TEST(CodeLocationForTEST, Verify) {
5345 VERIFY_CODE_LOCATION;
5348 class CodeLocationForTESTF : public Test {
5351 TEST_F(CodeLocationForTESTF, Verify) {
5352 VERIFY_CODE_LOCATION;
5355 class CodeLocationForTESTP : public TestWithParam<int> {
5358 TEST_P(CodeLocationForTESTP, Verify) {
5359 VERIFY_CODE_LOCATION;
5362 INSTANTIATE_TEST_CASE_P(, CodeLocationForTESTP, Values(0));
5364 template <typename T>
5365 class CodeLocationForTYPEDTEST : public Test {
5368 TYPED_TEST_CASE(CodeLocationForTYPEDTEST, int);
5370 TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
5371 VERIFY_CODE_LOCATION;
5374 template <typename T>
5375 class CodeLocationForTYPEDTESTP : public Test {
5378 TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP);
5380 TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
5381 VERIFY_CODE_LOCATION;
5384 REGISTER_TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP, Verify);
5386 INSTANTIATE_TYPED_TEST_CASE_P(My, CodeLocationForTYPEDTESTP, int);
5388 #undef VERIFY_CODE_LOCATION
5390 // Tests setting up and tearing down a test case.
5392 class SetUpTestCaseTest : public Test {
5394 // This will be called once before the first test in this test case
5396 static void SetUpTestCase() {
5397 printf("Setting up the test case . . .\n");
5399 // Initializes some shared resource. In this simple example, we
5400 // just create a C string. More complex stuff can be done if
5402 shared_resource_ = "123";
5404 // Increments the number of test cases that have been set up.
5407 // SetUpTestCase() should be called only once.
5408 EXPECT_EQ(1, counter_);
5411 // This will be called once after the last test in this test case is
5413 static void TearDownTestCase() {
5414 printf("Tearing down the test case . . .\n");
5416 // Decrements the number of test cases that have been set up.
5419 // TearDownTestCase() should be called only once.
5420 EXPECT_EQ(0, counter_);
5422 // Cleans up the shared resource.
5423 shared_resource_ = NULL;
5426 // This will be called before each test in this test case.
5427 virtual void SetUp() {
5428 // SetUpTestCase() should be called only once, so counter_ should
5430 EXPECT_EQ(1, counter_);
5433 // Number of test cases that have been set up.
5434 static int counter_;
5436 // Some resource to be shared by all tests in this test case.
5437 static const char* shared_resource_;
5440 int SetUpTestCaseTest::counter_ = 0;
5441 const char* SetUpTestCaseTest::shared_resource_ = NULL;
5443 // A test that uses the shared resource.
5444 TEST_F(SetUpTestCaseTest, Test1) {
5445 EXPECT_STRNE(NULL, shared_resource_);
5448 // Another test that uses the shared resource.
5449 TEST_F(SetUpTestCaseTest, Test2) {
5450 EXPECT_STREQ("123", shared_resource_);
5453 // The InitGoogleTestTest test case tests testing::InitGoogleTest().
5455 // The Flags struct stores a copy of all Google Test flags.
5457 // Constructs a Flags struct where each flag has its default value.
5458 Flags() : also_run_disabled_tests(false),
5459 break_on_failure(false),
5460 catch_exceptions(false),
5461 death_test_use_fork(false),
5469 stack_trace_depth(kMaxStackTraceDepth),
5470 stream_result_to(""),
5471 throw_on_failure(false) {}
5475 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5477 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5479 flags.also_run_disabled_tests = also_run_disabled_tests;
5483 // Creates a Flags struct where the gtest_break_on_failure flag has
5485 static Flags BreakOnFailure(bool break_on_failure) {
5487 flags.break_on_failure = break_on_failure;
5491 // Creates a Flags struct where the gtest_catch_exceptions flag has
5493 static Flags CatchExceptions(bool catch_exceptions) {
5495 flags.catch_exceptions = catch_exceptions;
5499 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5501 static Flags DeathTestUseFork(bool death_test_use_fork) {
5503 flags.death_test_use_fork = death_test_use_fork;
5507 // Creates a Flags struct where the gtest_filter flag has the given
5509 static Flags Filter(const char* filter) {
5511 flags.filter = filter;
5515 // Creates a Flags struct where the gtest_list_tests flag has the
5517 static Flags ListTests(bool list_tests) {
5519 flags.list_tests = list_tests;
5523 // Creates a Flags struct where the gtest_output flag has the given
5525 static Flags Output(const char* output) {
5527 flags.output = output;
5531 // Creates a Flags struct where the gtest_print_time flag has the given
5533 static Flags PrintTime(bool print_time) {
5535 flags.print_time = print_time;
5539 // Creates a Flags struct where the gtest_random_seed flag has
5541 static Flags RandomSeed(Int32 random_seed) {
5543 flags.random_seed = random_seed;
5547 // Creates a Flags struct where the gtest_repeat flag has the given
5549 static Flags Repeat(Int32 repeat) {
5551 flags.repeat = repeat;
5555 // Creates a Flags struct where the gtest_shuffle flag has
5557 static Flags Shuffle(bool shuffle) {
5559 flags.shuffle = shuffle;
5563 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5565 static Flags StackTraceDepth(Int32 stack_trace_depth) {
5567 flags.stack_trace_depth = stack_trace_depth;
5571 // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5573 static Flags StreamResultTo(const char* stream_result_to) {
5575 flags.stream_result_to = stream_result_to;
5579 // Creates a Flags struct where the gtest_throw_on_failure flag has
5581 static Flags ThrowOnFailure(bool throw_on_failure) {
5583 flags.throw_on_failure = throw_on_failure;
5587 // These fields store the flag values.
5588 bool also_run_disabled_tests;
5589 bool break_on_failure;
5590 bool catch_exceptions;
5591 bool death_test_use_fork;
5599 Int32 stack_trace_depth;
5600 const char* stream_result_to;
5601 bool throw_on_failure;
5604 // Fixture for testing InitGoogleTest().
5605 class InitGoogleTestTest : public Test {
5607 // Clears the flags before each test.
5608 virtual void SetUp() {
5609 GTEST_FLAG(also_run_disabled_tests) = false;
5610 GTEST_FLAG(break_on_failure) = false;
5611 GTEST_FLAG(catch_exceptions) = false;
5612 GTEST_FLAG(death_test_use_fork) = false;
5613 GTEST_FLAG(filter) = "";
5614 GTEST_FLAG(list_tests) = false;
5615 GTEST_FLAG(output) = "";
5616 GTEST_FLAG(print_time) = true;
5617 GTEST_FLAG(random_seed) = 0;
5618 GTEST_FLAG(repeat) = 1;
5619 GTEST_FLAG(shuffle) = false;
5620 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
5621 GTEST_FLAG(stream_result_to) = "";
5622 GTEST_FLAG(throw_on_failure) = false;
5625 // Asserts that two narrow or wide string arrays are equal.
5626 template <typename CharType>
5627 static void AssertStringArrayEq(size_t size1, CharType** array1,
5628 size_t size2, CharType** array2) {
5629 ASSERT_EQ(size1, size2) << " Array sizes different.";
5631 for (size_t i = 0; i != size1; i++) {
5632 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5636 // Verifies that the flag values match the expected values.
5637 static void CheckFlags(const Flags& expected) {
5638 EXPECT_EQ(expected.also_run_disabled_tests,
5639 GTEST_FLAG(also_run_disabled_tests));
5640 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5641 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
5642 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
5643 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5644 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5645 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
5646 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
5647 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
5648 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
5649 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
5650 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
5651 EXPECT_STREQ(expected.stream_result_to,
5652 GTEST_FLAG(stream_result_to).c_str());
5653 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
5656 // Parses a command line (specified by argc1 and argv1), then
5657 // verifies that the flag values are expected and that the
5658 // recognized flags are removed from the command line.
5659 template <typename CharType>
5660 static void TestParsingFlags(int argc1, const CharType** argv1,
5661 int argc2, const CharType** argv2,
5662 const Flags& expected, bool should_print_help) {
5663 const bool saved_help_flag = ::testing::internal::g_help_flag;
5664 ::testing::internal::g_help_flag = false;
5666 #if GTEST_HAS_STREAM_REDIRECTION
5670 // Parses the command line.
5671 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5673 #if GTEST_HAS_STREAM_REDIRECTION
5674 const std::string captured_stdout = GetCapturedStdout();
5677 // Verifies the flag values.
5678 CheckFlags(expected);
5680 // Verifies that the recognized flags are removed from the command
5682 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5684 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5685 // help message for the flags it recognizes.
5686 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5688 #if GTEST_HAS_STREAM_REDIRECTION
5689 const char* const expected_help_fragment =
5690 "This program contains tests written using";
5691 if (should_print_help) {
5692 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5694 EXPECT_PRED_FORMAT2(IsNotSubstring,
5695 expected_help_fragment, captured_stdout);
5697 #endif // GTEST_HAS_STREAM_REDIRECTION
5699 ::testing::internal::g_help_flag = saved_help_flag;
5702 // This macro wraps TestParsingFlags s.t. the user doesn't need
5703 // to specify the array sizes.
5705 #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5706 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5707 sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5708 expected, should_print_help)
5711 // Tests parsing an empty command line.
5712 TEST_F(InitGoogleTestTest, Empty) {
5713 const char* argv[] = {
5717 const char* argv2[] = {
5721 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5724 // Tests parsing a command line that has no flag.
5725 TEST_F(InitGoogleTestTest, NoFlag) {
5726 const char* argv[] = {
5731 const char* argv2[] = {
5736 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5739 // Tests parsing a bad --gtest_filter flag.
5740 TEST_F(InitGoogleTestTest, FilterBad) {
5741 const char* argv[] = {
5747 const char* argv2[] = {
5753 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
5756 // Tests parsing an empty --gtest_filter flag.
5757 TEST_F(InitGoogleTestTest, FilterEmpty) {
5758 const char* argv[] = {
5764 const char* argv2[] = {
5769 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5772 // Tests parsing a non-empty --gtest_filter flag.
5773 TEST_F(InitGoogleTestTest, FilterNonEmpty) {
5774 const char* argv[] = {
5776 "--gtest_filter=abc",
5780 const char* argv2[] = {
5785 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5788 // Tests parsing --gtest_break_on_failure.
5789 TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
5790 const char* argv[] = {
5792 "--gtest_break_on_failure",
5796 const char* argv2[] = {
5801 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5804 // Tests parsing --gtest_break_on_failure=0.
5805 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
5806 const char* argv[] = {
5808 "--gtest_break_on_failure=0",
5812 const char* argv2[] = {
5817 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5820 // Tests parsing --gtest_break_on_failure=f.
5821 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
5822 const char* argv[] = {
5824 "--gtest_break_on_failure=f",
5828 const char* argv2[] = {
5833 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5836 // Tests parsing --gtest_break_on_failure=F.
5837 TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
5838 const char* argv[] = {
5840 "--gtest_break_on_failure=F",
5844 const char* argv2[] = {
5849 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5852 // Tests parsing a --gtest_break_on_failure flag that has a "true"
5854 TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
5855 const char* argv[] = {
5857 "--gtest_break_on_failure=1",
5861 const char* argv2[] = {
5866 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5869 // Tests parsing --gtest_catch_exceptions.
5870 TEST_F(InitGoogleTestTest, CatchExceptions) {
5871 const char* argv[] = {
5873 "--gtest_catch_exceptions",
5877 const char* argv2[] = {
5882 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5885 // Tests parsing --gtest_death_test_use_fork.
5886 TEST_F(InitGoogleTestTest, DeathTestUseFork) {
5887 const char* argv[] = {
5889 "--gtest_death_test_use_fork",
5893 const char* argv2[] = {
5898 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5901 // Tests having the same flag twice with different values. The
5902 // expected behavior is that the one coming last takes precedence.
5903 TEST_F(InitGoogleTestTest, DuplicatedFlags) {
5904 const char* argv[] = {
5911 const char* argv2[] = {
5916 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5919 // Tests having an unrecognized flag on the command line.
5920 TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
5921 const char* argv[] = {
5923 "--gtest_break_on_failure",
5924 "bar", // Unrecognized by Google Test.
5929 const char* argv2[] = {
5936 flags.break_on_failure = true;
5938 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5941 // Tests having a --gtest_list_tests flag
5942 TEST_F(InitGoogleTestTest, ListTestsFlag) {
5943 const char* argv[] = {
5945 "--gtest_list_tests",
5949 const char* argv2[] = {
5954 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5957 // Tests having a --gtest_list_tests flag with a "true" value
5958 TEST_F(InitGoogleTestTest, ListTestsTrue) {
5959 const char* argv[] = {
5961 "--gtest_list_tests=1",
5965 const char* argv2[] = {
5970 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5973 // Tests having a --gtest_list_tests flag with a "false" value
5974 TEST_F(InitGoogleTestTest, ListTestsFalse) {
5975 const char* argv[] = {
5977 "--gtest_list_tests=0",
5981 const char* argv2[] = {
5986 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5989 // Tests parsing --gtest_list_tests=f.
5990 TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
5991 const char* argv[] = {
5993 "--gtest_list_tests=f",
5997 const char* argv2[] = {
6002 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6005 // Tests parsing --gtest_list_tests=F.
6006 TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
6007 const char* argv[] = {
6009 "--gtest_list_tests=F",
6013 const char* argv2[] = {
6018 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6021 // Tests parsing --gtest_output (invalid).
6022 TEST_F(InitGoogleTestTest, OutputEmpty) {
6023 const char* argv[] = {
6029 const char* argv2[] = {
6035 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
6038 // Tests parsing --gtest_output=xml
6039 TEST_F(InitGoogleTestTest, OutputXml) {
6040 const char* argv[] = {
6042 "--gtest_output=xml",
6046 const char* argv2[] = {
6051 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
6054 // Tests parsing --gtest_output=xml:file
6055 TEST_F(InitGoogleTestTest, OutputXmlFile) {
6056 const char* argv[] = {
6058 "--gtest_output=xml:file",
6062 const char* argv2[] = {
6067 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
6070 // Tests parsing --gtest_output=xml:directory/path/
6071 TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
6072 const char* argv[] = {
6074 "--gtest_output=xml:directory/path/",
6078 const char* argv2[] = {
6083 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6084 Flags::Output("xml:directory/path/"), false);
6087 // Tests having a --gtest_print_time flag
6088 TEST_F(InitGoogleTestTest, PrintTimeFlag) {
6089 const char* argv[] = {
6091 "--gtest_print_time",
6095 const char* argv2[] = {
6100 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6103 // Tests having a --gtest_print_time flag with a "true" value
6104 TEST_F(InitGoogleTestTest, PrintTimeTrue) {
6105 const char* argv[] = {
6107 "--gtest_print_time=1",
6111 const char* argv2[] = {
6116 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6119 // Tests having a --gtest_print_time flag with a "false" value
6120 TEST_F(InitGoogleTestTest, PrintTimeFalse) {
6121 const char* argv[] = {
6123 "--gtest_print_time=0",
6127 const char* argv2[] = {
6132 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6135 // Tests parsing --gtest_print_time=f.
6136 TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
6137 const char* argv[] = {
6139 "--gtest_print_time=f",
6143 const char* argv2[] = {
6148 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6151 // Tests parsing --gtest_print_time=F.
6152 TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
6153 const char* argv[] = {
6155 "--gtest_print_time=F",
6159 const char* argv2[] = {
6164 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6167 // Tests parsing --gtest_random_seed=number
6168 TEST_F(InitGoogleTestTest, RandomSeed) {
6169 const char* argv[] = {
6171 "--gtest_random_seed=1000",
6175 const char* argv2[] = {
6180 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6183 // Tests parsing --gtest_repeat=number
6184 TEST_F(InitGoogleTestTest, Repeat) {
6185 const char* argv[] = {
6187 "--gtest_repeat=1000",
6191 const char* argv2[] = {
6196 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
6199 // Tests having a --gtest_also_run_disabled_tests flag
6200 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
6201 const char* argv[] = {
6203 "--gtest_also_run_disabled_tests",
6207 const char* argv2[] = {
6212 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6213 Flags::AlsoRunDisabledTests(true), false);
6216 // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6217 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
6218 const char* argv[] = {
6220 "--gtest_also_run_disabled_tests=1",
6224 const char* argv2[] = {
6229 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6230 Flags::AlsoRunDisabledTests(true), false);
6233 // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6234 TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
6235 const char* argv[] = {
6237 "--gtest_also_run_disabled_tests=0",
6241 const char* argv2[] = {
6246 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6247 Flags::AlsoRunDisabledTests(false), false);
6250 // Tests parsing --gtest_shuffle.
6251 TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
6252 const char* argv[] = {
6258 const char* argv2[] = {
6263 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6266 // Tests parsing --gtest_shuffle=0.
6267 TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
6268 const char* argv[] = {
6270 "--gtest_shuffle=0",
6274 const char* argv2[] = {
6279 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6282 // Tests parsing a --gtest_shuffle flag that has a "true"
6284 TEST_F(InitGoogleTestTest, ShuffleTrue) {
6285 const char* argv[] = {
6287 "--gtest_shuffle=1",
6291 const char* argv2[] = {
6296 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6299 // Tests parsing --gtest_stack_trace_depth=number.
6300 TEST_F(InitGoogleTestTest, StackTraceDepth) {
6301 const char* argv[] = {
6303 "--gtest_stack_trace_depth=5",
6307 const char* argv2[] = {
6312 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6315 TEST_F(InitGoogleTestTest, StreamResultTo) {
6316 const char* argv[] = {
6318 "--gtest_stream_result_to=localhost:1234",
6322 const char* argv2[] = {
6327 GTEST_TEST_PARSING_FLAGS_(
6328 argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
6331 // Tests parsing --gtest_throw_on_failure.
6332 TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
6333 const char* argv[] = {
6335 "--gtest_throw_on_failure",
6339 const char* argv2[] = {
6344 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6347 // Tests parsing --gtest_throw_on_failure=0.
6348 TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
6349 const char* argv[] = {
6351 "--gtest_throw_on_failure=0",
6355 const char* argv2[] = {
6360 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
6363 // Tests parsing a --gtest_throw_on_failure flag that has a "true"
6365 TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
6366 const char* argv[] = {
6368 "--gtest_throw_on_failure=1",
6372 const char* argv2[] = {
6377 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6380 #if GTEST_OS_WINDOWS
6381 // Tests parsing wide strings.
6382 TEST_F(InitGoogleTestTest, WideStrings) {
6383 const wchar_t* argv[] = {
6385 L"--gtest_filter=Foo*",
6386 L"--gtest_list_tests=1",
6387 L"--gtest_break_on_failure",
6388 L"--non_gtest_flag",
6392 const wchar_t* argv2[] = {
6394 L"--non_gtest_flag",
6398 Flags expected_flags;
6399 expected_flags.break_on_failure = true;
6400 expected_flags.filter = "Foo*";
6401 expected_flags.list_tests = true;
6403 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6405 # endif // GTEST_OS_WINDOWS
6407 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6408 class FlagfileTest : public InitGoogleTestTest {
6410 virtual void SetUp() {
6411 InitGoogleTestTest::SetUp();
6413 testdata_path_.Set(internal::FilePath(
6414 internal::TempDir() + internal::GetCurrentExecutableName().string() +
6416 testing::internal::posix::RmDir(testdata_path_.c_str());
6417 EXPECT_TRUE(testdata_path_.CreateFolder());
6420 virtual void TearDown() {
6421 testing::internal::posix::RmDir(testdata_path_.c_str());
6422 InitGoogleTestTest::TearDown();
6425 internal::FilePath CreateFlagfile(const char* contents) {
6426 internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
6427 testdata_path_, internal::FilePath("unique"), "txt"));
6428 FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
6429 fprintf(f, "%s", contents);
6435 internal::FilePath testdata_path_;
6438 // Tests an empty flagfile.
6439 TEST_F(FlagfileTest, Empty) {
6440 internal::FilePath flagfile_path(CreateFlagfile(""));
6441 std::string flagfile_flag =
6442 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6444 const char* argv[] = {
6446 flagfile_flag.c_str(),
6450 const char* argv2[] = {
6455 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
6458 // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
6459 TEST_F(FlagfileTest, FilterNonEmpty) {
6460 internal::FilePath flagfile_path(CreateFlagfile(
6461 "--" GTEST_FLAG_PREFIX_ "filter=abc"));
6462 std::string flagfile_flag =
6463 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6465 const char* argv[] = {
6467 flagfile_flag.c_str(),
6471 const char* argv2[] = {
6476 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
6479 // Tests passing several flags via --gtest_flagfile.
6480 TEST_F(FlagfileTest, SeveralFlags) {
6481 internal::FilePath flagfile_path(CreateFlagfile(
6482 "--" GTEST_FLAG_PREFIX_ "filter=abc\n"
6483 "--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
6484 "--" GTEST_FLAG_PREFIX_ "list_tests"));
6485 std::string flagfile_flag =
6486 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6488 const char* argv[] = {
6490 flagfile_flag.c_str(),
6494 const char* argv2[] = {
6499 Flags expected_flags;
6500 expected_flags.break_on_failure = true;
6501 expected_flags.filter = "abc";
6502 expected_flags.list_tests = true;
6504 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6506 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6508 // Tests current_test_info() in UnitTest.
6509 class CurrentTestInfoTest : public Test {
6511 // Tests that current_test_info() returns NULL before the first test in
6512 // the test case is run.
6513 static void SetUpTestCase() {
6514 // There should be no tests running at this point.
6515 const TestInfo* test_info =
6516 UnitTest::GetInstance()->current_test_info();
6517 EXPECT_TRUE(test_info == NULL)
6518 << "There should be no tests running at this point.";
6521 // Tests that current_test_info() returns NULL after the last test in
6522 // the test case has run.
6523 static void TearDownTestCase() {
6524 const TestInfo* test_info =
6525 UnitTest::GetInstance()->current_test_info();
6526 EXPECT_TRUE(test_info == NULL)
6527 << "There should be no tests running at this point.";
6531 // Tests that current_test_info() returns TestInfo for currently running
6532 // test by checking the expected test name against the actual one.
6533 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
6534 const TestInfo* test_info =
6535 UnitTest::GetInstance()->current_test_info();
6536 ASSERT_TRUE(NULL != test_info)
6537 << "There is a test running so we should have a valid TestInfo.";
6538 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6539 << "Expected the name of the currently running test case.";
6540 EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
6541 << "Expected the name of the currently running test.";
6544 // Tests that current_test_info() returns TestInfo for currently running
6545 // test by checking the expected test name against the actual one. We
6546 // use this test to see that the TestInfo object actually changed from
6547 // the previous invocation.
6548 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
6549 const TestInfo* test_info =
6550 UnitTest::GetInstance()->current_test_info();
6551 ASSERT_TRUE(NULL != test_info)
6552 << "There is a test running so we should have a valid TestInfo.";
6553 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
6554 << "Expected the name of the currently running test case.";
6555 EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
6556 << "Expected the name of the currently running test.";
6559 } // namespace testing
6561 // These two lines test that we can define tests in a namespace that
6562 // has the name "testing" and is nested in another namespace.
6563 namespace my_namespace {
6566 // Makes sure that TEST knows to use ::testing::Test instead of
6567 // ::my_namespace::testing::Test.
6570 // Makes sure that an assertion knows to use ::testing::Message instead of
6571 // ::my_namespace::testing::Message.
6574 // Makes sure that an assertion knows to use
6575 // ::testing::AssertionResult instead of
6576 // ::my_namespace::testing::AssertionResult.
6577 class AssertionResult {};
6579 // Tests that an assertion that should succeed works as expected.
6580 TEST(NestedTestingNamespaceTest, Success) {
6581 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6584 // Tests that an assertion that should fail works as expected.
6585 TEST(NestedTestingNamespaceTest, Failure) {
6586 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6587 "This failure is expected.");
6590 } // namespace testing
6591 } // namespace my_namespace
6593 // Tests that one can call superclass SetUp and TearDown methods--
6594 // that is, that they are not private.
6595 // No tests are based on this fixture; the test "passes" if it compiles
6597 class ProtectedFixtureMethodsTest : public Test {
6599 virtual void SetUp() {
6602 virtual void TearDown() {
6607 // StreamingAssertionsTest tests the streaming versions of a representative
6608 // sample of assertions.
6609 TEST(StreamingAssertionsTest, Unconditional) {
6610 SUCCEED() << "expected success";
6611 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6612 "expected failure");
6613 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6614 "expected failure");
6618 // Silences warnings: "Condition is always true", "Unreachable code"
6619 # pragma option push -w-ccc -w-rch
6622 TEST(StreamingAssertionsTest, Truth) {
6623 EXPECT_TRUE(true) << "unexpected failure";
6624 ASSERT_TRUE(true) << "unexpected failure";
6625 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6626 "expected failure");
6627 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6628 "expected failure");
6631 TEST(StreamingAssertionsTest, Truth2) {
6632 EXPECT_FALSE(false) << "unexpected failure";
6633 ASSERT_FALSE(false) << "unexpected failure";
6634 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6635 "expected failure");
6636 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6637 "expected failure");
6641 // Restores warnings after previous "#pragma option push" supressed them
6645 TEST(StreamingAssertionsTest, IntegerEquals) {
6646 EXPECT_EQ(1, 1) << "unexpected failure";
6647 ASSERT_EQ(1, 1) << "unexpected failure";
6648 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6649 "expected failure");
6650 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6651 "expected failure");
6654 TEST(StreamingAssertionsTest, IntegerLessThan) {
6655 EXPECT_LT(1, 2) << "unexpected failure";
6656 ASSERT_LT(1, 2) << "unexpected failure";
6657 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6658 "expected failure");
6659 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6660 "expected failure");
6663 TEST(StreamingAssertionsTest, StringsEqual) {
6664 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6665 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6666 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6667 "expected failure");
6668 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6669 "expected failure");
6672 TEST(StreamingAssertionsTest, StringsNotEqual) {
6673 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6674 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6675 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6676 "expected failure");
6677 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6678 "expected failure");
6681 TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6682 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6683 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6684 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6685 "expected failure");
6686 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6687 "expected failure");
6690 TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6691 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6692 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6693 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6694 "expected failure");
6695 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6696 "expected failure");
6699 TEST(StreamingAssertionsTest, FloatingPointEquals) {
6700 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6701 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6702 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6703 "expected failure");
6704 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6705 "expected failure");
6708 #if GTEST_HAS_EXCEPTIONS
6710 TEST(StreamingAssertionsTest, Throw) {
6711 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6712 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6713 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6714 "expected failure", "expected failure");
6715 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6716 "expected failure", "expected failure");
6719 TEST(StreamingAssertionsTest, NoThrow) {
6720 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6721 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6722 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6723 "expected failure", "expected failure");
6724 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6725 "expected failure", "expected failure");
6728 TEST(StreamingAssertionsTest, AnyThrow) {
6729 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6730 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6731 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
6732 "expected failure", "expected failure");
6733 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
6734 "expected failure", "expected failure");
6737 #endif // GTEST_HAS_EXCEPTIONS
6739 // Tests that Google Test correctly decides whether to use colors in the output.
6741 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6742 GTEST_FLAG(color) = "yes";
6744 SetEnv("TERM", "xterm"); // TERM supports colors.
6745 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6746 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6748 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6749 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6750 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6753 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6754 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6756 GTEST_FLAG(color) = "True";
6757 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6759 GTEST_FLAG(color) = "t";
6760 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6762 GTEST_FLAG(color) = "1";
6763 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6766 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6767 GTEST_FLAG(color) = "no";
6769 SetEnv("TERM", "xterm"); // TERM supports colors.
6770 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6771 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6773 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6774 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6775 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6778 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6779 SetEnv("TERM", "xterm"); // TERM supports colors.
6781 GTEST_FLAG(color) = "F";
6782 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6784 GTEST_FLAG(color) = "0";
6785 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6787 GTEST_FLAG(color) = "unknown";
6788 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6791 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6792 GTEST_FLAG(color) = "auto";
6794 SetEnv("TERM", "xterm"); // TERM supports colors.
6795 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6796 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6799 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6800 GTEST_FLAG(color) = "auto";
6802 #if GTEST_OS_WINDOWS
6803 // On Windows, we ignore the TERM variable as it's usually not set.
6805 SetEnv("TERM", "dumb");
6806 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6809 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6811 SetEnv("TERM", "xterm");
6812 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6814 // On non-Windows platforms, we rely on TERM to determine if the
6815 // terminal supports colors.
6817 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6818 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6820 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6821 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6823 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6824 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6826 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6827 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6829 SetEnv("TERM", "xterm"); // TERM supports colors.
6830 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6832 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6833 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6835 SetEnv("TERM", "xterm-256color"); // TERM supports colors.
6836 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6838 SetEnv("TERM", "screen"); // TERM supports colors.
6839 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6841 SetEnv("TERM", "screen-256color"); // TERM supports colors.
6842 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6844 SetEnv("TERM", "tmux"); // TERM supports colors.
6845 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6847 SetEnv("TERM", "tmux-256color"); // TERM supports colors.
6848 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6850 SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
6851 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6853 SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
6854 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6856 SetEnv("TERM", "linux"); // TERM supports colors.
6857 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6859 SetEnv("TERM", "cygwin"); // TERM supports colors.
6860 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6861 #endif // GTEST_OS_WINDOWS
6864 // Verifies that StaticAssertTypeEq works in a namespace scope.
6866 static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6867 static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6868 StaticAssertTypeEq<const int, const int>();
6870 // Verifies that StaticAssertTypeEq works in a class.
6872 template <typename T>
6873 class StaticAssertTypeEqTestHelper {
6875 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6878 TEST(StaticAssertTypeEqTest, WorksInClass) {
6879 StaticAssertTypeEqTestHelper<bool>();
6882 // Verifies that StaticAssertTypeEq works inside a function.
6884 typedef int IntAlias;
6886 TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6887 StaticAssertTypeEq<int, IntAlias>();
6888 StaticAssertTypeEq<int*, IntAlias*>();
6891 TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
6892 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
6894 // We don't have a stack walker in Google Test yet.
6895 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
6896 EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
6899 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6900 EXPECT_FALSE(HasNonfatalFailure());
6903 static void FailFatally() { FAIL(); }
6905 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6907 const bool has_nonfatal_failure = HasNonfatalFailure();
6908 ClearCurrentTestPartResults();
6909 EXPECT_FALSE(has_nonfatal_failure);
6912 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6914 const bool has_nonfatal_failure = HasNonfatalFailure();
6915 ClearCurrentTestPartResults();
6916 EXPECT_TRUE(has_nonfatal_failure);
6919 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6922 const bool has_nonfatal_failure = HasNonfatalFailure();
6923 ClearCurrentTestPartResults();
6924 EXPECT_TRUE(has_nonfatal_failure);
6927 // A wrapper for calling HasNonfatalFailure outside of a test body.
6928 static bool HasNonfatalFailureHelper() {
6929 return testing::Test::HasNonfatalFailure();
6932 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6933 EXPECT_FALSE(HasNonfatalFailureHelper());
6936 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6938 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6939 ClearCurrentTestPartResults();
6940 EXPECT_TRUE(has_nonfatal_failure);
6943 TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6944 EXPECT_FALSE(HasFailure());
6947 TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6949 const bool has_failure = HasFailure();
6950 ClearCurrentTestPartResults();
6951 EXPECT_TRUE(has_failure);
6954 TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6956 const bool has_failure = HasFailure();
6957 ClearCurrentTestPartResults();
6958 EXPECT_TRUE(has_failure);
6961 TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6964 const bool has_failure = HasFailure();
6965 ClearCurrentTestPartResults();
6966 EXPECT_TRUE(has_failure);
6969 // A wrapper for calling HasFailure outside of a test body.
6970 static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6972 TEST(HasFailureTest, WorksOutsideOfTestBody) {
6973 EXPECT_FALSE(HasFailureHelper());
6976 TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6978 const bool has_failure = HasFailureHelper();
6979 ClearCurrentTestPartResults();
6980 EXPECT_TRUE(has_failure);
6983 class TestListener : public EmptyTestEventListener {
6985 TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
6986 TestListener(int* on_start_counter, bool* is_destroyed)
6987 : on_start_counter_(on_start_counter),
6988 is_destroyed_(is_destroyed) {}
6990 virtual ~TestListener() {
6992 *is_destroyed_ = true;
6996 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
6997 if (on_start_counter_ != NULL)
6998 (*on_start_counter_)++;
7002 int* on_start_counter_;
7003 bool* is_destroyed_;
7006 // Tests the constructor.
7007 TEST(TestEventListenersTest, ConstructionWorks) {
7008 TestEventListeners listeners;
7010 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
7011 EXPECT_TRUE(listeners.default_result_printer() == NULL);
7012 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7015 // Tests that the TestEventListeners destructor deletes all the listeners it
7017 TEST(TestEventListenersTest, DestructionWorks) {
7018 bool default_result_printer_is_destroyed = false;
7019 bool default_xml_printer_is_destroyed = false;
7020 bool extra_listener_is_destroyed = false;
7021 TestListener* default_result_printer = new TestListener(
7022 NULL, &default_result_printer_is_destroyed);
7023 TestListener* default_xml_printer = new TestListener(
7024 NULL, &default_xml_printer_is_destroyed);
7025 TestListener* extra_listener = new TestListener(
7026 NULL, &extra_listener_is_destroyed);
7029 TestEventListeners listeners;
7030 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
7031 default_result_printer);
7032 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
7033 default_xml_printer);
7034 listeners.Append(extra_listener);
7036 EXPECT_TRUE(default_result_printer_is_destroyed);
7037 EXPECT_TRUE(default_xml_printer_is_destroyed);
7038 EXPECT_TRUE(extra_listener_is_destroyed);
7041 // Tests that a listener Append'ed to a TestEventListeners list starts
7042 // receiving events.
7043 TEST(TestEventListenersTest, Append) {
7044 int on_start_counter = 0;
7045 bool is_destroyed = false;
7046 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7048 TestEventListeners listeners;
7049 listeners.Append(listener);
7050 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7051 *UnitTest::GetInstance());
7052 EXPECT_EQ(1, on_start_counter);
7054 EXPECT_TRUE(is_destroyed);
7057 // Tests that listeners receive events in the order they were appended to
7058 // the list, except for *End requests, which must be received in the reverse
7060 class SequenceTestingListener : public EmptyTestEventListener {
7062 SequenceTestingListener(std::vector<std::string>* vector, const char* id)
7063 : vector_(vector), id_(id) {}
7066 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
7067 vector_->push_back(GetEventDescription("OnTestProgramStart"));
7070 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
7071 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
7074 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
7075 int /*iteration*/) {
7076 vector_->push_back(GetEventDescription("OnTestIterationStart"));
7079 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
7080 int /*iteration*/) {
7081 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
7085 std::string GetEventDescription(const char* method) {
7087 message << id_ << "." << method;
7088 return message.GetString();
7091 std::vector<std::string>* vector_;
7092 const char* const id_;
7094 GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
7097 TEST(EventListenerTest, AppendKeepsOrder) {
7098 std::vector<std::string> vec;
7099 TestEventListeners listeners;
7100 listeners.Append(new SequenceTestingListener(&vec, "1st"));
7101 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
7102 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
7104 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7105 *UnitTest::GetInstance());
7106 ASSERT_EQ(3U, vec.size());
7107 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
7108 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
7109 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
7112 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
7113 *UnitTest::GetInstance());
7114 ASSERT_EQ(3U, vec.size());
7115 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
7116 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
7117 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
7120 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
7121 *UnitTest::GetInstance(), 0);
7122 ASSERT_EQ(3U, vec.size());
7123 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
7124 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
7125 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
7128 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
7129 *UnitTest::GetInstance(), 0);
7130 ASSERT_EQ(3U, vec.size());
7131 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
7132 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
7133 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
7136 // Tests that a listener removed from a TestEventListeners list stops receiving
7137 // events and is not deleted when the list is destroyed.
7138 TEST(TestEventListenersTest, Release) {
7139 int on_start_counter = 0;
7140 bool is_destroyed = false;
7141 // Although Append passes the ownership of this object to the list,
7142 // the following calls release it, and we need to delete it before the
7144 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7146 TestEventListeners listeners;
7147 listeners.Append(listener);
7148 EXPECT_EQ(listener, listeners.Release(listener));
7149 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7150 *UnitTest::GetInstance());
7151 EXPECT_TRUE(listeners.Release(listener) == NULL);
7153 EXPECT_EQ(0, on_start_counter);
7154 EXPECT_FALSE(is_destroyed);
7158 // Tests that no events are forwarded when event forwarding is disabled.
7159 TEST(EventListenerTest, SuppressEventForwarding) {
7160 int on_start_counter = 0;
7161 TestListener* listener = new TestListener(&on_start_counter, NULL);
7163 TestEventListeners listeners;
7164 listeners.Append(listener);
7165 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7166 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
7167 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7168 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7169 *UnitTest::GetInstance());
7170 EXPECT_EQ(0, on_start_counter);
7173 // Tests that events generated by Google Test are not forwarded in
7174 // death test subprocesses.
7175 TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
7176 EXPECT_DEATH_IF_SUPPORTED({
7177 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
7178 *GetUnitTestImpl()->listeners())) << "expected failure";},
7179 "expected failure");
7182 // Tests that a listener installed via SetDefaultResultPrinter() starts
7183 // receiving events and is returned via default_result_printer() and that
7184 // the previous default_result_printer is removed from the list and deleted.
7185 TEST(EventListenerTest, default_result_printer) {
7186 int on_start_counter = 0;
7187 bool is_destroyed = false;
7188 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7190 TestEventListeners listeners;
7191 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7193 EXPECT_EQ(listener, listeners.default_result_printer());
7195 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7196 *UnitTest::GetInstance());
7198 EXPECT_EQ(1, on_start_counter);
7200 // Replacing default_result_printer with something else should remove it
7201 // from the list and destroy it.
7202 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
7204 EXPECT_TRUE(listeners.default_result_printer() == NULL);
7205 EXPECT_TRUE(is_destroyed);
7207 // After broadcasting an event the counter is still the same, indicating
7208 // the listener is not in the list anymore.
7209 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7210 *UnitTest::GetInstance());
7211 EXPECT_EQ(1, on_start_counter);
7214 // Tests that the default_result_printer listener stops receiving events
7215 // when removed via Release and that is not owned by the list anymore.
7216 TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
7217 int on_start_counter = 0;
7218 bool is_destroyed = false;
7219 // Although Append passes the ownership of this object to the list,
7220 // the following calls release it, and we need to delete it before the
7222 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7224 TestEventListeners listeners;
7225 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7227 EXPECT_EQ(listener, listeners.Release(listener));
7228 EXPECT_TRUE(listeners.default_result_printer() == NULL);
7229 EXPECT_FALSE(is_destroyed);
7231 // Broadcasting events now should not affect default_result_printer.
7232 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7233 *UnitTest::GetInstance());
7234 EXPECT_EQ(0, on_start_counter);
7236 // Destroying the list should not affect the listener now, too.
7237 EXPECT_FALSE(is_destroyed);
7241 // Tests that a listener installed via SetDefaultXmlGenerator() starts
7242 // receiving events and is returned via default_xml_generator() and that
7243 // the previous default_xml_generator is removed from the list and deleted.
7244 TEST(EventListenerTest, default_xml_generator) {
7245 int on_start_counter = 0;
7246 bool is_destroyed = false;
7247 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7249 TestEventListeners listeners;
7250 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7252 EXPECT_EQ(listener, listeners.default_xml_generator());
7254 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7255 *UnitTest::GetInstance());
7257 EXPECT_EQ(1, on_start_counter);
7259 // Replacing default_xml_generator with something else should remove it
7260 // from the list and destroy it.
7261 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
7263 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7264 EXPECT_TRUE(is_destroyed);
7266 // After broadcasting an event the counter is still the same, indicating
7267 // the listener is not in the list anymore.
7268 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7269 *UnitTest::GetInstance());
7270 EXPECT_EQ(1, on_start_counter);
7273 // Tests that the default_xml_generator listener stops receiving events
7274 // when removed via Release and that is not owned by the list anymore.
7275 TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
7276 int on_start_counter = 0;
7277 bool is_destroyed = false;
7278 // Although Append passes the ownership of this object to the list,
7279 // the following calls release it, and we need to delete it before the
7281 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7283 TestEventListeners listeners;
7284 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7286 EXPECT_EQ(listener, listeners.Release(listener));
7287 EXPECT_TRUE(listeners.default_xml_generator() == NULL);
7288 EXPECT_FALSE(is_destroyed);
7290 // Broadcasting events now should not affect default_xml_generator.
7291 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7292 *UnitTest::GetInstance());
7293 EXPECT_EQ(0, on_start_counter);
7295 // Destroying the list should not affect the listener now, too.
7296 EXPECT_FALSE(is_destroyed);
7300 // Sanity tests to ensure that the alternative, verbose spellings of
7301 // some of the macros work. We don't test them thoroughly as that
7302 // would be quite involved. Since their implementations are
7303 // straightforward, and they are rarely used, we'll just rely on the
7304 // users to tell us when they are broken.
7305 GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
7306 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
7308 // GTEST_FAIL is the same as FAIL.
7309 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
7310 "An expected failure");
7312 // GTEST_ASSERT_XY is the same as ASSERT_XY.
7314 GTEST_ASSERT_EQ(0, 0);
7315 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
7316 "An expected failure");
7317 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
7318 "An expected failure");
7320 GTEST_ASSERT_NE(0, 1);
7321 GTEST_ASSERT_NE(1, 0);
7322 EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
7323 "An expected failure");
7325 GTEST_ASSERT_LE(0, 0);
7326 GTEST_ASSERT_LE(0, 1);
7327 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
7328 "An expected failure");
7330 GTEST_ASSERT_LT(0, 1);
7331 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
7332 "An expected failure");
7333 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
7334 "An expected failure");
7336 GTEST_ASSERT_GE(0, 0);
7337 GTEST_ASSERT_GE(1, 0);
7338 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
7339 "An expected failure");
7341 GTEST_ASSERT_GT(1, 0);
7342 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
7343 "An expected failure");
7344 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
7345 "An expected failure");
7348 // Tests for internal utilities necessary for implementation of the universal
7350 // TODO(vladl@google.com): Find a better home for them.
7352 class ConversionHelperBase {};
7353 class ConversionHelperDerived : public ConversionHelperBase {};
7355 // Tests that IsAProtocolMessage<T>::value is a compile-time constant.
7356 TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
7357 GTEST_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value,
7359 GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
7362 // Tests that IsAProtocolMessage<T>::value is true when T is
7363 // proto2::Message or a sub-class of it.
7364 TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
7365 EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
7366 EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value);
7369 // Tests that IsAProtocolMessage<T>::value is false when T is neither
7370 // ProtocolMessage nor a sub-class of it.
7371 TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7372 EXPECT_FALSE(IsAProtocolMessage<int>::value);
7373 EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
7376 // Tests that CompileAssertTypesEqual compiles when the type arguments are
7378 TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) {
7379 CompileAssertTypesEqual<void, void>();
7380 CompileAssertTypesEqual<int*, int*>();
7383 // Tests that RemoveReference does not affect non-reference types.
7384 TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) {
7385 CompileAssertTypesEqual<int, RemoveReference<int>::type>();
7386 CompileAssertTypesEqual<const char, RemoveReference<const char>::type>();
7389 // Tests that RemoveReference removes reference from reference types.
7390 TEST(RemoveReferenceTest, RemovesReference) {
7391 CompileAssertTypesEqual<int, RemoveReference<int&>::type>();
7392 CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>();
7395 // Tests GTEST_REMOVE_REFERENCE_.
7397 template <typename T1, typename T2>
7398 void TestGTestRemoveReference() {
7399 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>();
7402 TEST(RemoveReferenceTest, MacroVersion) {
7403 TestGTestRemoveReference<int, int>();
7404 TestGTestRemoveReference<const char, const char&>();
7408 // Tests that RemoveConst does not affect non-const types.
7409 TEST(RemoveConstTest, DoesNotAffectNonConstType) {
7410 CompileAssertTypesEqual<int, RemoveConst<int>::type>();
7411 CompileAssertTypesEqual<char&, RemoveConst<char&>::type>();
7414 // Tests that RemoveConst removes const from const types.
7415 TEST(RemoveConstTest, RemovesConst) {
7416 CompileAssertTypesEqual<int, RemoveConst<const int>::type>();
7417 CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>();
7418 CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>();
7421 // Tests GTEST_REMOVE_CONST_.
7423 template <typename T1, typename T2>
7424 void TestGTestRemoveConst() {
7425 CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>();
7428 TEST(RemoveConstTest, MacroVersion) {
7429 TestGTestRemoveConst<int, int>();
7430 TestGTestRemoveConst<double&, double&>();
7431 TestGTestRemoveConst<char, const char>();
7434 // Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7436 template <typename T1, typename T2>
7437 void TestGTestRemoveReferenceAndConst() {
7438 CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>();
7441 TEST(RemoveReferenceToConstTest, Works) {
7442 TestGTestRemoveReferenceAndConst<int, int>();
7443 TestGTestRemoveReferenceAndConst<double, double&>();
7444 TestGTestRemoveReferenceAndConst<char, const char>();
7445 TestGTestRemoveReferenceAndConst<char, const char&>();
7446 TestGTestRemoveReferenceAndConst<const char*, const char*>();
7449 // Tests that AddReference does not affect reference types.
7450 TEST(AddReferenceTest, DoesNotAffectReferenceType) {
7451 CompileAssertTypesEqual<int&, AddReference<int&>::type>();
7452 CompileAssertTypesEqual<const char&, AddReference<const char&>::type>();
7455 // Tests that AddReference adds reference to non-reference types.
7456 TEST(AddReferenceTest, AddsReference) {
7457 CompileAssertTypesEqual<int&, AddReference<int>::type>();
7458 CompileAssertTypesEqual<const char&, AddReference<const char>::type>();
7461 // Tests GTEST_ADD_REFERENCE_.
7463 template <typename T1, typename T2>
7464 void TestGTestAddReference() {
7465 CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>();
7468 TEST(AddReferenceTest, MacroVersion) {
7469 TestGTestAddReference<int&, int>();
7470 TestGTestAddReference<const char&, const char&>();
7473 // Tests GTEST_REFERENCE_TO_CONST_.
7475 template <typename T1, typename T2>
7476 void TestGTestReferenceToConst() {
7477 CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>();
7480 TEST(GTestReferenceToConstTest, Works) {
7481 TestGTestReferenceToConst<const char&, char>();
7482 TestGTestReferenceToConst<const int&, const int>();
7483 TestGTestReferenceToConst<const double&, double>();
7484 TestGTestReferenceToConst<const std::string&, const std::string&>();
7487 // Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant.
7488 TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) {
7489 GTEST_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true);
7490 GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value),
7494 // Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can
7495 // be implicitly converted to T2.
7496 TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) {
7497 EXPECT_TRUE((ImplicitlyConvertible<int, double>::value));
7498 EXPECT_TRUE((ImplicitlyConvertible<double, int>::value));
7499 EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value));
7500 EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value));
7501 EXPECT_TRUE((ImplicitlyConvertible<ConversionHelperDerived&,
7502 const ConversionHelperBase&>::value));
7503 EXPECT_TRUE((ImplicitlyConvertible<const ConversionHelperBase,
7504 ConversionHelperBase>::value));
7507 // Tests that ImplicitlyConvertible<T1, T2>::value is false when T1
7508 // cannot be implicitly converted to T2.
7509 TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) {
7510 EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value));
7511 EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value));
7512 EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value));
7513 EXPECT_FALSE((ImplicitlyConvertible<ConversionHelperBase&,
7514 ConversionHelperDerived&>::value));
7517 // Tests IsContainerTest.
7519 class NonContainer {};
7521 TEST(IsContainerTestTest, WorksForNonContainer) {
7522 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7523 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7524 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7527 TEST(IsContainerTestTest, WorksForContainer) {
7528 EXPECT_EQ(sizeof(IsContainer),
7529 sizeof(IsContainerTest<std::vector<bool> >(0)));
7530 EXPECT_EQ(sizeof(IsContainer),
7531 sizeof(IsContainerTest<std::map<int, double> >(0)));
7536 TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7537 EXPECT_TRUE(ArrayEq(5, 5L));
7538 EXPECT_FALSE(ArrayEq('a', 0));
7541 TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7542 // Note that a and b are distinct but compatible types.
7543 const int a[] = { 0, 1 };
7544 long b[] = { 0, 1 };
7545 EXPECT_TRUE(ArrayEq(a, b));
7546 EXPECT_TRUE(ArrayEq(a, 2, b));
7549 EXPECT_FALSE(ArrayEq(a, b));
7550 EXPECT_FALSE(ArrayEq(a, 1, b));
7553 TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7554 const char a[][3] = { "hi", "lo" };
7555 const char b[][3] = { "hi", "lo" };
7556 const char c[][3] = { "hi", "li" };
7558 EXPECT_TRUE(ArrayEq(a, b));
7559 EXPECT_TRUE(ArrayEq(a, 2, b));
7561 EXPECT_FALSE(ArrayEq(a, c));
7562 EXPECT_FALSE(ArrayEq(a, 2, c));
7565 // Tests ArrayAwareFind().
7567 TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7568 const char a[] = "hello";
7569 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7570 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7573 TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7574 int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
7575 const int b[2] = { 2, 3 };
7576 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7578 const int c[2] = { 6, 7 };
7579 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7582 // Tests CopyArray().
7584 TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7590 TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7591 const char a[3] = "hi";
7593 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7595 EXPECT_TRUE(ArrayEq(a, b));
7600 EXPECT_TRUE(ArrayEq(a, c));
7603 TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7604 const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
7606 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7608 EXPECT_TRUE(ArrayEq(a, b));
7613 EXPECT_TRUE(ArrayEq(a, c));
7616 // Tests NativeArray.
7618 TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7619 const int a[3] = { 0, 1, 2 };
7620 NativeArray<int> na(a, 3, RelationToSourceReference());
7621 EXPECT_EQ(3U, na.size());
7622 EXPECT_EQ(a, na.begin());
7625 TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7626 typedef int Array[2];
7627 Array* a = new Array[1];
7630 NativeArray<int> na(*a, 2, RelationToSourceCopy());
7631 EXPECT_NE(*a, na.begin());
7633 EXPECT_EQ(0, na.begin()[0]);
7634 EXPECT_EQ(1, na.begin()[1]);
7636 // We rely on the heap checker to verify that na deletes the copy of
7640 TEST(NativeArrayTest, TypeMembersAreCorrect) {
7641 StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7642 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7644 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7645 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7648 TEST(NativeArrayTest, MethodsWork) {
7649 const int a[3] = { 0, 1, 2 };
7650 NativeArray<int> na(a, 3, RelationToSourceCopy());
7651 ASSERT_EQ(3U, na.size());
7652 EXPECT_EQ(3, na.end() - na.begin());
7654 NativeArray<int>::const_iterator it = na.begin();
7661 EXPECT_EQ(na.end(), it);
7663 EXPECT_TRUE(na == na);
7665 NativeArray<int> na2(a, 3, RelationToSourceReference());
7666 EXPECT_TRUE(na == na2);
7668 const int b1[3] = { 0, 1, 1 };
7669 const int b2[4] = { 0, 1, 2, 3 };
7670 EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
7671 EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
7674 TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7675 const char a[2][3] = { "hi", "lo" };
7676 NativeArray<char[3]> na(a, 2, RelationToSourceReference());
7677 ASSERT_EQ(2U, na.size());
7678 EXPECT_EQ(a, na.begin());
7681 // Tests SkipPrefix().
7683 TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7684 const char* const str = "hello";
7686 const char* p = str;
7687 EXPECT_TRUE(SkipPrefix("", &p));
7691 EXPECT_TRUE(SkipPrefix("hell", &p));
7692 EXPECT_EQ(str + 4, p);
7695 TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7696 const char* const str = "world";
7698 const char* p = str;
7699 EXPECT_FALSE(SkipPrefix("W", &p));
7703 EXPECT_FALSE(SkipPrefix("world!", &p));