1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 // Tests for Google Test itself. This verifies that the basic constructs of
34 #include "gtest/gtest.h"
36 // Verifies that the command line flag variables can be accessed in
37 // code once "gtest.h" has been #included.
38 // Do not move it after other gtest #includes.
39 TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
41 GTEST_FLAG_GET(also_run_disabled_tests) ||
42 GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) ||
43 GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) ||
44 GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) ||
45 GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) ||
46 GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) ||
47 GTEST_FLAG_GET(repeat) > 0 ||
48 GTEST_FLAG_GET(recreate_environments_when_repeating) ||
49 GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) ||
50 GTEST_FLAG_GET(stack_trace_depth) > 0 ||
51 GTEST_FLAG_GET(stream_result_to) != "unknown" ||
52 GTEST_FLAG_GET(throw_on_failure);
53 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
56 #include <limits.h> // For INT_MAX.
65 #include <type_traits>
66 #include <unordered_set>
69 #include "gtest/gtest-spi.h"
70 #include "src/gtest-internal-inl.h"
75 #if GTEST_CAN_STREAM_RESULTS_
77 class StreamingListenerTest : public Test {
79 class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
81 // Sends a string to the socket.
82 void Send(const std::string& message) override { output_ += message; }
87 StreamingListenerTest()
88 : fake_sock_writer_(new FakeSocketWriter),
89 streamer_(fake_sock_writer_),
90 test_info_obj_("FooTest", "Bar", nullptr, nullptr,
91 CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {}
94 std::string* output() { return &(fake_sock_writer_->output_); }
96 FakeSocketWriter* const fake_sock_writer_;
97 StreamingListener streamer_;
99 TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test.
102 TEST_F(StreamingListenerTest, OnTestProgramEnd) {
104 streamer_.OnTestProgramEnd(unit_test_);
105 EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
108 TEST_F(StreamingListenerTest, OnTestIterationEnd) {
110 streamer_.OnTestIterationEnd(unit_test_, 42);
111 EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
114 TEST_F(StreamingListenerTest, OnTestCaseStart) {
116 streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", nullptr, nullptr));
117 EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
120 TEST_F(StreamingListenerTest, OnTestCaseEnd) {
122 streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", nullptr, nullptr));
123 EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
126 TEST_F(StreamingListenerTest, OnTestStart) {
128 streamer_.OnTestStart(test_info_obj_);
129 EXPECT_EQ("event=TestStart&name=Bar\n", *output());
132 TEST_F(StreamingListenerTest, OnTestEnd) {
134 streamer_.OnTestEnd(test_info_obj_);
135 EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
138 TEST_F(StreamingListenerTest, OnTestPartResult) {
140 streamer_.OnTestPartResult(TestPartResult(
141 TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
143 // Meta characters in the failure message should be properly escaped.
145 "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
149 #endif // GTEST_CAN_STREAM_RESULTS_
151 // Provides access to otherwise private parts of the TestEventListeners class
152 // that are needed to test it.
153 class TestEventListenersAccessor {
155 static TestEventListener* GetRepeater(TestEventListeners* listeners) {
156 return listeners->repeater();
159 static void SetDefaultResultPrinter(TestEventListeners* listeners,
160 TestEventListener* listener) {
161 listeners->SetDefaultResultPrinter(listener);
163 static void SetDefaultXmlGenerator(TestEventListeners* listeners,
164 TestEventListener* listener) {
165 listeners->SetDefaultXmlGenerator(listener);
168 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
169 return listeners.EventForwardingEnabled();
172 static void SuppressEventForwarding(TestEventListeners* listeners) {
173 listeners->SuppressEventForwarding();
177 class UnitTestRecordPropertyTestHelper : public Test {
179 UnitTestRecordPropertyTestHelper() {}
181 // Forwards to UnitTest::RecordProperty() to bypass access controls.
182 void UnitTestRecordProperty(const char* key, const std::string& value) {
183 unit_test_.RecordProperty(key, value);
189 } // namespace internal
190 } // namespace testing
192 using testing::AssertionFailure;
193 using testing::AssertionResult;
194 using testing::AssertionSuccess;
195 using testing::DoubleLE;
196 using testing::EmptyTestEventListener;
197 using testing::Environment;
198 using testing::FloatLE;
199 using testing::IsNotSubstring;
200 using testing::IsSubstring;
201 using testing::kMaxStackTraceDepth;
202 using testing::Message;
203 using testing::ScopedFakeTestPartResultReporter;
204 using testing::StaticAssertTypeEq;
206 using testing::TestEventListeners;
207 using testing::TestInfo;
208 using testing::TestPartResult;
209 using testing::TestPartResultArray;
210 using testing::TestProperty;
211 using testing::TestResult;
212 using testing::TestSuite;
213 using testing::TimeInMillis;
214 using testing::UnitTest;
215 using testing::internal::AlwaysFalse;
216 using testing::internal::AlwaysTrue;
217 using testing::internal::AppendUserMessage;
218 using testing::internal::ArrayAwareFind;
219 using testing::internal::ArrayEq;
220 using testing::internal::CodePointToUtf8;
221 using testing::internal::CopyArray;
222 using testing::internal::CountIf;
223 using testing::internal::EqFailure;
224 using testing::internal::FloatingPoint;
225 using testing::internal::ForEach;
226 using testing::internal::FormatEpochTimeInMillisAsIso8601;
227 using testing::internal::FormatTimeInMillisAsSeconds;
228 using testing::internal::GetCurrentOsStackTraceExceptTop;
229 using testing::internal::GetElementOr;
230 using testing::internal::GetNextRandomSeed;
231 using testing::internal::GetRandomSeedFromFlag;
232 using testing::internal::GetTestTypeId;
233 using testing::internal::GetTimeInMillis;
234 using testing::internal::GetTypeId;
235 using testing::internal::GetUnitTestImpl;
236 using testing::internal::GTestFlagSaver;
237 using testing::internal::HasDebugStringAndShortDebugString;
238 using testing::internal::Int32FromEnvOrDie;
239 using testing::internal::IsContainer;
240 using testing::internal::IsContainerTest;
241 using testing::internal::IsNotContainer;
242 using testing::internal::kMaxRandomSeed;
243 using testing::internal::kTestTypeIdInGoogleTest;
244 using testing::internal::NativeArray;
245 using testing::internal::OsStackTraceGetter;
246 using testing::internal::OsStackTraceGetterInterface;
247 using testing::internal::ParseFlag;
248 using testing::internal::RelationToSourceCopy;
249 using testing::internal::RelationToSourceReference;
250 using testing::internal::ShouldRunTestOnShard;
251 using testing::internal::ShouldShard;
252 using testing::internal::ShouldUseColor;
253 using testing::internal::Shuffle;
254 using testing::internal::ShuffleRange;
255 using testing::internal::SkipPrefix;
256 using testing::internal::StreamableToString;
257 using testing::internal::String;
258 using testing::internal::TestEventListenersAccessor;
259 using testing::internal::TestResultAccessor;
260 using testing::internal::UnitTestImpl;
261 using testing::internal::WideStringToUtf8;
262 using testing::internal::edit_distance::CalculateOptimalEdits;
263 using testing::internal::edit_distance::CreateUnifiedDiff;
264 using testing::internal::edit_distance::EditType;
266 #if GTEST_HAS_STREAM_REDIRECTION
267 using testing::internal::CaptureStdout;
268 using testing::internal::GetCapturedStdout;
271 #if GTEST_IS_THREADSAFE
272 using testing::internal::ThreadWithParam;
275 class TestingVector : public std::vector<int> {
278 ::std::ostream& operator<<(::std::ostream& os,
279 const TestingVector& vector) {
281 for (size_t i = 0; i < vector.size(); i++) {
282 os << vector[i] << " ";
288 // This line tests that we can define tests in an unnamed namespace.
291 TEST(GetRandomSeedFromFlagTest, HandlesZero) {
292 const int seed = GetRandomSeedFromFlag(0);
294 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
297 TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
298 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
299 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
300 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
301 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
302 GetRandomSeedFromFlag(kMaxRandomSeed));
305 TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
306 const int seed1 = GetRandomSeedFromFlag(-1);
308 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
310 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
312 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
315 TEST(GetNextRandomSeedTest, WorksForValidInput) {
316 EXPECT_EQ(2, GetNextRandomSeed(1));
317 EXPECT_EQ(3, GetNextRandomSeed(2));
318 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
319 GetNextRandomSeed(kMaxRandomSeed - 1));
320 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
322 // We deliberately don't test GetNextRandomSeed() with invalid
323 // inputs, as that requires death tests, which are expensive. This
324 // is fine as GetNextRandomSeed() is internal and has a
325 // straightforward definition.
328 static void ClearCurrentTestPartResults() {
329 TestResultAccessor::ClearTestPartResults(
330 GetUnitTestImpl()->current_test_result());
335 TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
336 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
337 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
340 class SubClassOfTest : public Test {};
341 class AnotherSubClassOfTest : public Test {};
343 TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
344 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
345 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
346 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
347 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
348 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
349 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
352 // Verifies that GetTestTypeId() returns the same value, no matter it
353 // is called from inside Google Test or outside of it.
354 TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
355 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
358 // Tests CanonicalizeForStdLibVersioning.
360 using ::testing::internal::CanonicalizeForStdLibVersioning;
362 TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) {
363 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind"));
364 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_"));
365 EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo"));
366 EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x"));
367 EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x"));
368 EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x"));
371 TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
372 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind"));
373 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_"));
375 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind"));
376 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_"));
378 EXPECT_EQ("std::bind",
379 CanonicalizeForStdLibVersioning("std::__google::bind"));
380 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_"));
383 // Tests FormatTimeInMillisAsSeconds().
385 TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
386 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
389 TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
390 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
391 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
392 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
393 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
394 EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
397 TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
398 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
399 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
400 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
401 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
402 EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
405 // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
406 // for particular dates below was verified in Python using
407 // datetime.datetime.fromutctimestamp(<timetamp>/1000).
409 // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
410 // have to set up a particular timezone to obtain predictable results.
411 class FormatEpochTimeInMillisAsIso8601Test : public Test {
413 // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
414 // 32 bits, even when 64-bit integer types are available. We have to
415 // force the constants to have a 64-bit type here.
416 static const TimeInMillis kMillisPerSec = 1000;
419 void SetUp() override {
422 GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
424 saved_tz_ = strdup(getenv("TZ"));
425 GTEST_DISABLE_MSC_DEPRECATED_POP_()
427 // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
428 // cannot use the local time zone because the function's output depends
430 SetTimeZone("UTC+00");
433 void TearDown() override {
434 SetTimeZone(saved_tz_);
435 free(const_cast<char*>(saved_tz_));
439 static void SetTimeZone(const char* time_zone) {
440 // tzset() distinguishes between the TZ variable being present and empty
441 // and not being present, so we have to consider the case of time_zone
443 #if _MSC_VER || GTEST_OS_WINDOWS_MINGW
444 // ...Unless it's MSVC, whose standard library's _putenv doesn't
445 // distinguish between an empty and a missing variable.
446 const std::string env_var =
447 std::string("TZ=") + (time_zone ? time_zone : "");
448 _putenv(env_var.c_str());
449 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
451 GTEST_DISABLE_MSC_WARNINGS_POP_()
454 setenv(("TZ"), time_zone, 1);
462 const char* saved_tz_;
465 const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
467 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
468 EXPECT_EQ("2011-10-31T18:52:42.000",
469 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
472 TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
474 "2011-10-31T18:52:42.234",
475 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
478 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
479 EXPECT_EQ("2011-09-03T05:07:02.000",
480 FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
483 TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
484 EXPECT_EQ("2011-09-28T17:08:22.000",
485 FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
488 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
489 EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
493 // Silences warnings: "Condition is always true", "Unreachable code"
494 # pragma option push -w-ccc -w-rch
497 // Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal
498 // when the RHS is a pointer type.
499 TEST(NullLiteralTest, LHSAllowsNullLiterals) {
500 EXPECT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
501 ASSERT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
502 EXPECT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
503 ASSERT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
504 EXPECT_EQ(nullptr, static_cast<void*>(nullptr));
505 ASSERT_EQ(nullptr, static_cast<void*>(nullptr));
507 const int* const p = nullptr;
508 EXPECT_EQ(0, p); // NOLINT
509 ASSERT_EQ(0, p); // NOLINT
510 EXPECT_EQ(NULL, p); // NOLINT
511 ASSERT_EQ(NULL, p); // NOLINT
512 EXPECT_EQ(nullptr, p);
513 ASSERT_EQ(nullptr, p);
516 struct ConvertToAll {
517 template <typename T>
518 operator T() const { // NOLINT
523 struct ConvertToPointer {
525 operator T*() const { // NOLINT
530 struct ConvertToAllButNoPointers {
531 template <typename T,
532 typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0>
533 operator T() const { // NOLINT
539 inline bool operator==(MyType const&, MyType const&) { return true; }
541 TEST(NullLiteralTest, ImplicitConversion) {
542 EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr));
543 #if !defined(__GNUC__) || defined(__clang__)
544 // Disabled due to GCC bug gcc.gnu.org/PR89580
545 EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr));
547 EXPECT_EQ(ConvertToAll{}, MyType{});
548 EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{});
552 #pragma clang diagnostic push
553 #if __has_warning("-Wzero-as-null-pointer-constant")
554 #pragma clang diagnostic error "-Wzero-as-null-pointer-constant"
558 TEST(NullLiteralTest, NoConversionNoWarning) {
559 // Test that gtests detection and handling of null pointer constants
560 // doesn't trigger a warning when '0' isn't actually used as null.
566 #pragma clang diagnostic pop
570 // Restores warnings after previous "#pragma option push" suppressed them.
575 // Tests CodePointToUtf8().
577 // Tests that the NUL character L'\0' is encoded correctly.
578 TEST(CodePointToUtf8Test, CanEncodeNul) {
579 EXPECT_EQ("", CodePointToUtf8(L'\0'));
582 // Tests that ASCII characters are encoded correctly.
583 TEST(CodePointToUtf8Test, CanEncodeAscii) {
584 EXPECT_EQ("a", CodePointToUtf8(L'a'));
585 EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
586 EXPECT_EQ("&", CodePointToUtf8(L'&'));
587 EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
590 // Tests that Unicode code-points that have 8 to 11 bits are encoded
591 // as 110xxxxx 10xxxxxx.
592 TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
593 // 000 1101 0011 => 110-00011 10-010011
594 EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
596 // 101 0111 0110 => 110-10101 10-110110
597 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
598 // in wide strings and wide chars. In order to accommodate them, we have to
599 // introduce such character constants as integers.
600 EXPECT_EQ("\xD5\xB6",
601 CodePointToUtf8(static_cast<wchar_t>(0x576)));
604 // Tests that Unicode code-points that have 12 to 16 bits are encoded
605 // as 1110xxxx 10xxxxxx 10xxxxxx.
606 TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
607 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
608 EXPECT_EQ("\xE0\xA3\x93",
609 CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
611 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
612 EXPECT_EQ("\xEC\x9D\x8D",
613 CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
616 #if !GTEST_WIDE_STRING_USES_UTF16_
617 // Tests in this group require a wchar_t to hold > 16 bits, and thus
618 // are skipped on Windows, and Cygwin, where a wchar_t is
619 // 16-bit wide. This code may not compile on those systems.
621 // Tests that Unicode code-points that have 17 to 21 bits are encoded
622 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
623 TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
624 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
625 EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
627 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
628 EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
630 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
631 EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
634 // Tests that encoding an invalid code-point generates the expected result.
635 TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
636 EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
639 #endif // !GTEST_WIDE_STRING_USES_UTF16_
641 // Tests WideStringToUtf8().
643 // Tests that the NUL character L'\0' is encoded correctly.
644 TEST(WideStringToUtf8Test, CanEncodeNul) {
645 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
646 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
649 // Tests that ASCII strings are encoded correctly.
650 TEST(WideStringToUtf8Test, CanEncodeAscii) {
651 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
652 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
653 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
654 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
657 // Tests that Unicode code-points that have 8 to 11 bits are encoded
658 // as 110xxxxx 10xxxxxx.
659 TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
660 // 000 1101 0011 => 110-00011 10-010011
661 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
662 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
664 // 101 0111 0110 => 110-10101 10-110110
665 const wchar_t s[] = { 0x576, '\0' };
666 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
667 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
670 // Tests that Unicode code-points that have 12 to 16 bits are encoded
671 // as 1110xxxx 10xxxxxx 10xxxxxx.
672 TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
673 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
674 const wchar_t s1[] = { 0x8D3, '\0' };
675 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
676 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
678 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
679 const wchar_t s2[] = { 0xC74D, '\0' };
680 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
681 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
684 // Tests that the conversion stops when the function encounters \0 character.
685 TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
686 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
689 // Tests that the conversion stops when the function reaches the limit
690 // specified by the 'length' parameter.
691 TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
692 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
695 #if !GTEST_WIDE_STRING_USES_UTF16_
696 // Tests that Unicode code-points that have 17 to 21 bits are encoded
697 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
698 // on the systems using UTF-16 encoding.
699 TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
700 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
701 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
702 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
704 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
705 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
706 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
709 // Tests that encoding an invalid code-point generates the expected result.
710 TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
711 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
712 WideStringToUtf8(L"\xABCDFF", -1).c_str());
714 #else // !GTEST_WIDE_STRING_USES_UTF16_
715 // Tests that surrogate pairs are encoded correctly on the systems using
716 // UTF-16 encoding in the wide strings.
717 TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
718 const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
719 EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
722 // Tests that encoding an invalid UTF-16 surrogate pair
723 // generates the expected result.
724 TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
725 // Leading surrogate is at the end of the string.
726 const wchar_t s1[] = { 0xD800, '\0' };
727 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
728 // Leading surrogate is not followed by the trailing surrogate.
729 const wchar_t s2[] = { 0xD800, 'M', '\0' };
730 EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
731 // Trailing surrogate appearas without a leading surrogate.
732 const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
733 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
735 #endif // !GTEST_WIDE_STRING_USES_UTF16_
737 // Tests that codepoint concatenation works correctly.
738 #if !GTEST_WIDE_STRING_USES_UTF16_
739 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
740 const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
748 WideStringToUtf8(s, -1).c_str());
751 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
752 const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
754 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
755 WideStringToUtf8(s, -1).c_str());
757 #endif // !GTEST_WIDE_STRING_USES_UTF16_
759 // Tests the Random class.
761 TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
762 testing::internal::Random random(42);
763 EXPECT_DEATH_IF_SUPPORTED(
765 "Cannot generate a number in the range \\[0, 0\\)");
766 EXPECT_DEATH_IF_SUPPORTED(
767 random.Generate(testing::internal::Random::kMaxRange + 1),
768 "Generation of a number in \\[0, 2147483649\\) was requested, "
769 "but this can only generate numbers in \\[0, 2147483648\\)");
772 TEST(RandomTest, GeneratesNumbersWithinRange) {
773 constexpr uint32_t kRange = 10000;
774 testing::internal::Random random(12345);
775 for (int i = 0; i < 10; i++) {
776 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
779 testing::internal::Random random2(testing::internal::Random::kMaxRange);
780 for (int i = 0; i < 10; i++) {
781 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
785 TEST(RandomTest, RepeatsWhenReseeded) {
786 constexpr int kSeed = 123;
787 constexpr int kArraySize = 10;
788 constexpr uint32_t kRange = 10000;
789 uint32_t values[kArraySize];
791 testing::internal::Random random(kSeed);
792 for (int i = 0; i < kArraySize; i++) {
793 values[i] = random.Generate(kRange);
796 random.Reseed(kSeed);
797 for (int i = 0; i < kArraySize; i++) {
798 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
802 // Tests STL container utilities.
806 static bool IsPositive(int n) { return n > 0; }
808 TEST(ContainerUtilityTest, CountIf) {
810 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
814 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
819 EXPECT_EQ(2, CountIf(v, IsPositive));
824 static int g_sum = 0;
825 static void Accumulate(int n) { g_sum += n; }
827 TEST(ContainerUtilityTest, ForEach) {
830 ForEach(v, Accumulate);
831 EXPECT_EQ(0, g_sum); // Works for an empty container;
835 ForEach(v, Accumulate);
836 EXPECT_EQ(1, g_sum); // Works for a container with one element.
841 ForEach(v, Accumulate);
842 EXPECT_EQ(321, g_sum);
845 // Tests GetElementOr().
846 TEST(ContainerUtilityTest, GetElementOr) {
848 EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
852 EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
853 EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
854 EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
855 EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
858 TEST(ContainerUtilityDeathTest, ShuffleRange) {
863 testing::internal::Random random(1);
865 EXPECT_DEATH_IF_SUPPORTED(
866 ShuffleRange(&random, -1, 1, &a),
867 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
868 EXPECT_DEATH_IF_SUPPORTED(
869 ShuffleRange(&random, 4, 4, &a),
870 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
871 EXPECT_DEATH_IF_SUPPORTED(
872 ShuffleRange(&random, 3, 2, &a),
873 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
874 EXPECT_DEATH_IF_SUPPORTED(
875 ShuffleRange(&random, 3, 4, &a),
876 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
879 class VectorShuffleTest : public Test {
881 static const size_t kVectorSize = 20;
883 VectorShuffleTest() : random_(1) {
884 for (int i = 0; i < static_cast<int>(kVectorSize); i++) {
885 vector_.push_back(i);
889 static bool VectorIsCorrupt(const TestingVector& vector) {
890 if (kVectorSize != vector.size()) {
894 bool found_in_vector[kVectorSize] = { false };
895 for (size_t i = 0; i < vector.size(); i++) {
896 const int e = vector[i];
897 if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {
900 found_in_vector[e] = true;
903 // Vector size is correct, elements' range is correct, no
904 // duplicate elements. Therefore no corruption has occurred.
908 static bool VectorIsNotCorrupt(const TestingVector& vector) {
909 return !VectorIsCorrupt(vector);
912 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
913 for (int i = begin; i < end; i++) {
914 if (i != vector[static_cast<size_t>(i)]) {
921 static bool RangeIsUnshuffled(
922 const TestingVector& vector, int begin, int end) {
923 return !RangeIsShuffled(vector, begin, end);
926 static bool VectorIsShuffled(const TestingVector& vector) {
927 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
930 static bool VectorIsUnshuffled(const TestingVector& vector) {
931 return !VectorIsShuffled(vector);
934 testing::internal::Random random_;
935 TestingVector vector_;
936 }; // class VectorShuffleTest
938 const size_t VectorShuffleTest::kVectorSize;
940 TEST_F(VectorShuffleTest, HandlesEmptyRange) {
941 // Tests an empty range at the beginning...
942 ShuffleRange(&random_, 0, 0, &vector_);
943 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
944 ASSERT_PRED1(VectorIsUnshuffled, vector_);
946 // ...in the middle...
947 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
948 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
949 ASSERT_PRED1(VectorIsUnshuffled, vector_);
952 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
953 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
954 ASSERT_PRED1(VectorIsUnshuffled, vector_);
956 // ...and past the end.
957 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
958 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
959 ASSERT_PRED1(VectorIsUnshuffled, vector_);
962 TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
963 // Tests a size one range at the beginning...
964 ShuffleRange(&random_, 0, 1, &vector_);
965 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
966 ASSERT_PRED1(VectorIsUnshuffled, vector_);
968 // ...in the middle...
969 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
970 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
971 ASSERT_PRED1(VectorIsUnshuffled, vector_);
973 // ...and at the end.
974 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
975 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
976 ASSERT_PRED1(VectorIsUnshuffled, vector_);
979 // Because we use our own random number generator and a fixed seed,
980 // we can guarantee that the following "random" tests will succeed.
982 TEST_F(VectorShuffleTest, ShufflesEntireVector) {
983 Shuffle(&random_, &vector_);
984 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
985 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
987 // Tests the first and last elements in particular to ensure that
988 // there are no off-by-one problems in our shuffle algorithm.
989 EXPECT_NE(0, vector_[0]);
990 EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);
993 TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
994 const int kRangeSize = kVectorSize/2;
996 ShuffleRange(&random_, 0, kRangeSize, &vector_);
998 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
999 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
1000 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize,
1001 static_cast<int>(kVectorSize));
1004 TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
1005 const int kRangeSize = kVectorSize / 2;
1006 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
1008 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1009 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1010 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize,
1011 static_cast<int>(kVectorSize));
1014 TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
1015 const int kRangeSize = static_cast<int>(kVectorSize) / 3;
1016 ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
1018 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1019 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1020 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
1021 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,
1022 static_cast<int>(kVectorSize));
1025 TEST_F(VectorShuffleTest, ShufflesRepeatably) {
1026 TestingVector vector2;
1027 for (size_t i = 0; i < kVectorSize; i++) {
1028 vector2.push_back(static_cast<int>(i));
1031 random_.Reseed(1234);
1032 Shuffle(&random_, &vector_);
1033 random_.Reseed(1234);
1034 Shuffle(&random_, &vector2);
1036 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1037 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
1039 for (size_t i = 0; i < kVectorSize; i++) {
1040 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
1044 // Tests the size of the AssertHelper class.
1046 TEST(AssertHelperTest, AssertHelperIsSmall) {
1047 // To avoid breaking clients that use lots of assertions in one
1048 // function, we cannot grow the size of AssertHelper.
1049 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
1052 // Tests String::EndsWithCaseInsensitive().
1053 TEST(StringTest, EndsWithCaseInsensitive) {
1054 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
1055 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
1056 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
1057 EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
1059 EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
1060 EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
1061 EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
1064 // C++Builder's preprocessor is buggy; it fails to expand macros that
1065 // appear in macro parameters after wide char literals. Provide an alias
1066 // for NULL as a workaround.
1067 static const wchar_t* const kNull = nullptr;
1069 // Tests String::CaseInsensitiveWideCStringEquals
1070 TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1071 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr));
1072 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1073 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1074 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1075 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
1076 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1077 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1078 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1081 #if GTEST_OS_WINDOWS
1083 // Tests String::ShowWideCString().
1084 TEST(StringTest, ShowWideCString) {
1085 EXPECT_STREQ("(null)",
1086 String::ShowWideCString(NULL).c_str());
1087 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1088 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1091 # if GTEST_OS_WINDOWS_MOBILE
1092 TEST(StringTest, AnsiAndUtf16Null) {
1093 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1094 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1097 TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1098 const char* ansi = String::Utf16ToAnsi(L"str");
1099 EXPECT_STREQ("str", ansi);
1101 const WCHAR* utf16 = String::AnsiToUtf16("str");
1102 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
1106 TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1107 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1108 EXPECT_STREQ(".:\\ \"*?", ansi);
1110 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
1111 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
1114 # endif // GTEST_OS_WINDOWS_MOBILE
1116 #endif // GTEST_OS_WINDOWS
1118 // Tests TestProperty construction.
1119 TEST(TestPropertyTest, StringValue) {
1120 TestProperty property("key", "1");
1121 EXPECT_STREQ("key", property.key());
1122 EXPECT_STREQ("1", property.value());
1125 // Tests TestProperty replacing a value.
1126 TEST(TestPropertyTest, ReplaceStringValue) {
1127 TestProperty property("key", "1");
1128 EXPECT_STREQ("1", property.value());
1129 property.SetValue("2");
1130 EXPECT_STREQ("2", property.value());
1133 // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1134 // functions (i.e. their definitions cannot be inlined at the call
1135 // sites), or C++Builder won't compile the code.
1136 static void AddFatalFailure() {
1137 FAIL() << "Expected fatal failure.";
1140 static void AddNonfatalFailure() {
1141 ADD_FAILURE() << "Expected non-fatal failure.";
1144 class ScopedFakeTestPartResultReporterTest : public Test {
1145 public: // Must be public and not protected due to a bug in g++ 3.4.2.
1150 static void AddFailure(FailureMode failure) {
1151 if (failure == FATAL_FAILURE) {
1154 AddNonfatalFailure();
1159 // Tests that ScopedFakeTestPartResultReporter intercepts test
1161 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
1162 TestPartResultArray results;
1164 ScopedFakeTestPartResultReporter reporter(
1165 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1167 AddFailure(NONFATAL_FAILURE);
1168 AddFailure(FATAL_FAILURE);
1171 EXPECT_EQ(2, results.size());
1172 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1173 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1176 TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1177 TestPartResultArray results;
1179 // Tests, that the deprecated constructor still works.
1180 ScopedFakeTestPartResultReporter reporter(&results);
1181 AddFailure(NONFATAL_FAILURE);
1183 EXPECT_EQ(1, results.size());
1186 #if GTEST_IS_THREADSAFE
1188 class ScopedFakeTestPartResultReporterWithThreadsTest
1189 : public ScopedFakeTestPartResultReporterTest {
1191 static void AddFailureInOtherThread(FailureMode failure) {
1192 ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
1197 TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1198 InterceptsTestFailuresInAllThreads) {
1199 TestPartResultArray results;
1201 ScopedFakeTestPartResultReporter reporter(
1202 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1203 AddFailure(NONFATAL_FAILURE);
1204 AddFailure(FATAL_FAILURE);
1205 AddFailureInOtherThread(NONFATAL_FAILURE);
1206 AddFailureInOtherThread(FATAL_FAILURE);
1209 EXPECT_EQ(4, results.size());
1210 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1211 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1212 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1213 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1216 #endif // GTEST_IS_THREADSAFE
1218 // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1219 // work even if the failure is generated in a called function rather than
1220 // the current context.
1222 typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
1224 TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1225 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
1228 TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1229 EXPECT_FATAL_FAILURE(AddFatalFailure(),
1230 ::std::string("Expected fatal failure."));
1233 TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1234 // We have another test below to verify that the macro catches fatal
1235 // failures generated on another thread.
1236 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
1237 "Expected fatal failure.");
1241 // Silences warnings: "Condition is always true"
1242 # pragma option push -w-ccc
1245 // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1246 // function even when the statement in it contains ASSERT_*.
1248 int NonVoidFunction() {
1249 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1250 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1254 TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1258 // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1259 // current function even though 'statement' generates a fatal failure.
1261 void DoesNotAbortHelper(bool* aborted) {
1262 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1263 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1269 // Restores warnings after previous "#pragma option push" suppressed them.
1273 TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1274 bool aborted = true;
1275 DoesNotAbortHelper(&aborted);
1276 EXPECT_FALSE(aborted);
1279 // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1280 // statement that contains a macro which expands to code containing an
1281 // unprotected comma.
1283 static int global_var = 0;
1284 #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1286 TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1287 #ifndef __BORLANDC__
1288 // ICE's in C++Builder.
1289 EXPECT_FATAL_FAILURE({
1290 GTEST_USE_UNPROTECTED_COMMA_;
1295 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1296 GTEST_USE_UNPROTECTED_COMMA_;
1301 // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1303 typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1305 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1306 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1307 "Expected non-fatal failure.");
1310 TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1311 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1312 ::std::string("Expected non-fatal failure."));
1315 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1316 // We have another test below to verify that the macro catches
1317 // non-fatal failures generated on another thread.
1318 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
1319 "Expected non-fatal failure.");
1322 // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1323 // statement that contains a macro which expands to code containing an
1324 // unprotected comma.
1325 TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1326 EXPECT_NONFATAL_FAILURE({
1327 GTEST_USE_UNPROTECTED_COMMA_;
1328 AddNonfatalFailure();
1331 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1332 GTEST_USE_UNPROTECTED_COMMA_;
1333 AddNonfatalFailure();
1337 #if GTEST_IS_THREADSAFE
1339 typedef ScopedFakeTestPartResultReporterWithThreadsTest
1340 ExpectFailureWithThreadsTest;
1342 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1343 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1344 "Expected fatal failure.");
1347 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1348 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1349 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1352 #endif // GTEST_IS_THREADSAFE
1354 // Tests the TestProperty class.
1356 TEST(TestPropertyTest, ConstructorWorks) {
1357 const TestProperty property("key", "value");
1358 EXPECT_STREQ("key", property.key());
1359 EXPECT_STREQ("value", property.value());
1362 TEST(TestPropertyTest, SetValue) {
1363 TestProperty property("key", "value_1");
1364 EXPECT_STREQ("key", property.key());
1365 property.SetValue("value_2");
1366 EXPECT_STREQ("key", property.key());
1367 EXPECT_STREQ("value_2", property.value());
1370 // Tests the TestResult class
1372 // The test fixture for testing TestResult.
1373 class TestResultTest : public Test {
1375 typedef std::vector<TestPartResult> TPRVector;
1377 // We make use of 2 TestPartResult objects,
1378 TestPartResult * pr1, * pr2;
1380 // ... and 3 TestResult objects.
1381 TestResult * r0, * r1, * r2;
1383 void SetUp() override {
1384 // pr1 is for success.
1385 pr1 = new TestPartResult(TestPartResult::kSuccess,
1390 // pr2 is for fatal failure.
1391 pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1393 -1, // This line number means "unknown"
1396 // Creates the TestResult objects.
1397 r0 = new TestResult();
1398 r1 = new TestResult();
1399 r2 = new TestResult();
1401 // In order to test TestResult, we need to modify its internal
1402 // state, in particular the TestPartResult vector it holds.
1403 // test_part_results() returns a const reference to this vector.
1404 // We cast it to a non-const object s.t. it can be modified
1405 TPRVector* results1 = const_cast<TPRVector*>(
1406 &TestResultAccessor::test_part_results(*r1));
1407 TPRVector* results2 = const_cast<TPRVector*>(
1408 &TestResultAccessor::test_part_results(*r2));
1410 // r0 is an empty TestResult.
1412 // r1 contains a single SUCCESS TestPartResult.
1413 results1->push_back(*pr1);
1415 // r2 contains a SUCCESS, and a FAILURE.
1416 results2->push_back(*pr1);
1417 results2->push_back(*pr2);
1420 void TearDown() override {
1429 // Helper that compares two TestPartResults.
1430 static void CompareTestPartResult(const TestPartResult& expected,
1431 const TestPartResult& actual) {
1432 EXPECT_EQ(expected.type(), actual.type());
1433 EXPECT_STREQ(expected.file_name(), actual.file_name());
1434 EXPECT_EQ(expected.line_number(), actual.line_number());
1435 EXPECT_STREQ(expected.summary(), actual.summary());
1436 EXPECT_STREQ(expected.message(), actual.message());
1437 EXPECT_EQ(expected.passed(), actual.passed());
1438 EXPECT_EQ(expected.failed(), actual.failed());
1439 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1440 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
1444 // Tests TestResult::total_part_count().
1445 TEST_F(TestResultTest, total_part_count) {
1446 ASSERT_EQ(0, r0->total_part_count());
1447 ASSERT_EQ(1, r1->total_part_count());
1448 ASSERT_EQ(2, r2->total_part_count());
1451 // Tests TestResult::Passed().
1452 TEST_F(TestResultTest, Passed) {
1453 ASSERT_TRUE(r0->Passed());
1454 ASSERT_TRUE(r1->Passed());
1455 ASSERT_FALSE(r2->Passed());
1458 // Tests TestResult::Failed().
1459 TEST_F(TestResultTest, Failed) {
1460 ASSERT_FALSE(r0->Failed());
1461 ASSERT_FALSE(r1->Failed());
1462 ASSERT_TRUE(r2->Failed());
1465 // Tests TestResult::GetTestPartResult().
1467 typedef TestResultTest TestResultDeathTest;
1469 TEST_F(TestResultDeathTest, GetTestPartResult) {
1470 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1471 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1472 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1473 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
1476 // Tests TestResult has no properties when none are added.
1477 TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1478 TestResult test_result;
1479 ASSERT_EQ(0, test_result.test_property_count());
1482 // Tests TestResult has the expected property when added.
1483 TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1484 TestResult test_result;
1485 TestProperty property("key_1", "1");
1486 TestResultAccessor::RecordProperty(&test_result, "testcase", property);
1487 ASSERT_EQ(1, test_result.test_property_count());
1488 const TestProperty& actual_property = test_result.GetTestProperty(0);
1489 EXPECT_STREQ("key_1", actual_property.key());
1490 EXPECT_STREQ("1", actual_property.value());
1493 // Tests TestResult has multiple properties when added.
1494 TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1495 TestResult test_result;
1496 TestProperty property_1("key_1", "1");
1497 TestProperty property_2("key_2", "2");
1498 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1499 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1500 ASSERT_EQ(2, test_result.test_property_count());
1501 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1502 EXPECT_STREQ("key_1", actual_property_1.key());
1503 EXPECT_STREQ("1", actual_property_1.value());
1505 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1506 EXPECT_STREQ("key_2", actual_property_2.key());
1507 EXPECT_STREQ("2", actual_property_2.value());
1510 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
1511 TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1512 TestResult test_result;
1513 TestProperty property_1_1("key_1", "1");
1514 TestProperty property_2_1("key_2", "2");
1515 TestProperty property_1_2("key_1", "12");
1516 TestProperty property_2_2("key_2", "22");
1517 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
1518 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
1519 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
1520 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
1522 ASSERT_EQ(2, test_result.test_property_count());
1523 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1524 EXPECT_STREQ("key_1", actual_property_1.key());
1525 EXPECT_STREQ("12", actual_property_1.value());
1527 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1528 EXPECT_STREQ("key_2", actual_property_2.key());
1529 EXPECT_STREQ("22", actual_property_2.value());
1532 // Tests TestResult::GetTestProperty().
1533 TEST(TestResultPropertyTest, GetTestProperty) {
1534 TestResult test_result;
1535 TestProperty property_1("key_1", "1");
1536 TestProperty property_2("key_2", "2");
1537 TestProperty property_3("key_3", "3");
1538 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1539 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1540 TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
1542 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1543 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1544 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
1546 EXPECT_STREQ("key_1", fetched_property_1.key());
1547 EXPECT_STREQ("1", fetched_property_1.value());
1549 EXPECT_STREQ("key_2", fetched_property_2.key());
1550 EXPECT_STREQ("2", fetched_property_2.value());
1552 EXPECT_STREQ("key_3", fetched_property_3.key());
1553 EXPECT_STREQ("3", fetched_property_3.value());
1555 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1556 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
1559 // Tests the Test class.
1561 // It's difficult to test every public method of this class (we are
1562 // already stretching the limit of Google Test by using it to test itself!).
1563 // Fortunately, we don't have to do that, as we are already testing
1564 // the functionalities of the Test class extensively by using Google Test
1567 // Therefore, this section only contains one test.
1569 // Tests that GTestFlagSaver works on Windows and Mac.
1571 class GTestFlagSaverTest : public Test {
1573 // Saves the Google Test flags such that we can restore them later, and
1574 // then sets them to their default values. This will be called
1575 // before the first test in this test case is run.
1576 static void SetUpTestSuite() {
1577 saver_ = new GTestFlagSaver;
1579 GTEST_FLAG_SET(also_run_disabled_tests, false);
1580 GTEST_FLAG_SET(break_on_failure, false);
1581 GTEST_FLAG_SET(catch_exceptions, false);
1582 GTEST_FLAG_SET(death_test_use_fork, false);
1583 GTEST_FLAG_SET(color, "auto");
1584 GTEST_FLAG_SET(fail_fast, false);
1585 GTEST_FLAG_SET(filter, "");
1586 GTEST_FLAG_SET(list_tests, false);
1587 GTEST_FLAG_SET(output, "");
1588 GTEST_FLAG_SET(brief, false);
1589 GTEST_FLAG_SET(print_time, true);
1590 GTEST_FLAG_SET(random_seed, 0);
1591 GTEST_FLAG_SET(repeat, 1);
1592 GTEST_FLAG_SET(recreate_environments_when_repeating, true);
1593 GTEST_FLAG_SET(shuffle, false);
1594 GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
1595 GTEST_FLAG_SET(stream_result_to, "");
1596 GTEST_FLAG_SET(throw_on_failure, false);
1599 // Restores the Google Test flags that the tests have modified. This will
1600 // be called after the last test in this test case is run.
1601 static void TearDownTestSuite() {
1606 // Verifies that the Google Test flags have their default values, and then
1607 // modifies each of them.
1608 void VerifyAndModifyFlags() {
1609 EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests));
1610 EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure));
1611 EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions));
1612 EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str());
1613 EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork));
1614 EXPECT_FALSE(GTEST_FLAG_GET(fail_fast));
1615 EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str());
1616 EXPECT_FALSE(GTEST_FLAG_GET(list_tests));
1617 EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str());
1618 EXPECT_FALSE(GTEST_FLAG_GET(brief));
1619 EXPECT_TRUE(GTEST_FLAG_GET(print_time));
1620 EXPECT_EQ(0, GTEST_FLAG_GET(random_seed));
1621 EXPECT_EQ(1, GTEST_FLAG_GET(repeat));
1622 EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating));
1623 EXPECT_FALSE(GTEST_FLAG_GET(shuffle));
1624 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth));
1625 EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str());
1626 EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure));
1628 GTEST_FLAG_SET(also_run_disabled_tests, true);
1629 GTEST_FLAG_SET(break_on_failure, true);
1630 GTEST_FLAG_SET(catch_exceptions, true);
1631 GTEST_FLAG_SET(color, "no");
1632 GTEST_FLAG_SET(death_test_use_fork, true);
1633 GTEST_FLAG_SET(fail_fast, true);
1634 GTEST_FLAG_SET(filter, "abc");
1635 GTEST_FLAG_SET(list_tests, true);
1636 GTEST_FLAG_SET(output, "xml:foo.xml");
1637 GTEST_FLAG_SET(brief, true);
1638 GTEST_FLAG_SET(print_time, false);
1639 GTEST_FLAG_SET(random_seed, 1);
1640 GTEST_FLAG_SET(repeat, 100);
1641 GTEST_FLAG_SET(recreate_environments_when_repeating, false);
1642 GTEST_FLAG_SET(shuffle, true);
1643 GTEST_FLAG_SET(stack_trace_depth, 1);
1644 GTEST_FLAG_SET(stream_result_to, "localhost:1234");
1645 GTEST_FLAG_SET(throw_on_failure, true);
1649 // For saving Google Test flags during this test case.
1650 static GTestFlagSaver* saver_;
1653 GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;
1655 // Google Test doesn't guarantee the order of tests. The following two
1656 // tests are designed to work regardless of their order.
1658 // Modifies the Google Test flags in the test body.
1659 TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1660 VerifyAndModifyFlags();
1663 // Verifies that the Google Test flags in the body of the previous test were
1664 // restored to their original values.
1665 TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1666 VerifyAndModifyFlags();
1669 // Sets an environment variable with the given name to the given
1670 // value. If the value argument is "", unsets the environment
1671 // variable. The caller must ensure that both arguments are not NULL.
1672 static void SetEnv(const char* name, const char* value) {
1673 #if GTEST_OS_WINDOWS_MOBILE
1674 // Environment variables are not supported on Windows CE.
1676 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1677 // C++Builder's putenv only stores a pointer to its parameter; we have to
1678 // ensure that the string remains valid as long as it might be needed.
1679 // We use an std::map to do so.
1680 static std::map<std::string, std::string*> added_env;
1682 // Because putenv stores a pointer to the string buffer, we can't delete the
1683 // previous string (if present) until after it's replaced.
1684 std::string *prev_env = NULL;
1685 if (added_env.find(name) != added_env.end()) {
1686 prev_env = added_env[name];
1688 added_env[name] = new std::string(
1689 (Message() << name << "=" << value).GetString());
1691 // The standard signature of putenv accepts a 'char*' argument. Other
1692 // implementations, like C++Builder's, accept a 'const char*'.
1693 // We cast away the 'const' since that would work for both variants.
1694 putenv(const_cast<char*>(added_env[name]->c_str()));
1696 #elif GTEST_OS_WINDOWS // If we are on Windows proper.
1697 _putenv((Message() << name << "=" << value).GetString().c_str());
1699 if (*value == '\0') {
1702 setenv(name, value, 1);
1704 #endif // GTEST_OS_WINDOWS_MOBILE
1707 #if !GTEST_OS_WINDOWS_MOBILE
1708 // Environment variables are not supported on Windows CE.
1710 using testing::internal::Int32FromGTestEnv;
1712 // Tests Int32FromGTestEnv().
1714 // Tests that Int32FromGTestEnv() returns the default value when the
1715 // environment variable is not set.
1716 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1717 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1718 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1721 # if !defined(GTEST_GET_INT32_FROM_ENV_)
1723 // Tests that Int32FromGTestEnv() returns the default value when the
1724 // environment variable overflows as an Int32.
1725 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1726 printf("(expecting 2 warnings)\n");
1728 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1729 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1731 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1732 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1735 // Tests that Int32FromGTestEnv() returns the default value when the
1736 // environment variable does not represent a valid decimal integer.
1737 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1738 printf("(expecting 2 warnings)\n");
1740 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1741 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1743 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1744 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1747 # endif // !defined(GTEST_GET_INT32_FROM_ENV_)
1749 // Tests that Int32FromGTestEnv() parses and returns the value of the
1750 // environment variable when it represents a valid decimal integer in
1751 // the range of an Int32.
1752 TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1753 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1754 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1756 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1757 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1759 #endif // !GTEST_OS_WINDOWS_MOBILE
1761 // Tests ParseFlag().
1763 // Tests that ParseInt32Flag() returns false and doesn't change the
1764 // output value when the flag has wrong format
1765 TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1766 int32_t value = 123;
1767 EXPECT_FALSE(ParseFlag("--a=100", "b", &value));
1768 EXPECT_EQ(123, value);
1770 EXPECT_FALSE(ParseFlag("a=100", "a", &value));
1771 EXPECT_EQ(123, value);
1774 // Tests that ParseFlag() returns false and doesn't change the
1775 // output value when the flag overflows as an Int32.
1776 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1777 printf("(expecting 2 warnings)\n");
1779 int32_t value = 123;
1780 EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value));
1781 EXPECT_EQ(123, value);
1783 EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value));
1784 EXPECT_EQ(123, value);
1787 // Tests that ParseInt32Flag() returns false and doesn't change the
1788 // output value when the flag does not represent a valid decimal
1790 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1791 printf("(expecting 2 warnings)\n");
1793 int32_t value = 123;
1794 EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value));
1795 EXPECT_EQ(123, value);
1797 EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value));
1798 EXPECT_EQ(123, value);
1801 // Tests that ParseInt32Flag() parses the value of the flag and
1802 // returns true when the flag represents a valid decimal integer in
1803 // the range of an Int32.
1804 TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1805 int32_t value = 123;
1806 EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1807 EXPECT_EQ(456, value);
1809 EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value));
1810 EXPECT_EQ(-789, value);
1813 // Tests that Int32FromEnvOrDie() parses the value of the var or
1814 // returns the correct default.
1815 // Environment variables are not supported on Windows CE.
1816 #if !GTEST_OS_WINDOWS_MOBILE
1817 TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1818 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1819 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1820 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1821 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1822 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1824 #endif // !GTEST_OS_WINDOWS_MOBILE
1826 // Tests that Int32FromEnvOrDie() aborts with an error message
1827 // if the variable is not an int32_t.
1828 TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1829 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1830 EXPECT_DEATH_IF_SUPPORTED(
1831 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1835 // Tests that Int32FromEnvOrDie() aborts with an error message
1836 // if the variable cannot be represented by an int32_t.
1837 TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1838 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1839 EXPECT_DEATH_IF_SUPPORTED(
1840 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1844 // Tests that ShouldRunTestOnShard() selects all tests
1845 // where there is 1 shard.
1846 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1847 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1848 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1849 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1850 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1851 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1854 class ShouldShardTest : public testing::Test {
1856 void SetUp() override {
1857 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1858 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1861 void TearDown() override {
1862 SetEnv(index_var_, "");
1863 SetEnv(total_var_, "");
1866 const char* index_var_;
1867 const char* total_var_;
1870 // Tests that sharding is disabled if neither of the environment variables
1872 TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1873 SetEnv(index_var_, "");
1874 SetEnv(total_var_, "");
1876 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1877 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1880 // Tests that sharding is not enabled if total_shards == 1.
1881 TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1882 SetEnv(index_var_, "0");
1883 SetEnv(total_var_, "1");
1884 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1885 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1888 // Tests that sharding is enabled if total_shards > 1 and
1889 // we are not in a death test subprocess.
1890 // Environment variables are not supported on Windows CE.
1891 #if !GTEST_OS_WINDOWS_MOBILE
1892 TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1893 SetEnv(index_var_, "4");
1894 SetEnv(total_var_, "22");
1895 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1896 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1898 SetEnv(index_var_, "8");
1899 SetEnv(total_var_, "9");
1900 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1901 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1903 SetEnv(index_var_, "0");
1904 SetEnv(total_var_, "9");
1905 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1906 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1908 #endif // !GTEST_OS_WINDOWS_MOBILE
1910 // Tests that we exit in error if the sharding values are not valid.
1912 typedef ShouldShardTest ShouldShardDeathTest;
1914 TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
1915 SetEnv(index_var_, "4");
1916 SetEnv(total_var_, "4");
1917 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1919 SetEnv(index_var_, "4");
1920 SetEnv(total_var_, "-2");
1921 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1923 SetEnv(index_var_, "5");
1924 SetEnv(total_var_, "");
1925 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1927 SetEnv(index_var_, "");
1928 SetEnv(total_var_, "5");
1929 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1932 // Tests that ShouldRunTestOnShard is a partition when 5
1934 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1935 // Choose an arbitrary number of tests and shards.
1936 const int num_tests = 17;
1937 const int num_shards = 5;
1939 // Check partitioning: each test should be on exactly 1 shard.
1940 for (int test_id = 0; test_id < num_tests; test_id++) {
1941 int prev_selected_shard_index = -1;
1942 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1943 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1944 if (prev_selected_shard_index < 0) {
1945 prev_selected_shard_index = shard_index;
1947 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1948 << shard_index << " are both selected to run test " << test_id;
1954 // Check balance: This is not required by the sharding protocol, but is a
1955 // desirable property for performance.
1956 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1957 int num_tests_on_shard = 0;
1958 for (int test_id = 0; test_id < num_tests; test_id++) {
1959 num_tests_on_shard +=
1960 ShouldRunTestOnShard(num_shards, shard_index, test_id);
1962 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1966 // For the same reason we are not explicitly testing everything in the
1967 // Test class, there are no separate tests for the following classes
1968 // (except for some trivial cases):
1970 // TestSuite, UnitTest, UnitTestResultPrinter.
1972 // Similarly, there are no separate tests for the following macros:
1974 // TEST, TEST_F, RUN_ALL_TESTS
1976 TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1977 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr);
1978 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1981 TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
1982 EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
1983 EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
1986 // When a property using a reserved key is supplied to this function, it
1987 // tests that a non-fatal failure is added, a fatal failure is not added,
1988 // and that the property is not recorded.
1989 void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1990 const TestResult& test_result, const char* key) {
1991 EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
1992 ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
1993 << "' recorded unexpectedly.";
1996 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
1998 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
1999 ASSERT_TRUE(test_info != nullptr);
2000 ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
2004 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2006 const testing::TestSuite* test_suite =
2007 UnitTest::GetInstance()->current_test_suite();
2008 ASSERT_TRUE(test_suite != nullptr);
2009 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2010 test_suite->ad_hoc_test_result(), key);
2013 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2015 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2016 UnitTest::GetInstance()->ad_hoc_test_result(), key);
2019 // Tests that property recording functions in UnitTest outside of tests
2020 // functions correcly. Creating a separate instance of UnitTest ensures it
2021 // is in a state similar to the UnitTest's singleton's between tests.
2022 class UnitTestRecordPropertyTest :
2023 public testing::internal::UnitTestRecordPropertyTestHelper {
2025 static void SetUpTestSuite() {
2026 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2028 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2030 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2032 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2034 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2036 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2039 Test::RecordProperty("test_case_key_1", "1");
2041 const testing::TestSuite* test_suite =
2042 UnitTest::GetInstance()->current_test_suite();
2044 ASSERT_TRUE(test_suite != nullptr);
2046 ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count());
2047 EXPECT_STREQ("test_case_key_1",
2048 test_suite->ad_hoc_test_result().GetTestProperty(0).key());
2050 test_suite->ad_hoc_test_result().GetTestProperty(0).value());
2054 // Tests TestResult has the expected property when added.
2055 TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
2056 UnitTestRecordProperty("key_1", "1");
2058 ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
2060 EXPECT_STREQ("key_1",
2061 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2063 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2066 // Tests TestResult has multiple properties when added.
2067 TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
2068 UnitTestRecordProperty("key_1", "1");
2069 UnitTestRecordProperty("key_2", "2");
2071 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2073 EXPECT_STREQ("key_1",
2074 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2075 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2077 EXPECT_STREQ("key_2",
2078 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2079 EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2082 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
2083 TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
2084 UnitTestRecordProperty("key_1", "1");
2085 UnitTestRecordProperty("key_2", "2");
2086 UnitTestRecordProperty("key_1", "12");
2087 UnitTestRecordProperty("key_2", "22");
2089 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2091 EXPECT_STREQ("key_1",
2092 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2094 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2096 EXPECT_STREQ("key_2",
2097 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2099 unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2102 TEST_F(UnitTestRecordPropertyTest,
2103 AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
2104 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2106 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2108 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2110 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2112 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2114 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2118 TEST_F(UnitTestRecordPropertyTest,
2119 AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
2120 EXPECT_NONFATAL_FAILURE(
2121 Test::RecordProperty("name", "1"),
2122 "'classname', 'name', 'status', 'time', 'type_param', 'value_param',"
2123 " 'file', and 'line' are reserved");
2126 class UnitTestRecordPropertyTestEnvironment : public Environment {
2128 void TearDown() override {
2129 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2131 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2133 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2135 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2137 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2139 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2141 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2143 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2148 // This will test property recording outside of any test or test case.
2149 static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ =
2150 AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
2152 // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2153 // of various arities. They do not attempt to be exhaustive. Rather,
2154 // view them as smoke tests that can be easily reviewed and verified.
2155 // A more complete set of tests for predicate assertions can be found
2156 // in gtest_pred_impl_unittest.cc.
2158 // First, some predicates and predicate-formatters needed by the tests.
2160 // Returns true if and only if the argument is an even number.
2161 bool IsEven(int n) {
2162 return (n % 2) == 0;
2165 // A functor that returns true if and only if the argument is an even number.
2166 struct IsEvenFunctor {
2167 bool operator()(int n) { return IsEven(n); }
2170 // A predicate-formatter function that asserts the argument is an even
2172 AssertionResult AssertIsEven(const char* expr, int n) {
2174 return AssertionSuccess();
2178 msg << expr << " evaluates to " << n << ", which is not even.";
2179 return AssertionFailure(msg);
2182 // A predicate function that returns AssertionResult for use in
2183 // EXPECT/ASSERT_TRUE/FALSE.
2184 AssertionResult ResultIsEven(int n) {
2186 return AssertionSuccess() << n << " is even";
2188 return AssertionFailure() << n << " is odd";
2191 // A predicate function that returns AssertionResult but gives no
2192 // explanation why it succeeds. Needed for testing that
2193 // EXPECT/ASSERT_FALSE handles such functions correctly.
2194 AssertionResult ResultIsEvenNoExplanation(int n) {
2196 return AssertionSuccess();
2198 return AssertionFailure() << n << " is odd";
2201 // A predicate-formatter functor that asserts the argument is an even
2203 struct AssertIsEvenFunctor {
2204 AssertionResult operator()(const char* expr, int n) {
2205 return AssertIsEven(expr, n);
2209 // Returns true if and only if the sum of the arguments is an even number.
2210 bool SumIsEven2(int n1, int n2) {
2211 return IsEven(n1 + n2);
2214 // A functor that returns true if and only if the sum of the arguments is an
2216 struct SumIsEven3Functor {
2217 bool operator()(int n1, int n2, int n3) {
2218 return IsEven(n1 + n2 + n3);
2222 // A predicate-formatter function that asserts the sum of the
2223 // arguments is an even number.
2224 AssertionResult AssertSumIsEven4(
2225 const char* e1, const char* e2, const char* e3, const char* e4,
2226 int n1, int n2, int n3, int n4) {
2227 const int sum = n1 + n2 + n3 + n4;
2229 return AssertionSuccess();
2233 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2234 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2235 << ") evaluates to " << sum << ", which is not even.";
2236 return AssertionFailure(msg);
2239 // A predicate-formatter functor that asserts the sum of the arguments
2240 // is an even number.
2241 struct AssertSumIsEven5Functor {
2242 AssertionResult operator()(
2243 const char* e1, const char* e2, const char* e3, const char* e4,
2244 const char* e5, int n1, int n2, int n3, int n4, int n5) {
2245 const int sum = n1 + n2 + n3 + n4 + n5;
2247 return AssertionSuccess();
2251 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2253 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2254 << ") evaluates to " << sum << ", which is not even.";
2255 return AssertionFailure(msg);
2260 // Tests unary predicate assertions.
2262 // Tests unary predicate assertions that don't use a custom formatter.
2263 TEST(Pred1Test, WithoutFormat) {
2265 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2266 ASSERT_PRED1(IsEven, 4);
2269 EXPECT_NONFATAL_FAILURE({ // NOLINT
2270 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2271 }, "This failure is expected.");
2272 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2273 "evaluates to false");
2276 // Tests unary predicate assertions that use a custom formatter.
2277 TEST(Pred1Test, WithFormat) {
2279 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2280 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2281 << "This failure is UNEXPECTED!";
2285 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2286 "n evaluates to 5, which is not even.");
2287 EXPECT_FATAL_FAILURE({ // NOLINT
2288 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2289 }, "This failure is expected.");
2292 // Tests that unary predicate assertions evaluates their arguments
2294 TEST(Pred1Test, SingleEvaluationOnFailure) {
2297 EXPECT_PRED1(IsEven, n++);
2298 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2301 EXPECT_FATAL_FAILURE({ // NOLINT
2302 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2303 << "This failure is expected.";
2304 }, "This failure is expected.");
2305 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2309 // Tests predicate assertions whose arity is >= 2.
2311 // Tests predicate assertions that don't use a custom formatter.
2312 TEST(PredTest, WithoutFormat) {
2314 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2315 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2320 EXPECT_NONFATAL_FAILURE({ // NOLINT
2321 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2322 }, "This failure is expected.");
2323 EXPECT_FATAL_FAILURE({ // NOLINT
2324 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2325 }, "evaluates to false");
2328 // Tests predicate assertions that use a custom formatter.
2329 TEST(PredTest, WithFormat) {
2331 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2332 "This failure is UNEXPECTED!";
2333 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2340 EXPECT_NONFATAL_FAILURE({ // NOLINT
2341 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2342 }, "evaluates to 13, which is not even.");
2343 EXPECT_FATAL_FAILURE({ // NOLINT
2344 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2345 << "This failure is expected.";
2346 }, "This failure is expected.");
2349 // Tests that predicate assertions evaluates their arguments
2351 TEST(PredTest, SingleEvaluationOnFailure) {
2355 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2356 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2357 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2359 // Another success case.
2364 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2365 n1++, n2++, n3++, n4++, n5++)
2366 << "This failure is UNEXPECTED!";
2367 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2368 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2369 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2370 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2371 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2375 EXPECT_NONFATAL_FAILURE({ // NOLINT
2376 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2377 << "This failure is expected.";
2378 }, "This failure is expected.");
2379 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2380 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2381 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2383 // Another failure case.
2384 n1 = n2 = n3 = n4 = 0;
2385 EXPECT_NONFATAL_FAILURE({ // NOLINT
2386 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2387 }, "evaluates to 1, which is not even.");
2388 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2389 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2390 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2391 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2394 // Test predicate assertions for sets
2395 TEST(PredTest, ExpectPredEvalFailure) {
2396 std::set<int> set_a = {2, 1, 3, 4, 5};
2397 std::set<int> set_b = {0, 4, 8};
2398 const auto compare_sets = [] (std::set<int>, std::set<int>) { return false; };
2399 EXPECT_NONFATAL_FAILURE(
2400 EXPECT_PRED2(compare_sets, set_a, set_b),
2401 "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates "
2402 "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }");
2405 // Some helper functions for testing using overloaded/template
2406 // functions with ASSERT_PREDn and EXPECT_PREDn.
2408 bool IsPositive(double x) {
2412 template <typename T>
2413 bool IsNegative(T x) {
2417 template <typename T1, typename T2>
2418 bool GreaterThan(T1 x1, T2 x2) {
2422 // Tests that overloaded functions can be used in *_PRED* as long as
2423 // their types are explicitly specified.
2424 TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2425 // C++Builder requires C-style casts rather than static_cast.
2426 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2427 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
2430 // Tests that template functions can be used in *_PRED* as long as
2431 // their types are explicitly specified.
2432 TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2433 EXPECT_PRED1(IsNegative<int>, -5);
2434 // Makes sure that we can handle templates with more than one
2436 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2440 // Some helper functions for testing using overloaded/template
2441 // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2443 AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2444 return n > 0 ? AssertionSuccess() :
2445 AssertionFailure(Message() << "Failure");
2448 AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2449 return x > 0 ? AssertionSuccess() :
2450 AssertionFailure(Message() << "Failure");
2453 template <typename T>
2454 AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2455 return x < 0 ? AssertionSuccess() :
2456 AssertionFailure(Message() << "Failure");
2459 template <typename T1, typename T2>
2460 AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2461 const T1& x1, const T2& x2) {
2462 return x1 == x2 ? AssertionSuccess() :
2463 AssertionFailure(Message() << "Failure");
2466 // Tests that overloaded functions can be used in *_PRED_FORMAT*
2467 // without explicitly specifying their types.
2468 TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2469 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2470 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2473 // Tests that template functions can be used in *_PRED_FORMAT* without
2474 // explicitly specifying their types.
2475 TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2476 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2477 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2481 // Tests string assertions.
2483 // Tests ASSERT_STREQ with non-NULL arguments.
2484 TEST(StringAssertionTest, ASSERT_STREQ) {
2485 const char * const p1 = "good";
2486 ASSERT_STREQ(p1, p1);
2488 // Let p2 have the same content as p1, but be at a different address.
2489 const char p2[] = "good";
2490 ASSERT_STREQ(p1, p2);
2492 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2493 " \"bad\"\n \"good\"");
2496 // Tests ASSERT_STREQ with NULL arguments.
2497 TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2498 ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr);
2499 EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null");
2502 // Tests ASSERT_STREQ with NULL arguments.
2503 TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2504 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null");
2507 // Tests ASSERT_STRNE.
2508 TEST(StringAssertionTest, ASSERT_STRNE) {
2509 ASSERT_STRNE("hi", "Hi");
2510 ASSERT_STRNE("Hi", nullptr);
2511 ASSERT_STRNE(nullptr, "Hi");
2512 ASSERT_STRNE("", nullptr);
2513 ASSERT_STRNE(nullptr, "");
2514 ASSERT_STRNE("", "Hi");
2515 ASSERT_STRNE("Hi", "");
2516 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2517 "\"Hi\" vs \"Hi\"");
2520 // Tests ASSERT_STRCASEEQ.
2521 TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2522 ASSERT_STRCASEEQ("hi", "Hi");
2523 ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);
2525 ASSERT_STRCASEEQ("", "");
2526 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2530 // Tests ASSERT_STRCASENE.
2531 TEST(StringAssertionTest, ASSERT_STRCASENE) {
2532 ASSERT_STRCASENE("hi1", "Hi2");
2533 ASSERT_STRCASENE("Hi", nullptr);
2534 ASSERT_STRCASENE(nullptr, "Hi");
2535 ASSERT_STRCASENE("", nullptr);
2536 ASSERT_STRCASENE(nullptr, "");
2537 ASSERT_STRCASENE("", "Hi");
2538 ASSERT_STRCASENE("Hi", "");
2539 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2543 // Tests *_STREQ on wide strings.
2544 TEST(StringAssertionTest, STREQ_Wide) {
2546 ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr);
2549 ASSERT_STREQ(L"", L"");
2551 // Non-null vs NULL.
2552 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null");
2555 EXPECT_STREQ(L"Hi", L"Hi");
2558 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2561 // Strings containing wide characters.
2562 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2565 // The streaming variation.
2566 EXPECT_NONFATAL_FAILURE({ // NOLINT
2567 EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
2568 }, "Expected failure");
2571 // Tests *_STRNE on wide strings.
2572 TEST(StringAssertionTest, STRNE_Wide) {
2574 EXPECT_NONFATAL_FAILURE(
2576 EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr);
2581 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2584 // Non-null vs NULL.
2585 ASSERT_STRNE(L"non-null", nullptr);
2588 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2592 EXPECT_STRNE(L"abc", L"Abc");
2594 // Strings containing wide characters.
2595 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2598 // The streaming variation.
2599 ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
2602 // Tests for ::testing::IsSubstring().
2604 // Tests that IsSubstring() returns the correct result when the input
2605 // argument type is const char*.
2606 TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2607 EXPECT_FALSE(IsSubstring("", "", nullptr, "a"));
2608 EXPECT_FALSE(IsSubstring("", "", "b", nullptr));
2609 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2611 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr));
2612 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2615 // Tests that IsSubstring() returns the correct result when the input
2616 // argument type is const wchar_t*.
2617 TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2618 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2619 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
2620 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2623 IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr));
2624 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2627 // Tests that IsSubstring() generates the correct message when the input
2628 // argument type is const char*.
2629 TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2630 EXPECT_STREQ("Value of: needle_expr\n"
2631 " Actual: \"needle\"\n"
2632 "Expected: a substring of haystack_expr\n"
2633 "Which is: \"haystack\"",
2634 IsSubstring("needle_expr", "haystack_expr",
2635 "needle", "haystack").failure_message());
2638 // Tests that IsSubstring returns the correct result when the input
2639 // argument type is ::std::string.
2640 TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2641 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2642 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2645 #if GTEST_HAS_STD_WSTRING
2646 // Tests that IsSubstring returns the correct result when the input
2647 // argument type is ::std::wstring.
2648 TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2649 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2650 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2653 // Tests that IsSubstring() generates the correct message when the input
2654 // argument type is ::std::wstring.
2655 TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2656 EXPECT_STREQ("Value of: needle_expr\n"
2657 " Actual: L\"needle\"\n"
2658 "Expected: a substring of haystack_expr\n"
2659 "Which is: L\"haystack\"",
2661 "needle_expr", "haystack_expr",
2662 ::std::wstring(L"needle"), L"haystack").failure_message());
2665 #endif // GTEST_HAS_STD_WSTRING
2667 // Tests for ::testing::IsNotSubstring().
2669 // Tests that IsNotSubstring() returns the correct result when the input
2670 // argument type is const char*.
2671 TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2672 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2673 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2676 // Tests that IsNotSubstring() returns the correct result when the input
2677 // argument type is const wchar_t*.
2678 TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2679 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2680 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2683 // Tests that IsNotSubstring() generates the correct message when the input
2684 // argument type is const wchar_t*.
2685 TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2686 EXPECT_STREQ("Value of: needle_expr\n"
2687 " Actual: L\"needle\"\n"
2688 "Expected: not a substring of haystack_expr\n"
2689 "Which is: L\"two needles\"",
2691 "needle_expr", "haystack_expr",
2692 L"needle", L"two needles").failure_message());
2695 // Tests that IsNotSubstring returns the correct result when the input
2696 // argument type is ::std::string.
2697 TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2698 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2699 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2702 // Tests that IsNotSubstring() generates the correct message when the input
2703 // argument type is ::std::string.
2704 TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2705 EXPECT_STREQ("Value of: needle_expr\n"
2706 " Actual: \"needle\"\n"
2707 "Expected: not a substring of haystack_expr\n"
2708 "Which is: \"two needles\"",
2710 "needle_expr", "haystack_expr",
2711 ::std::string("needle"), "two needles").failure_message());
2714 #if GTEST_HAS_STD_WSTRING
2716 // Tests that IsNotSubstring returns the correct result when the input
2717 // argument type is ::std::wstring.
2718 TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2720 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2721 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2724 #endif // GTEST_HAS_STD_WSTRING
2726 // Tests floating-point assertions.
2728 template <typename RawType>
2729 class FloatingPointTest : public Test {
2731 // Pre-calculated numbers to be used by the tests.
2733 RawType close_to_positive_zero;
2734 RawType close_to_negative_zero;
2735 RawType further_from_negative_zero;
2737 RawType close_to_one;
2738 RawType further_from_one;
2741 RawType close_to_infinity;
2742 RawType further_from_infinity;
2748 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2749 typedef typename Floating::Bits Bits;
2751 void SetUp() override {
2752 const uint32_t max_ulps = Floating::kMaxUlps;
2754 // The bits that represent 0.0.
2755 const Bits zero_bits = Floating(0).bits();
2757 // Makes some numbers close to 0.0.
2758 values_.close_to_positive_zero = Floating::ReinterpretBits(
2759 zero_bits + max_ulps/2);
2760 values_.close_to_negative_zero = -Floating::ReinterpretBits(
2761 zero_bits + max_ulps - max_ulps/2);
2762 values_.further_from_negative_zero = -Floating::ReinterpretBits(
2763 zero_bits + max_ulps + 1 - max_ulps/2);
2765 // The bits that represent 1.0.
2766 const Bits one_bits = Floating(1).bits();
2768 // Makes some numbers close to 1.0.
2769 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2770 values_.further_from_one = Floating::ReinterpretBits(
2771 one_bits + max_ulps + 1);
2774 values_.infinity = Floating::Infinity();
2776 // The bits that represent +infinity.
2777 const Bits infinity_bits = Floating(values_.infinity).bits();
2779 // Makes some numbers close to infinity.
2780 values_.close_to_infinity = Floating::ReinterpretBits(
2781 infinity_bits - max_ulps);
2782 values_.further_from_infinity = Floating::ReinterpretBits(
2783 infinity_bits - max_ulps - 1);
2785 // Makes some NAN's. Sets the most significant bit of the fraction so that
2786 // our NaN's are quiet; trying to process a signaling NaN would raise an
2787 // exception if our environment enables floating point exceptions.
2788 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2789 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2790 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2791 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
2795 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2798 static TestValues values_;
2801 template <typename RawType>
2802 typename FloatingPointTest<RawType>::TestValues
2803 FloatingPointTest<RawType>::values_;
2805 // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2806 typedef FloatingPointTest<float> FloatTest;
2808 // Tests that the size of Float::Bits matches the size of float.
2809 TEST_F(FloatTest, Size) {
2813 // Tests comparing with +0 and -0.
2814 TEST_F(FloatTest, Zeros) {
2815 EXPECT_FLOAT_EQ(0.0, -0.0);
2816 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2818 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2822 // Tests comparing numbers close to 0.
2824 // This ensures that *_FLOAT_EQ handles the sign correctly and no
2825 // overflow occurs when comparing numbers whose absolute value is very
2827 TEST_F(FloatTest, AlmostZeros) {
2828 // In C++Builder, names within local classes (such as used by
2829 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2830 // scoping class. Use a static local alias as a workaround.
2831 // We use the assignment syntax since some compilers, like Sun Studio,
2832 // don't allow initializing references using construction syntax
2834 static const FloatTest::TestValues& v = this->values_;
2836 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2837 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2838 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2840 EXPECT_FATAL_FAILURE({ // NOLINT
2841 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2842 v.further_from_negative_zero);
2843 }, "v.further_from_negative_zero");
2846 // Tests comparing numbers close to each other.
2847 TEST_F(FloatTest, SmallDiff) {
2848 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2849 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2850 "values_.further_from_one");
2853 // Tests comparing numbers far apart.
2854 TEST_F(FloatTest, LargeDiff) {
2855 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2859 // Tests comparing with infinity.
2861 // This ensures that no overflow occurs when comparing numbers whose
2862 // absolute value is very large.
2863 TEST_F(FloatTest, Infinity) {
2864 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2865 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
2866 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2867 "-values_.infinity");
2869 // This is interesting as the representations of infinity and nan1
2870 // are only 1 DLP apart.
2871 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2875 // Tests that comparing with NAN always returns false.
2876 TEST_F(FloatTest, NaN) {
2877 // In C++Builder, names within local classes (such as used by
2878 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2879 // scoping class. Use a static local alias as a workaround.
2880 // We use the assignment syntax since some compilers, like Sun Studio,
2881 // don't allow initializing references using construction syntax
2883 static const FloatTest::TestValues& v = this->values_;
2885 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2887 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2889 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2892 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2896 // Tests that *_FLOAT_EQ are reflexive.
2897 TEST_F(FloatTest, Reflexive) {
2898 EXPECT_FLOAT_EQ(0.0, 0.0);
2899 EXPECT_FLOAT_EQ(1.0, 1.0);
2900 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
2903 // Tests that *_FLOAT_EQ are commutative.
2904 TEST_F(FloatTest, Commutative) {
2905 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2906 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2908 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2909 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2913 // Tests EXPECT_NEAR.
2914 TEST_F(FloatTest, EXPECT_NEAR) {
2915 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2916 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2917 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
2918 "The difference between 1.0f and 1.5f is 0.5, "
2919 "which exceeds 0.25f");
2922 // Tests ASSERT_NEAR.
2923 TEST_F(FloatTest, ASSERT_NEAR) {
2924 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2925 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2926 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
2927 "The difference between 1.0f and 1.5f is 0.5, "
2928 "which exceeds 0.25f");
2931 // Tests the cases where FloatLE() should succeed.
2932 TEST_F(FloatTest, FloatLESucceeds) {
2933 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2934 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
2936 // or when val1 is greater than, but almost equals to, val2.
2937 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2940 // Tests the cases where FloatLE() should fail.
2941 TEST_F(FloatTest, FloatLEFails) {
2942 // When val1 is greater than val2 by a large margin,
2943 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2944 "(2.0f) <= (1.0f)");
2946 // or by a small yet non-negligible margin,
2947 EXPECT_NONFATAL_FAILURE({ // NOLINT
2948 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2949 }, "(values_.further_from_one) <= (1.0f)");
2951 EXPECT_NONFATAL_FAILURE({ // NOLINT
2952 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2953 }, "(values_.nan1) <= (values_.infinity)");
2954 EXPECT_NONFATAL_FAILURE({ // NOLINT
2955 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2956 }, "(-values_.infinity) <= (values_.nan1)");
2957 EXPECT_FATAL_FAILURE({ // NOLINT
2958 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2959 }, "(values_.nan1) <= (values_.nan1)");
2962 // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2963 typedef FloatingPointTest<double> DoubleTest;
2965 // Tests that the size of Double::Bits matches the size of double.
2966 TEST_F(DoubleTest, Size) {
2970 // Tests comparing with +0 and -0.
2971 TEST_F(DoubleTest, Zeros) {
2972 EXPECT_DOUBLE_EQ(0.0, -0.0);
2973 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2975 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2979 // Tests comparing numbers close to 0.
2981 // This ensures that *_DOUBLE_EQ handles the sign correctly and no
2982 // overflow occurs when comparing numbers whose absolute value is very
2984 TEST_F(DoubleTest, AlmostZeros) {
2985 // In C++Builder, names within local classes (such as used by
2986 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2987 // scoping class. Use a static local alias as a workaround.
2988 // We use the assignment syntax since some compilers, like Sun Studio,
2989 // don't allow initializing references using construction syntax
2991 static const DoubleTest::TestValues& v = this->values_;
2993 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2994 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2995 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2997 EXPECT_FATAL_FAILURE({ // NOLINT
2998 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2999 v.further_from_negative_zero);
3000 }, "v.further_from_negative_zero");
3003 // Tests comparing numbers close to each other.
3004 TEST_F(DoubleTest, SmallDiff) {
3005 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
3006 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
3007 "values_.further_from_one");
3010 // Tests comparing numbers far apart.
3011 TEST_F(DoubleTest, LargeDiff) {
3012 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
3016 // Tests comparing with infinity.
3018 // This ensures that no overflow occurs when comparing numbers whose
3019 // absolute value is very large.
3020 TEST_F(DoubleTest, Infinity) {
3021 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
3022 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
3023 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
3024 "-values_.infinity");
3026 // This is interesting as the representations of infinity_ and nan1_
3027 // are only 1 DLP apart.
3028 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
3032 // Tests that comparing with NAN always returns false.
3033 TEST_F(DoubleTest, NaN) {
3034 static const DoubleTest::TestValues& v = this->values_;
3036 // Nokia's STLport crashes if we try to output infinity or NaN.
3037 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
3039 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
3040 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3041 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
3045 // Tests that *_DOUBLE_EQ are reflexive.
3046 TEST_F(DoubleTest, Reflexive) {
3047 EXPECT_DOUBLE_EQ(0.0, 0.0);
3048 EXPECT_DOUBLE_EQ(1.0, 1.0);
3049 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
3052 // Tests that *_DOUBLE_EQ are commutative.
3053 TEST_F(DoubleTest, Commutative) {
3054 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3055 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
3057 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3058 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3062 // Tests EXPECT_NEAR.
3063 TEST_F(DoubleTest, EXPECT_NEAR) {
3064 EXPECT_NEAR(-1.0, -1.1, 0.2);
3065 EXPECT_NEAR(2.0, 3.0, 1.0);
3066 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3067 "The difference between 1.0 and 1.5 is 0.5, "
3068 "which exceeds 0.25");
3069 // At this magnitude adjacent doubles are 512.0 apart, so this triggers a
3070 // slightly different failure reporting path.
3071 EXPECT_NONFATAL_FAILURE(
3072 EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),
3073 "The abs_error parameter 1.0 evaluates to 1 which is smaller than the "
3074 "minimum distance between doubles for numbers of this magnitude which is "
3078 // Tests ASSERT_NEAR.
3079 TEST_F(DoubleTest, ASSERT_NEAR) {
3080 ASSERT_NEAR(-1.0, -1.1, 0.2);
3081 ASSERT_NEAR(2.0, 3.0, 1.0);
3082 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3083 "The difference between 1.0 and 1.5 is 0.5, "
3084 "which exceeds 0.25");
3087 // Tests the cases where DoubleLE() should succeed.
3088 TEST_F(DoubleTest, DoubleLESucceeds) {
3089 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3090 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
3092 // or when val1 is greater than, but almost equals to, val2.
3093 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3096 // Tests the cases where DoubleLE() should fail.
3097 TEST_F(DoubleTest, DoubleLEFails) {
3098 // When val1 is greater than val2 by a large margin,
3099 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
3102 // or by a small yet non-negligible margin,
3103 EXPECT_NONFATAL_FAILURE({ // NOLINT
3104 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3105 }, "(values_.further_from_one) <= (1.0)");
3107 EXPECT_NONFATAL_FAILURE({ // NOLINT
3108 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3109 }, "(values_.nan1) <= (values_.infinity)");
3110 EXPECT_NONFATAL_FAILURE({ // NOLINT
3111 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3112 }, " (-values_.infinity) <= (values_.nan1)");
3113 EXPECT_FATAL_FAILURE({ // NOLINT
3114 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3115 }, "(values_.nan1) <= (values_.nan1)");
3119 // Verifies that a test or test case whose name starts with DISABLED_ is
3122 // A test whose name starts with DISABLED_.
3124 TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3125 FAIL() << "Unexpected failure: Disabled test should not be run.";
3128 // A test whose name does not start with DISABLED_.
3130 TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3134 // A test case whose name starts with DISABLED_.
3136 TEST(DISABLED_TestSuite, TestShouldNotRun) {
3137 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3140 // A test case and test whose names start with DISABLED_.
3142 TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {
3143 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3146 // Check that when all tests in a test case are disabled, SetUpTestSuite() and
3147 // TearDownTestSuite() are not called.
3148 class DisabledTestsTest : public Test {
3150 static void SetUpTestSuite() {
3151 FAIL() << "Unexpected failure: All tests disabled in test case. "
3152 "SetUpTestSuite() should not be called.";
3155 static void TearDownTestSuite() {
3156 FAIL() << "Unexpected failure: All tests disabled in test case. "
3157 "TearDownTestSuite() should not be called.";
3161 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3162 FAIL() << "Unexpected failure: Disabled test should not be run.";
3165 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3166 FAIL() << "Unexpected failure: Disabled test should not be run.";
3169 // Tests that disabled typed tests aren't run.
3171 template <typename T>
3172 class TypedTest : public Test {
3175 typedef testing::Types<int, double> NumericTypes;
3176 TYPED_TEST_SUITE(TypedTest, NumericTypes);
3178 TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3179 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3182 template <typename T>
3183 class DISABLED_TypedTest : public Test {
3186 TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
3188 TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3189 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3192 // Tests that disabled type-parameterized tests aren't run.
3194 template <typename T>
3195 class TypedTestP : public Test {
3198 TYPED_TEST_SUITE_P(TypedTestP);
3200 TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3201 FAIL() << "Unexpected failure: "
3202 << "Disabled type-parameterized test should not run.";
3205 REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
3207 INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);
3209 template <typename T>
3210 class DISABLED_TypedTestP : public Test {
3213 TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
3215 TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3216 FAIL() << "Unexpected failure: "
3217 << "Disabled type-parameterized test should not run.";
3220 REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
3222 INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
3224 // Tests that assertion macros evaluate their arguments exactly once.
3226 class SingleEvaluationTest : public Test {
3227 public: // Must be public and not protected due to a bug in g++ 3.4.2.
3228 // This helper function is needed by the FailedASSERT_STREQ test
3229 // below. It's public to work around C++Builder's bug with scoping local
3231 static void CompareAndIncrementCharPtrs() {
3232 ASSERT_STREQ(p1_++, p2_++);
3235 // This helper function is needed by the FailedASSERT_NE test below. It's
3236 // public to work around C++Builder's bug with scoping local classes.
3237 static void CompareAndIncrementInts() {
3238 ASSERT_NE(a_++, b_++);
3242 SingleEvaluationTest() {
3249 static const char* const s1_;
3250 static const char* const s2_;
3251 static const char* p1_;
3252 static const char* p2_;
3258 const char* const SingleEvaluationTest::s1_ = "01234";
3259 const char* const SingleEvaluationTest::s2_ = "abcde";
3260 const char* SingleEvaluationTest::p1_;
3261 const char* SingleEvaluationTest::p2_;
3262 int SingleEvaluationTest::a_;
3263 int SingleEvaluationTest::b_;
3265 // Tests that when ASSERT_STREQ fails, it evaluates its arguments
3267 TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3268 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3270 EXPECT_EQ(s1_ + 1, p1_);
3271 EXPECT_EQ(s2_ + 1, p2_);
3274 // Tests that string assertion arguments are evaluated exactly once.
3275 TEST_F(SingleEvaluationTest, ASSERT_STR) {
3276 // successful EXPECT_STRNE
3277 EXPECT_STRNE(p1_++, p2_++);
3278 EXPECT_EQ(s1_ + 1, p1_);
3279 EXPECT_EQ(s2_ + 1, p2_);
3281 // failed EXPECT_STRCASEEQ
3282 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3284 EXPECT_EQ(s1_ + 2, p1_);
3285 EXPECT_EQ(s2_ + 2, p2_);
3288 // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3290 TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3291 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3292 "(a_++) != (b_++)");
3297 // Tests that assertion arguments are evaluated exactly once.
3298 TEST_F(SingleEvaluationTest, OtherCases) {
3299 // successful EXPECT_TRUE
3300 EXPECT_TRUE(0 == a_++); // NOLINT
3303 // failed EXPECT_TRUE
3304 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3307 // successful EXPECT_GT
3308 EXPECT_GT(a_++, b_++);
3313 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3317 // successful ASSERT_TRUE
3318 ASSERT_TRUE(0 < a_++); // NOLINT
3321 // successful ASSERT_GT
3322 ASSERT_GT(a_++, b_++);
3327 #if GTEST_HAS_EXCEPTIONS
3332 #define ERROR_DESC "class std::runtime_error"
3334 #define ERROR_DESC "std::runtime_error"
3337 #else // GTEST_HAS_RTTI
3339 #define ERROR_DESC "an std::exception-derived error"
3341 #endif // GTEST_HAS_RTTI
3343 void ThrowAnInteger() {
3346 void ThrowRuntimeError(const char* what) {
3347 throw std::runtime_error(what);
3350 // Tests that assertion arguments are evaluated exactly once.
3351 TEST_F(SingleEvaluationTest, ExceptionTests) {
3352 // successful EXPECT_THROW
3353 EXPECT_THROW({ // NOLINT
3359 // failed EXPECT_THROW, throws different
3360 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3363 }, bool), "throws a different type");
3366 // failed EXPECT_THROW, throws runtime error
3367 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3369 ThrowRuntimeError("A description");
3370 }, bool), "throws " ERROR_DESC " with description \"A description\"");
3373 // failed EXPECT_THROW, throws nothing
3374 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3377 // successful EXPECT_NO_THROW
3378 EXPECT_NO_THROW(a_++);
3381 // failed EXPECT_NO_THROW
3382 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3388 // successful EXPECT_ANY_THROW
3389 EXPECT_ANY_THROW({ // NOLINT
3395 // failed EXPECT_ANY_THROW
3396 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3400 #endif // GTEST_HAS_EXCEPTIONS
3402 // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3403 class NoFatalFailureTest : public Test {
3406 void FailsNonFatal() {
3407 ADD_FAILURE() << "some non-fatal failure";
3410 FAIL() << "some fatal failure";
3413 void DoAssertNoFatalFailureOnFails() {
3414 ASSERT_NO_FATAL_FAILURE(Fails());
3415 ADD_FAILURE() << "should not reach here.";
3418 void DoExpectNoFatalFailureOnFails() {
3419 EXPECT_NO_FATAL_FAILURE(Fails());
3420 ADD_FAILURE() << "other failure";
3424 TEST_F(NoFatalFailureTest, NoFailure) {
3425 EXPECT_NO_FATAL_FAILURE(Succeeds());
3426 ASSERT_NO_FATAL_FAILURE(Succeeds());
3429 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3430 EXPECT_NONFATAL_FAILURE(
3431 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3432 "some non-fatal failure");
3433 EXPECT_NONFATAL_FAILURE(
3434 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3435 "some non-fatal failure");
3438 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3439 TestPartResultArray gtest_failures;
3441 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3442 DoAssertNoFatalFailureOnFails();
3444 ASSERT_EQ(2, gtest_failures.size());
3445 EXPECT_EQ(TestPartResult::kFatalFailure,
3446 gtest_failures.GetTestPartResult(0).type());
3447 EXPECT_EQ(TestPartResult::kFatalFailure,
3448 gtest_failures.GetTestPartResult(1).type());
3449 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3450 gtest_failures.GetTestPartResult(0).message());
3451 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3452 gtest_failures.GetTestPartResult(1).message());
3455 TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3456 TestPartResultArray gtest_failures;
3458 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3459 DoExpectNoFatalFailureOnFails();
3461 ASSERT_EQ(3, gtest_failures.size());
3462 EXPECT_EQ(TestPartResult::kFatalFailure,
3463 gtest_failures.GetTestPartResult(0).type());
3464 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3465 gtest_failures.GetTestPartResult(1).type());
3466 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3467 gtest_failures.GetTestPartResult(2).type());
3468 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3469 gtest_failures.GetTestPartResult(0).message());
3470 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3471 gtest_failures.GetTestPartResult(1).message());
3472 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3473 gtest_failures.GetTestPartResult(2).message());
3476 TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3477 TestPartResultArray gtest_failures;
3479 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3480 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3482 ASSERT_EQ(2, gtest_failures.size());
3483 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3484 gtest_failures.GetTestPartResult(0).type());
3485 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3486 gtest_failures.GetTestPartResult(1).type());
3487 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3488 gtest_failures.GetTestPartResult(0).message());
3489 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3490 gtest_failures.GetTestPartResult(1).message());
3493 // Tests non-string assertions.
3495 std::string EditsToString(const std::vector<EditType>& edits) {
3497 for (size_t i = 0; i < edits.size(); ++i) {
3498 static const char kEdits[] = " +-/";
3499 out.append(1, kEdits[edits[i]]);
3504 std::vector<size_t> CharsToIndices(const std::string& str) {
3505 std::vector<size_t> out;
3506 for (size_t i = 0; i < str.size(); ++i) {
3507 out.push_back(static_cast<size_t>(str[i]));
3512 std::vector<std::string> CharsToLines(const std::string& str) {
3513 std::vector<std::string> out;
3514 for (size_t i = 0; i < str.size(); ++i) {
3515 out.push_back(str.substr(i, 1));
3520 TEST(EditDistance, TestSuites) {
3525 const char* expected_edits;
3526 const char* expected_diff;
3528 static const Case kCases[] = {
3530 {__LINE__, "A", "A", " ", ""},
3531 {__LINE__, "ABCDE", "ABCDE", " ", ""},
3533 {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
3534 {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
3536 {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
3537 {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
3539 {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
3540 {__LINE__, "ABCD", "abcd", "////",
3541 "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
3543 {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
3544 "@@ -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"},
3545 {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
3546 "@@ -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"},
3547 {__LINE__, "ABCDE", "BCDCD", "- +/",
3548 "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
3549 {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
3550 "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
3551 "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
3553 for (const Case* c = kCases; c->left; ++c) {
3554 EXPECT_TRUE(c->expected_edits ==
3555 EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3556 CharsToIndices(c->right))))
3557 << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
3558 << EditsToString(CalculateOptimalEdits(
3559 CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
3560 EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
3561 CharsToLines(c->right)))
3562 << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
3563 << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
3568 // Tests EqFailure(), used for implementing *EQ* assertions.
3569 TEST(AssertionTest, EqFailure) {
3570 const std::string foo_val("5"), bar_val("6");
3571 const std::string msg1(
3572 EqFailure("foo", "bar", foo_val, bar_val, false)
3573 .failure_message());
3575 "Expected equality of these values:\n"
3582 const std::string msg2(
3583 EqFailure("foo", "6", foo_val, bar_val, false)
3584 .failure_message());
3586 "Expected equality of these values:\n"
3592 const std::string msg3(
3593 EqFailure("5", "bar", foo_val, bar_val, false)
3594 .failure_message());
3596 "Expected equality of these values:\n"
3602 const std::string msg4(
3603 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3605 "Expected equality of these values:\n"
3610 const std::string msg5(
3611 EqFailure("foo", "bar",
3612 std::string("\"x\""), std::string("\"y\""),
3613 true).failure_message());
3615 "Expected equality of these values:\n"
3617 " Which is: \"x\"\n"
3619 " Which is: \"y\"\n"
3624 TEST(AssertionTest, EqFailureWithDiff) {
3625 const std::string left(
3626 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
3627 const std::string right(
3628 "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
3629 const std::string msg1(
3630 EqFailure("left", "right", left, right, false).failure_message());
3632 "Expected equality of these values:\n"
3635 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3637 " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3638 "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
3639 "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
3643 // Tests AppendUserMessage(), used for implementing the *EQ* macros.
3644 TEST(AssertionTest, AppendUserMessage) {
3645 const std::string foo("foo");
3649 AppendUserMessage(foo, msg).c_str());
3652 EXPECT_STREQ("foo\nbar",
3653 AppendUserMessage(foo, msg).c_str());
3657 // Silences warnings: "Condition is always true", "Unreachable code"
3658 # pragma option push -w-ccc -w-rch
3661 // Tests ASSERT_TRUE.
3662 TEST(AssertionTest, ASSERT_TRUE) {
3663 ASSERT_TRUE(2 > 1); // NOLINT
3664 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3668 // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3669 TEST(AssertionTest, AssertTrueWithAssertionResult) {
3670 ASSERT_TRUE(ResultIsEven(2));
3671 #ifndef __BORLANDC__
3672 // ICE's in C++Builder.
3673 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3674 "Value of: ResultIsEven(3)\n"
3675 " Actual: false (3 is odd)\n"
3678 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3679 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3680 "Value of: ResultIsEvenNoExplanation(3)\n"
3681 " Actual: false (3 is odd)\n"
3685 // Tests ASSERT_FALSE.
3686 TEST(AssertionTest, ASSERT_FALSE) {
3687 ASSERT_FALSE(2 < 1); // NOLINT
3688 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3694 // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3695 TEST(AssertionTest, AssertFalseWithAssertionResult) {
3696 ASSERT_FALSE(ResultIsEven(3));
3697 #ifndef __BORLANDC__
3698 // ICE's in C++Builder.
3699 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3700 "Value of: ResultIsEven(2)\n"
3701 " Actual: true (2 is even)\n"
3704 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3705 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3706 "Value of: ResultIsEvenNoExplanation(2)\n"
3712 // Restores warnings after previous "#pragma option push" suppressed them
3716 // Tests using ASSERT_EQ on double values. The purpose is to make
3717 // sure that the specialization we did for integer and anonymous enums
3718 // isn't used for double arguments.
3719 TEST(ExpectTest, ASSERT_EQ_Double) {
3721 ASSERT_EQ(5.6, 5.6);
3724 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3729 TEST(AssertionTest, ASSERT_EQ) {
3730 ASSERT_EQ(5, 2 + 3);
3731 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3732 "Expected equality of these values:\n"
3738 // Tests ASSERT_EQ(NULL, pointer).
3739 TEST(AssertionTest, ASSERT_EQ_NULL) {
3741 const char* p = nullptr;
3742 ASSERT_EQ(nullptr, p);
3746 EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:");
3749 // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3750 // treated as a null pointer by the compiler, we need to make sure
3751 // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3752 // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3753 TEST(ExpectTest, ASSERT_EQ_0) {
3760 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3765 TEST(AssertionTest, ASSERT_NE) {
3767 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3768 "Expected: ('a') != ('a'), "
3769 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3773 TEST(AssertionTest, ASSERT_LE) {
3776 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3777 "Expected: (2) <= (0), actual: 2 vs 0");
3781 TEST(AssertionTest, ASSERT_LT) {
3783 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3784 "Expected: (2) < (2), actual: 2 vs 2");
3788 TEST(AssertionTest, ASSERT_GE) {
3791 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3792 "Expected: (2) >= (3), actual: 2 vs 3");
3796 TEST(AssertionTest, ASSERT_GT) {
3798 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3799 "Expected: (2) > (2), actual: 2 vs 2");
3802 #if GTEST_HAS_EXCEPTIONS
3804 void ThrowNothing() {}
3806 // Tests ASSERT_THROW.
3807 TEST(AssertionTest, ASSERT_THROW) {
3808 ASSERT_THROW(ThrowAnInteger(), int);
3810 # ifndef __BORLANDC__
3812 // ICE's in C++Builder 2007 and 2009.
3813 EXPECT_FATAL_FAILURE(
3814 ASSERT_THROW(ThrowAnInteger(), bool),
3815 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3816 " Actual: it throws a different type.");
3817 EXPECT_FATAL_FAILURE(
3818 ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
3819 "Expected: ThrowRuntimeError(\"A description\") "
3820 "throws an exception of type std::logic_error.\n "
3821 "Actual: it throws " ERROR_DESC " "
3822 "with description \"A description\".");
3825 EXPECT_FATAL_FAILURE(
3826 ASSERT_THROW(ThrowNothing(), bool),
3827 "Expected: ThrowNothing() throws an exception of type bool.\n"
3828 " Actual: it throws nothing.");
3831 // Tests ASSERT_NO_THROW.
3832 TEST(AssertionTest, ASSERT_NO_THROW) {
3833 ASSERT_NO_THROW(ThrowNothing());
3834 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3835 "Expected: ThrowAnInteger() doesn't throw an exception."
3836 "\n Actual: it throws.");
3837 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
3838 "Expected: ThrowRuntimeError(\"A description\") "
3839 "doesn't throw an exception.\n "
3840 "Actual: it throws " ERROR_DESC " "
3841 "with description \"A description\".");
3844 // Tests ASSERT_ANY_THROW.
3845 TEST(AssertionTest, ASSERT_ANY_THROW) {
3846 ASSERT_ANY_THROW(ThrowAnInteger());
3847 EXPECT_FATAL_FAILURE(
3848 ASSERT_ANY_THROW(ThrowNothing()),
3849 "Expected: ThrowNothing() throws an exception.\n"
3850 " Actual: it doesn't.");
3853 #endif // GTEST_HAS_EXCEPTIONS
3855 // Makes sure we deal with the precedence of <<. This test should
3857 TEST(AssertionTest, AssertPrecedence) {
3858 ASSERT_EQ(1 < 2, true);
3859 bool false_value = false;
3860 ASSERT_EQ(true && false_value, false);
3863 // A subroutine used by the following test.
3864 void TestEq1(int x) {
3868 // Tests calling a test subroutine that's not part of a fixture.
3869 TEST(AssertionTest, NonFixtureSubroutine) {
3870 EXPECT_FATAL_FAILURE(TestEq1(2),
3871 " x\n Which is: 2");
3874 // An uncopyable class.
3877 explicit Uncopyable(int a_value) : value_(a_value) {}
3879 int value() const { return value_; }
3880 bool operator==(const Uncopyable& rhs) const {
3881 return value() == rhs.value();
3884 // This constructor deliberately has no implementation, as we don't
3885 // want this class to be copyable.
3886 Uncopyable(const Uncopyable&); // NOLINT
3891 ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3892 return os << value.value();
3896 bool IsPositiveUncopyable(const Uncopyable& x) {
3897 return x.value() > 0;
3900 // A subroutine used by the following test.
3901 void TestAssertNonPositive() {
3903 ASSERT_PRED1(IsPositiveUncopyable, y);
3905 // A subroutine used by the following test.
3906 void TestAssertEqualsUncopyable() {
3912 // Tests that uncopyable objects can be used in assertions.
3913 TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3915 ASSERT_PRED1(IsPositiveUncopyable, x);
3917 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3918 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3919 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3920 "Expected equality of these values:\n"
3921 " x\n Which is: 5\n y\n Which is: -1");
3924 // Tests that uncopyable objects can be used in expects.
3925 TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3927 EXPECT_PRED1(IsPositiveUncopyable, x);
3929 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3930 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3932 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3933 "Expected equality of these values:\n"
3934 " x\n Which is: 5\n y\n Which is: -1");
3942 TEST(AssertionTest, NamedEnum) {
3943 EXPECT_EQ(kE1, kE1);
3944 EXPECT_LT(kE1, kE2);
3945 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3946 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
3949 // Sun Studio and HP aCC2reject this code.
3950 #if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3952 // Tests using assertions with anonymous enums.
3958 // We want to test the case where the size of the anonymous enum is
3959 // larger than sizeof(int), to make sure our implementation of the
3960 // assertions doesn't truncate the enums. However, MSVC
3961 // (incorrectly) doesn't allow an enum value to exceed the range of
3962 // an int, so this has to be conditionally compiled.
3964 // On Linux, kCaseB and kCaseA have the same value when truncated to
3965 // int size. We want to test whether this will confuse the
3967 kCaseB = testing::internal::kMaxBiggestInt,
3973 # endif // GTEST_OS_LINUX
3978 TEST(AssertionTest, AnonymousEnum) {
3981 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
3983 # endif // GTEST_OS_LINUX
3985 EXPECT_EQ(kCaseA, kCaseA);
3986 EXPECT_NE(kCaseA, kCaseB);
3987 EXPECT_LT(kCaseA, kCaseB);
3988 EXPECT_LE(kCaseA, kCaseB);
3989 EXPECT_GT(kCaseB, kCaseA);
3990 EXPECT_GE(kCaseA, kCaseA);
3991 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
3992 "(kCaseA) >= (kCaseB)");
3993 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
3996 ASSERT_EQ(kCaseA, kCaseA);
3997 ASSERT_NE(kCaseA, kCaseB);
3998 ASSERT_LT(kCaseA, kCaseB);
3999 ASSERT_LE(kCaseA, kCaseB);
4000 ASSERT_GT(kCaseB, kCaseA);
4001 ASSERT_GE(kCaseA, kCaseA);
4003 # ifndef __BORLANDC__
4005 // ICE's in C++Builder.
4006 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
4007 " kCaseB\n Which is: ");
4008 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
4012 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
4016 #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
4018 #if GTEST_OS_WINDOWS
4020 static HRESULT UnexpectedHRESULTFailure() {
4021 return E_UNEXPECTED;
4024 static HRESULT OkHRESULTSuccess() {
4028 static HRESULT FalseHRESULTSuccess() {
4032 // HRESULT assertion tests test both zero and non-zero
4033 // success codes as well as failure message for each.
4035 // Windows CE doesn't support message texts.
4036 TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
4037 EXPECT_HRESULT_SUCCEEDED(S_OK);
4038 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
4040 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4041 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4042 " Actual: 0x8000FFFF");
4045 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
4046 ASSERT_HRESULT_SUCCEEDED(S_OK);
4047 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
4049 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4050 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4051 " Actual: 0x8000FFFF");
4054 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
4055 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
4057 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
4058 "Expected: (OkHRESULTSuccess()) fails.\n"
4060 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
4061 "Expected: (FalseHRESULTSuccess()) fails.\n"
4065 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4066 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
4068 # ifndef __BORLANDC__
4070 // ICE's in C++Builder 2007 and 2009.
4071 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4072 "Expected: (OkHRESULTSuccess()) fails.\n"
4076 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4077 "Expected: (FalseHRESULTSuccess()) fails.\n"
4081 // Tests that streaming to the HRESULT macros works.
4082 TEST(HRESULTAssertionTest, Streaming) {
4083 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4084 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4085 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4086 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4088 EXPECT_NONFATAL_FAILURE(
4089 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4090 "expected failure");
4092 # ifndef __BORLANDC__
4094 // ICE's in C++Builder 2007 and 2009.
4095 EXPECT_FATAL_FAILURE(
4096 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4097 "expected failure");
4100 EXPECT_NONFATAL_FAILURE(
4101 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4102 "expected failure");
4104 EXPECT_FATAL_FAILURE(
4105 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4106 "expected failure");
4109 #endif // GTEST_OS_WINDOWS
4111 // The following code intentionally tests a suboptimal syntax.
4113 #pragma GCC diagnostic push
4114 #pragma GCC diagnostic ignored "-Wdangling-else"
4115 #pragma GCC diagnostic ignored "-Wempty-body"
4116 #pragma GCC diagnostic ignored "-Wpragmas"
4118 // Tests that the assertion macros behave like single statements.
4119 TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4121 ASSERT_TRUE(false) << "This should never be executed; "
4122 "It's a compilation test only.";
4125 EXPECT_FALSE(false);
4135 EXPECT_GT(3, 2) << "";
4138 #pragma GCC diagnostic pop
4141 #if GTEST_HAS_EXCEPTIONS
4142 // Tests that the compiler will not complain about unreachable code in the
4143 // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4144 TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4147 EXPECT_THROW(throw 1, int);
4148 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4149 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4150 EXPECT_NO_THROW(n++);
4151 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4152 EXPECT_ANY_THROW(throw 1);
4153 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4156 TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
4157 EXPECT_THROW(throw std::exception(), std::exception);
4160 // The following code intentionally tests a suboptimal syntax.
4162 #pragma GCC diagnostic push
4163 #pragma GCC diagnostic ignored "-Wdangling-else"
4164 #pragma GCC diagnostic ignored "-Wempty-body"
4165 #pragma GCC diagnostic ignored "-Wpragmas"
4167 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4169 EXPECT_THROW(ThrowNothing(), bool);
4172 EXPECT_THROW(ThrowAnInteger(), int);
4177 EXPECT_NO_THROW(ThrowAnInteger());
4180 EXPECT_NO_THROW(ThrowNothing());
4185 EXPECT_ANY_THROW(ThrowNothing());
4188 EXPECT_ANY_THROW(ThrowAnInteger());
4193 #pragma GCC diagnostic pop
4196 #endif // GTEST_HAS_EXCEPTIONS
4198 // The following code intentionally tests a suboptimal syntax.
4200 #pragma GCC diagnostic push
4201 #pragma GCC diagnostic ignored "-Wdangling-else"
4202 #pragma GCC diagnostic ignored "-Wempty-body"
4203 #pragma GCC diagnostic ignored "-Wpragmas"
4205 TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4207 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4208 << "It's a compilation test only.";
4213 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4218 EXPECT_NO_FATAL_FAILURE(SUCCEED());
4225 ASSERT_NO_FATAL_FAILURE(SUCCEED());
4228 #pragma GCC diagnostic pop
4231 // Tests that the assertion macros work well with switch statements.
4232 TEST(AssertionSyntaxTest, WorksWithSwitch) {
4242 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4244 // Binary assertions are implemented using a different code path
4245 // than the Boolean assertions. Hence we test them separately.
4249 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4257 #if GTEST_HAS_EXCEPTIONS
4259 void ThrowAString() {
4260 throw "std::string";
4263 // Test that the exception assertion macros compile and work with const
4265 TEST(AssertionSyntaxTest, WorksWithConst) {
4266 ASSERT_THROW(ThrowAString(), const char*);
4268 EXPECT_THROW(ThrowAString(), const char*);
4271 #endif // GTEST_HAS_EXCEPTIONS
4277 // Tests that Google Test tracks SUCCEED*.
4278 TEST(SuccessfulAssertionTest, SUCCEED) {
4281 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4284 // Tests that Google Test doesn't track successful EXPECT_*.
4285 TEST(SuccessfulAssertionTest, EXPECT) {
4287 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4290 // Tests that Google Test doesn't track successful EXPECT_STR*.
4291 TEST(SuccessfulAssertionTest, EXPECT_STR) {
4292 EXPECT_STREQ("", "");
4293 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4296 // Tests that Google Test doesn't track successful ASSERT_*.
4297 TEST(SuccessfulAssertionTest, ASSERT) {
4299 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4302 // Tests that Google Test doesn't track successful ASSERT_STR*.
4303 TEST(SuccessfulAssertionTest, ASSERT_STR) {
4304 ASSERT_STREQ("", "");
4305 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4308 } // namespace testing
4312 // Tests the message streaming variation of assertions.
4314 TEST(AssertionWithMessageTest, EXPECT) {
4315 EXPECT_EQ(1, 1) << "This should succeed.";
4316 EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4317 "Expected failure #1");
4318 EXPECT_LE(1, 2) << "This should succeed.";
4319 EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4320 "Expected failure #2.");
4321 EXPECT_GE(1, 0) << "This should succeed.";
4322 EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4323 "Expected failure #3.");
4325 EXPECT_STREQ("1", "1") << "This should succeed.";
4326 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4327 "Expected failure #4.");
4328 EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4329 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4330 "Expected failure #5.");
4332 EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4333 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4334 "Expected failure #6.");
4335 EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4338 TEST(AssertionWithMessageTest, ASSERT) {
4339 ASSERT_EQ(1, 1) << "This should succeed.";
4340 ASSERT_NE(1, 2) << "This should succeed.";
4341 ASSERT_LE(1, 2) << "This should succeed.";
4342 ASSERT_LT(1, 2) << "This should succeed.";
4343 ASSERT_GE(1, 0) << "This should succeed.";
4344 EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4345 "Expected failure.");
4348 TEST(AssertionWithMessageTest, ASSERT_STR) {
4349 ASSERT_STREQ("1", "1") << "This should succeed.";
4350 ASSERT_STRNE("1", "2") << "This should succeed.";
4351 ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4352 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4353 "Expected failure.");
4356 TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4357 ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4358 ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4359 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT
4363 // Tests using ASSERT_FALSE with a streamed message.
4364 TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4365 ASSERT_FALSE(false) << "This shouldn't fail.";
4366 EXPECT_FATAL_FAILURE({ // NOLINT
4367 ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4368 << " evaluates to " << true;
4369 }, "Expected failure");
4372 // Tests using FAIL with a streamed message.
4373 TEST(AssertionWithMessageTest, FAIL) {
4374 EXPECT_FATAL_FAILURE(FAIL() << 0,
4378 // Tests using SUCCEED with a streamed message.
4379 TEST(AssertionWithMessageTest, SUCCEED) {
4380 SUCCEED() << "Success == " << 1;
4383 // Tests using ASSERT_TRUE with a streamed message.
4384 TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4385 ASSERT_TRUE(true) << "This should succeed.";
4386 ASSERT_TRUE(true) << true;
4387 EXPECT_FATAL_FAILURE(
4389 ASSERT_TRUE(false) << static_cast<const char*>(nullptr)
4390 << static_cast<char*>(nullptr);
4395 #if GTEST_OS_WINDOWS
4396 // Tests using wide strings in assertion messages.
4397 TEST(AssertionWithMessageTest, WideStringMessage) {
4398 EXPECT_NONFATAL_FAILURE({ // NOLINT
4399 EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4400 }, "This failure is expected.");
4401 EXPECT_FATAL_FAILURE({ // NOLINT
4402 ASSERT_EQ(1, 2) << "This failure is "
4403 << L"expected too.\x8120";
4404 }, "This failure is expected too.");
4406 #endif // GTEST_OS_WINDOWS
4408 // Tests EXPECT_TRUE.
4409 TEST(ExpectTest, EXPECT_TRUE) {
4410 EXPECT_TRUE(true) << "Intentional success";
4411 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4412 "Intentional failure #1.");
4413 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4414 "Intentional failure #2.");
4415 EXPECT_TRUE(2 > 1); // NOLINT
4416 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4420 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4424 // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4425 TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4426 EXPECT_TRUE(ResultIsEven(2));
4427 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4428 "Value of: ResultIsEven(3)\n"
4429 " Actual: false (3 is odd)\n"
4431 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4432 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4433 "Value of: ResultIsEvenNoExplanation(3)\n"
4434 " Actual: false (3 is odd)\n"
4438 // Tests EXPECT_FALSE with a streamed message.
4439 TEST(ExpectTest, EXPECT_FALSE) {
4440 EXPECT_FALSE(2 < 1); // NOLINT
4441 EXPECT_FALSE(false) << "Intentional success";
4442 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4443 "Intentional failure #1.");
4444 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4445 "Intentional failure #2.");
4446 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4450 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4454 // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4455 TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4456 EXPECT_FALSE(ResultIsEven(3));
4457 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4458 "Value of: ResultIsEven(2)\n"
4459 " Actual: true (2 is even)\n"
4461 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4462 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4463 "Value of: ResultIsEvenNoExplanation(2)\n"
4469 // Restores warnings after previous "#pragma option push" suppressed them
4474 TEST(ExpectTest, EXPECT_EQ) {
4475 EXPECT_EQ(5, 2 + 3);
4476 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4477 "Expected equality of these values:\n"
4481 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4485 // Tests using EXPECT_EQ on double values. The purpose is to make
4486 // sure that the specialization we did for integer and anonymous enums
4487 // isn't used for double arguments.
4488 TEST(ExpectTest, EXPECT_EQ_Double) {
4490 EXPECT_EQ(5.6, 5.6);
4493 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4497 // Tests EXPECT_EQ(NULL, pointer).
4498 TEST(ExpectTest, EXPECT_EQ_NULL) {
4500 const char* p = nullptr;
4501 EXPECT_EQ(nullptr, p);
4505 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:");
4508 // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4509 // treated as a null pointer by the compiler, we need to make sure
4510 // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4511 // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4512 TEST(ExpectTest, EXPECT_EQ_0) {
4519 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4524 TEST(ExpectTest, EXPECT_NE) {
4527 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4528 "Expected: ('a') != ('a'), "
4529 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4530 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4532 char* const p0 = nullptr;
4533 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4535 // Only way to get the Nokia compiler to compile the cast
4536 // is to have a separate void* variable first. Putting
4537 // the two casts on the same line doesn't work, neither does
4538 // a direct C-style to char*.
4539 void* pv1 = (void*)0x1234; // NOLINT
4540 char* const p1 = reinterpret_cast<char*>(pv1);
4541 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4546 TEST(ExpectTest, EXPECT_LE) {
4549 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4550 "Expected: (2) <= (0), actual: 2 vs 0");
4551 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4556 TEST(ExpectTest, EXPECT_LT) {
4558 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4559 "Expected: (2) < (2), actual: 2 vs 2");
4560 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4565 TEST(ExpectTest, EXPECT_GE) {
4568 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4569 "Expected: (2) >= (3), actual: 2 vs 3");
4570 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4575 TEST(ExpectTest, EXPECT_GT) {
4577 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4578 "Expected: (2) > (2), actual: 2 vs 2");
4579 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4583 #if GTEST_HAS_EXCEPTIONS
4585 // Tests EXPECT_THROW.
4586 TEST(ExpectTest, EXPECT_THROW) {
4587 EXPECT_THROW(ThrowAnInteger(), int);
4588 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4589 "Expected: ThrowAnInteger() throws an exception of "
4590 "type bool.\n Actual: it throws a different type.");
4591 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"),
4593 "Expected: ThrowRuntimeError(\"A description\") "
4594 "throws an exception of type std::logic_error.\n "
4595 "Actual: it throws " ERROR_DESC " "
4596 "with description \"A description\".");
4597 EXPECT_NONFATAL_FAILURE(
4598 EXPECT_THROW(ThrowNothing(), bool),
4599 "Expected: ThrowNothing() throws an exception of type bool.\n"
4600 " Actual: it throws nothing.");
4603 // Tests EXPECT_NO_THROW.
4604 TEST(ExpectTest, EXPECT_NO_THROW) {
4605 EXPECT_NO_THROW(ThrowNothing());
4606 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4607 "Expected: ThrowAnInteger() doesn't throw an "
4608 "exception.\n Actual: it throws.");
4609 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
4610 "Expected: ThrowRuntimeError(\"A description\") "
4611 "doesn't throw an exception.\n "
4612 "Actual: it throws " ERROR_DESC " "
4613 "with description \"A description\".");
4616 // Tests EXPECT_ANY_THROW.
4617 TEST(ExpectTest, EXPECT_ANY_THROW) {
4618 EXPECT_ANY_THROW(ThrowAnInteger());
4619 EXPECT_NONFATAL_FAILURE(
4620 EXPECT_ANY_THROW(ThrowNothing()),
4621 "Expected: ThrowNothing() throws an exception.\n"
4622 " Actual: it doesn't.");
4625 #endif // GTEST_HAS_EXCEPTIONS
4627 // Make sure we deal with the precedence of <<.
4628 TEST(ExpectTest, ExpectPrecedence) {
4629 EXPECT_EQ(1 < 2, true);
4630 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4631 " true && false\n Which is: false");
4635 // Tests the StreamableToString() function.
4637 // Tests using StreamableToString() on a scalar.
4638 TEST(StreamableToStringTest, Scalar) {
4639 EXPECT_STREQ("5", StreamableToString(5).c_str());
4642 // Tests using StreamableToString() on a non-char pointer.
4643 TEST(StreamableToStringTest, Pointer) {
4646 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4649 // Tests using StreamableToString() on a NULL non-char pointer.
4650 TEST(StreamableToStringTest, NullPointer) {
4652 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4655 // Tests using StreamableToString() on a C string.
4656 TEST(StreamableToStringTest, CString) {
4657 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4660 // Tests using StreamableToString() on a NULL C string.
4661 TEST(StreamableToStringTest, NullCString) {
4663 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4666 // Tests using streamable values as assertion messages.
4668 // Tests using std::string as an assertion message.
4669 TEST(StreamableTest, string) {
4670 static const std::string str(
4671 "This failure message is a std::string, and is expected.");
4672 EXPECT_FATAL_FAILURE(FAIL() << str,
4676 // Tests that we can output strings containing embedded NULs.
4677 // Limited to Linux because we can only do this with std::string's.
4678 TEST(StreamableTest, stringWithEmbeddedNUL) {
4679 static const char char_array_with_nul[] =
4680 "Here's a NUL\0 and some more string";
4681 static const std::string string_with_nul(char_array_with_nul,
4682 sizeof(char_array_with_nul)
4683 - 1); // drops the trailing NUL
4684 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4685 "Here's a NUL\\0 and some more string");
4688 // Tests that we can output a NUL char.
4689 TEST(StreamableTest, NULChar) {
4690 EXPECT_FATAL_FAILURE({ // NOLINT
4691 FAIL() << "A NUL" << '\0' << " and some more string";
4692 }, "A NUL\\0 and some more string");
4695 // Tests using int as an assertion message.
4696 TEST(StreamableTest, int) {
4697 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4701 // Tests using NULL char pointer as an assertion message.
4703 // In MSVC, streaming a NULL char * causes access violation. Google Test
4704 // implemented a workaround (substituting "(null)" for NULL). This
4705 // tests whether the workaround works.
4706 TEST(StreamableTest, NullCharPtr) {
4707 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)");
4710 // Tests that basic IO manipulators (endl, ends, and flush) can be
4711 // streamed to testing::Message.
4712 TEST(StreamableTest, BasicIoManip) {
4713 EXPECT_FATAL_FAILURE({ // NOLINT
4714 FAIL() << "Line 1." << std::endl
4715 << "A NUL char " << std::ends << std::flush << " in line 2.";
4716 }, "Line 1.\nA NUL char \\0 in line 2.");
4719 // Tests the macros that haven't been covered so far.
4721 void AddFailureHelper(bool* aborted) {
4723 ADD_FAILURE() << "Intentional failure.";
4727 // Tests ADD_FAILURE.
4728 TEST(MacroTest, ADD_FAILURE) {
4729 bool aborted = true;
4730 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4731 "Intentional failure.");
4732 EXPECT_FALSE(aborted);
4735 // Tests ADD_FAILURE_AT.
4736 TEST(MacroTest, ADD_FAILURE_AT) {
4737 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4738 // the failure message contains the user-streamed part.
4739 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4741 // Verifies that the user-streamed part is optional.
4742 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4744 // Unfortunately, we cannot verify that the failure message contains
4745 // the right file path and line number the same way, as
4746 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4747 // line number. Instead, we do that in googletest-output-test_.cc.
4751 TEST(MacroTest, FAIL) {
4752 EXPECT_FATAL_FAILURE(FAIL(),
4754 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4755 "Intentional failure.");
4758 // Tests GTEST_FAIL_AT.
4759 TEST(MacroTest, GTEST_FAIL_AT) {
4760 // Verifies that GTEST_FAIL_AT does generate a fatal failure and
4761 // the failure message contains the user-streamed part.
4762 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4764 // Verifies that the user-streamed part is optional.
4765 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed");
4767 // See the ADD_FAIL_AT test above to see how we test that the failure message
4768 // contains the right filename and line number -- the same applies here.
4772 TEST(MacroTest, SUCCEED) {
4774 SUCCEED() << "Explicit success.";
4777 // Tests for EXPECT_EQ() and ASSERT_EQ().
4779 // These tests fail *intentionally*, s.t. the failure messages can be
4780 // generated and tested.
4782 // We have different tests for different argument types.
4784 // Tests using bool values in {EXPECT|ASSERT}_EQ.
4785 TEST(EqAssertionTest, Bool) {
4786 EXPECT_EQ(true, true);
4787 EXPECT_FATAL_FAILURE({
4788 bool false_value = false;
4789 ASSERT_EQ(false_value, true);
4790 }, " false_value\n Which is: false\n true");
4793 // Tests using int values in {EXPECT|ASSERT}_EQ.
4794 TEST(EqAssertionTest, Int) {
4796 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4800 // Tests using time_t values in {EXPECT|ASSERT}_EQ.
4801 TEST(EqAssertionTest, Time_T) {
4802 EXPECT_EQ(static_cast<time_t>(0),
4803 static_cast<time_t>(0));
4804 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4805 static_cast<time_t>(1234)),
4809 // Tests using char values in {EXPECT|ASSERT}_EQ.
4810 TEST(EqAssertionTest, Char) {
4811 ASSERT_EQ('z', 'z');
4812 const char ch = 'b';
4813 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4814 " ch\n Which is: 'b'");
4815 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4816 " ch\n Which is: 'b'");
4819 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4820 TEST(EqAssertionTest, WideChar) {
4821 EXPECT_EQ(L'b', L'b');
4823 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4824 "Expected equality of these values:\n"
4826 " Which is: L'\0' (0, 0x0)\n"
4828 " Which is: L'x' (120, 0x78)");
4830 static wchar_t wchar;
4832 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4835 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
4836 " wchar\n Which is: L'");
4839 // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4840 TEST(EqAssertionTest, StdString) {
4841 // Compares a const char* to an std::string that has identical
4843 ASSERT_EQ("Test", ::std::string("Test"));
4845 // Compares two identical std::strings.
4846 static const ::std::string str1("A * in the middle");
4847 static const ::std::string str2(str1);
4848 EXPECT_EQ(str1, str2);
4850 // Compares a const char* to an std::string that has different
4852 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4855 // Compares an std::string to a char* that has different content.
4856 char* const p1 = const_cast<char*>("foo");
4857 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4860 // Compares two std::strings that have different contents, one of
4861 // which having a NUL character in the middle. This should fail.
4862 static ::std::string str3(str1);
4864 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4865 " str3\n Which is: \"A \\0 in the middle\"");
4868 #if GTEST_HAS_STD_WSTRING
4870 // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4871 TEST(EqAssertionTest, StdWideString) {
4872 // Compares two identical std::wstrings.
4873 const ::std::wstring wstr1(L"A * in the middle");
4874 const ::std::wstring wstr2(wstr1);
4875 ASSERT_EQ(wstr1, wstr2);
4877 // Compares an std::wstring to a const wchar_t* that has identical
4879 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4880 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4882 // Compares an std::wstring to a const wchar_t* that has different
4884 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4885 EXPECT_NONFATAL_FAILURE({ // NOLINT
4886 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4889 // Compares two std::wstrings that have different contents, one of
4890 // which having a NUL character in the middle.
4891 ::std::wstring wstr3(wstr1);
4892 wstr3.at(2) = L'\0';
4893 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4896 // Compares a wchar_t* to an std::wstring that has different
4898 EXPECT_FATAL_FAILURE({ // NOLINT
4899 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4903 #endif // GTEST_HAS_STD_WSTRING
4905 // Tests using char pointers in {EXPECT|ASSERT}_EQ.
4906 TEST(EqAssertionTest, CharPointer) {
4907 char* const p0 = nullptr;
4908 // Only way to get the Nokia compiler to compile the cast
4909 // is to have a separate void* variable first. Putting
4910 // the two casts on the same line doesn't work, neither does
4911 // a direct C-style to char*.
4912 void* pv1 = (void*)0x1234; // NOLINT
4913 void* pv2 = (void*)0xABC0; // NOLINT
4914 char* const p1 = reinterpret_cast<char*>(pv1);
4915 char* const p2 = reinterpret_cast<char*>(pv2);
4918 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4920 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4922 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4923 reinterpret_cast<char*>(0xABC0)),
4927 // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4928 TEST(EqAssertionTest, WideCharPointer) {
4929 wchar_t* const p0 = nullptr;
4930 // Only way to get the Nokia compiler to compile the cast
4931 // is to have a separate void* variable first. Putting
4932 // the two casts on the same line doesn't work, neither does
4933 // a direct C-style to char*.
4934 void* pv1 = (void*)0x1234; // NOLINT
4935 void* pv2 = (void*)0xABC0; // NOLINT
4936 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4937 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4940 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4942 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4944 void* pv3 = (void*)0x1234; // NOLINT
4945 void* pv4 = (void*)0xABC0; // NOLINT
4946 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4947 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4948 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4952 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4953 TEST(EqAssertionTest, OtherPointer) {
4954 ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));
4955 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),
4956 reinterpret_cast<const int*>(0x1234)),
4960 // A class that supports binary comparison operators but not streaming.
4961 class UnprintableChar {
4963 explicit UnprintableChar(char ch) : char_(ch) {}
4965 bool operator==(const UnprintableChar& rhs) const {
4966 return char_ == rhs.char_;
4968 bool operator!=(const UnprintableChar& rhs) const {
4969 return char_ != rhs.char_;
4971 bool operator<(const UnprintableChar& rhs) const {
4972 return char_ < rhs.char_;
4974 bool operator<=(const UnprintableChar& rhs) const {
4975 return char_ <= rhs.char_;
4977 bool operator>(const UnprintableChar& rhs) const {
4978 return char_ > rhs.char_;
4980 bool operator>=(const UnprintableChar& rhs) const {
4981 return char_ >= rhs.char_;
4988 // Tests that ASSERT_EQ() and friends don't require the arguments to
4990 TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4991 const UnprintableChar x('x'), y('y');
4999 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
5000 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
5001 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
5002 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
5003 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
5005 // Code tested by EXPECT_FATAL_FAILURE cannot reference local
5006 // variables, so we have to write UnprintableChar('x') instead of x.
5007 #ifndef __BORLANDC__
5008 // ICE's in C++Builder.
5009 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
5010 "1-byte object <78>");
5011 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
5012 "1-byte object <78>");
5014 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
5015 "1-byte object <79>");
5016 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
5017 "1-byte object <78>");
5018 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
5019 "1-byte object <79>");
5022 // Tests the FRIEND_TEST macro.
5024 // This class has a private member we want to test. We will test it
5025 // both in a TEST and in a TEST_F.
5031 int Bar() const { return 1; }
5033 // Declares the friend tests that can access the private member
5035 FRIEND_TEST(FRIEND_TEST_Test, TEST);
5036 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
5039 // Tests that the FRIEND_TEST declaration allows a TEST to access a
5040 // class's private members. This should compile.
5041 TEST(FRIEND_TEST_Test, TEST) {
5042 ASSERT_EQ(1, Foo().Bar());
5045 // The fixture needed to test using FRIEND_TEST with TEST_F.
5046 class FRIEND_TEST_Test2 : public Test {
5051 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
5052 // class's private members. This should compile.
5053 TEST_F(FRIEND_TEST_Test2, TEST_F) {
5054 ASSERT_EQ(1, foo.Bar());
5057 // Tests the life cycle of Test objects.
5059 // The test fixture for testing the life cycle of Test objects.
5061 // This class counts the number of live test objects that uses this
5063 class TestLifeCycleTest : public Test {
5065 // Constructor. Increments the number of test objects that uses
5067 TestLifeCycleTest() { count_++; }
5069 // Destructor. Decrements the number of test objects that uses this
5071 ~TestLifeCycleTest() override { count_--; }
5073 // Returns the number of live test objects that uses this fixture.
5074 int count() const { return count_; }
5080 int TestLifeCycleTest::count_ = 0;
5082 // Tests the life cycle of test objects.
5083 TEST_F(TestLifeCycleTest, Test1) {
5084 // There should be only one test object in this test case that's
5086 ASSERT_EQ(1, count());
5089 // Tests the life cycle of test objects.
5090 TEST_F(TestLifeCycleTest, Test2) {
5091 // After Test1 is done and Test2 is started, there should still be
5092 // only one live test object, as the object for Test1 should've been
5094 ASSERT_EQ(1, count());
5099 // Tests that the copy constructor works when it is NOT optimized away by
5101 TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5102 // Checks that the copy constructor doesn't try to dereference NULL pointers
5103 // in the source object.
5104 AssertionResult r1 = AssertionSuccess();
5105 AssertionResult r2 = r1;
5106 // The following line is added to prevent the compiler from optimizing
5107 // away the constructor call.
5110 AssertionResult r3 = r1;
5111 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
5112 EXPECT_STREQ("abc", r1.message());
5115 // Tests that AssertionSuccess and AssertionFailure construct
5116 // AssertionResult objects as expected.
5117 TEST(AssertionResultTest, ConstructionWorks) {
5118 AssertionResult r1 = AssertionSuccess();
5120 EXPECT_STREQ("", r1.message());
5122 AssertionResult r2 = AssertionSuccess() << "abc";
5124 EXPECT_STREQ("abc", r2.message());
5126 AssertionResult r3 = AssertionFailure();
5128 EXPECT_STREQ("", r3.message());
5130 AssertionResult r4 = AssertionFailure() << "def";
5132 EXPECT_STREQ("def", r4.message());
5134 AssertionResult r5 = AssertionFailure(Message() << "ghi");
5136 EXPECT_STREQ("ghi", r5.message());
5139 // Tests that the negation flips the predicate result but keeps the message.
5140 TEST(AssertionResultTest, NegationWorks) {
5141 AssertionResult r1 = AssertionSuccess() << "abc";
5143 EXPECT_STREQ("abc", (!r1).message());
5145 AssertionResult r2 = AssertionFailure() << "def";
5147 EXPECT_STREQ("def", (!r2).message());
5150 TEST(AssertionResultTest, StreamingWorks) {
5151 AssertionResult r = AssertionSuccess();
5152 r << "abc" << 'd' << 0 << true;
5153 EXPECT_STREQ("abcd0true", r.message());
5156 TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5157 AssertionResult r = AssertionSuccess();
5158 r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5159 EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5162 // The next test uses explicit conversion operators
5164 TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5165 struct ExplicitlyConvertibleToBool {
5166 explicit operator bool() const { return value; }
5169 ExplicitlyConvertibleToBool v1 = {false};
5170 ExplicitlyConvertibleToBool v2 = {true};
5175 struct ConvertibleToAssertionResult {
5176 operator AssertionResult() const { return AssertionResult(true); }
5179 TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5180 ConvertibleToAssertionResult obj;
5184 // Tests streaming a user type whose definition and operator << are
5185 // both in the global namespace.
5188 explicit Base(int an_x) : x_(an_x) {}
5189 int x() const { return x_; }
5193 std::ostream& operator<<(std::ostream& os,
5195 return os << val.x();
5197 std::ostream& operator<<(std::ostream& os,
5198 const Base* pointer) {
5199 return os << "(" << pointer->x() << ")";
5202 TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5206 msg << a << &a; // Uses ::operator<<.
5207 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5210 // Tests streaming a user type whose definition and operator<< are
5211 // both in an unnamed namespace.
5213 class MyTypeInUnnamedNameSpace : public Base {
5215 explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
5217 std::ostream& operator<<(std::ostream& os,
5218 const MyTypeInUnnamedNameSpace& val) {
5219 return os << val.x();
5221 std::ostream& operator<<(std::ostream& os,
5222 const MyTypeInUnnamedNameSpace* pointer) {
5223 return os << "(" << pointer->x() << ")";
5227 TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5229 MyTypeInUnnamedNameSpace a(1);
5231 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
5232 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5235 // Tests streaming a user type whose definition and operator<< are
5236 // both in a user namespace.
5237 namespace namespace1 {
5238 class MyTypeInNameSpace1 : public Base {
5240 explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
5242 std::ostream& operator<<(std::ostream& os,
5243 const MyTypeInNameSpace1& val) {
5244 return os << val.x();
5246 std::ostream& operator<<(std::ostream& os,
5247 const MyTypeInNameSpace1* pointer) {
5248 return os << "(" << pointer->x() << ")";
5250 } // namespace namespace1
5252 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5254 namespace1::MyTypeInNameSpace1 a(1);
5256 msg << a << &a; // Uses namespace1::operator<<.
5257 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5260 // Tests streaming a user type whose definition is in a user namespace
5261 // but whose operator<< is in the global namespace.
5262 namespace namespace2 {
5263 class MyTypeInNameSpace2 : public ::Base {
5265 explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
5267 } // namespace namespace2
5268 std::ostream& operator<<(std::ostream& os,
5269 const namespace2::MyTypeInNameSpace2& val) {
5270 return os << val.x();
5272 std::ostream& operator<<(std::ostream& os,
5273 const namespace2::MyTypeInNameSpace2* pointer) {
5274 return os << "(" << pointer->x() << ")";
5277 TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5279 namespace2::MyTypeInNameSpace2 a(1);
5281 msg << a << &a; // Uses ::operator<<.
5282 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5285 // Tests streaming NULL pointers to testing::Message.
5286 TEST(MessageTest, NullPointers) {
5288 char* const p1 = nullptr;
5289 unsigned char* const p2 = nullptr;
5291 double* p4 = nullptr;
5293 Message* p6 = nullptr;
5295 msg << p1 << p2 << p3 << p4 << p5 << p6;
5296 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5297 msg.GetString().c_str());
5300 // Tests streaming wide strings to testing::Message.
5301 TEST(MessageTest, WideStrings) {
5302 // Streams a NULL of type const wchar_t*.
5303 const wchar_t* const_wstr = nullptr;
5304 EXPECT_STREQ("(null)",
5305 (Message() << const_wstr).GetString().c_str());
5307 // Streams a NULL of type wchar_t*.
5308 wchar_t* wstr = nullptr;
5309 EXPECT_STREQ("(null)",
5310 (Message() << wstr).GetString().c_str());
5312 // Streams a non-NULL of type const wchar_t*.
5313 const_wstr = L"abc\x8119";
5314 EXPECT_STREQ("abc\xe8\x84\x99",
5315 (Message() << const_wstr).GetString().c_str());
5317 // Streams a non-NULL of type wchar_t*.
5318 wstr = const_cast<wchar_t*>(const_wstr);
5319 EXPECT_STREQ("abc\xe8\x84\x99",
5320 (Message() << wstr).GetString().c_str());
5324 // This line tests that we can define tests in the testing namespace.
5327 // Tests the TestInfo class.
5329 class TestInfoTest : public Test {
5331 static const TestInfo* GetTestInfo(const char* test_name) {
5332 const TestSuite* const test_suite =
5333 GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr);
5335 for (int i = 0; i < test_suite->total_test_count(); ++i) {
5336 const TestInfo* const test_info = test_suite->GetTestInfo(i);
5337 if (strcmp(test_name, test_info->name()) == 0)
5343 static const TestResult* GetTestResult(
5344 const TestInfo* test_info) {
5345 return test_info->result();
5349 // Tests TestInfo::test_case_name() and TestInfo::name().
5350 TEST_F(TestInfoTest, Names) {
5351 const TestInfo* const test_info = GetTestInfo("Names");
5353 ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
5354 ASSERT_STREQ("Names", test_info->name());
5357 // Tests TestInfo::result().
5358 TEST_F(TestInfoTest, result) {
5359 const TestInfo* const test_info = GetTestInfo("result");
5361 // Initially, there is no TestPartResult for this test.
5362 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5364 // After the previous assertion, there is still none.
5365 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5368 #define VERIFY_CODE_LOCATION \
5369 const int expected_line = __LINE__ - 1; \
5370 const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
5371 ASSERT_TRUE(test_info); \
5372 EXPECT_STREQ(__FILE__, test_info->file()); \
5373 EXPECT_EQ(expected_line, test_info->line())
5375 TEST(CodeLocationForTEST, Verify) {
5376 VERIFY_CODE_LOCATION;
5379 class CodeLocationForTESTF : public Test {
5382 TEST_F(CodeLocationForTESTF, Verify) {
5383 VERIFY_CODE_LOCATION;
5386 class CodeLocationForTESTP : public TestWithParam<int> {
5389 TEST_P(CodeLocationForTESTP, Verify) {
5390 VERIFY_CODE_LOCATION;
5393 INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
5395 template <typename T>
5396 class CodeLocationForTYPEDTEST : public Test {
5399 TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);
5401 TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
5402 VERIFY_CODE_LOCATION;
5405 template <typename T>
5406 class CodeLocationForTYPEDTESTP : public Test {
5409 TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
5411 TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
5412 VERIFY_CODE_LOCATION;
5415 REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
5417 INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
5419 #undef VERIFY_CODE_LOCATION
5421 // Tests setting up and tearing down a test case.
5422 // Legacy API is deprecated but still available
5423 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5424 class SetUpTestCaseTest : public Test {
5426 // This will be called once before the first test in this test case
5428 static void SetUpTestCase() {
5429 printf("Setting up the test case . . .\n");
5431 // Initializes some shared resource. In this simple example, we
5432 // just create a C string. More complex stuff can be done if
5434 shared_resource_ = "123";
5436 // Increments the number of test cases that have been set up.
5439 // SetUpTestCase() should be called only once.
5440 EXPECT_EQ(1, counter_);
5443 // This will be called once after the last test in this test case is
5445 static void TearDownTestCase() {
5446 printf("Tearing down the test case . . .\n");
5448 // Decrements the number of test cases that have been set up.
5451 // TearDownTestCase() should be called only once.
5452 EXPECT_EQ(0, counter_);
5454 // Cleans up the shared resource.
5455 shared_resource_ = nullptr;
5458 // This will be called before each test in this test case.
5459 void SetUp() override {
5460 // SetUpTestCase() should be called only once, so counter_ should
5462 EXPECT_EQ(1, counter_);
5465 // Number of test cases that have been set up.
5466 static int counter_;
5468 // Some resource to be shared by all tests in this test case.
5469 static const char* shared_resource_;
5472 int SetUpTestCaseTest::counter_ = 0;
5473 const char* SetUpTestCaseTest::shared_resource_ = nullptr;
5475 // A test that uses the shared resource.
5476 TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
5478 // Another test that uses the shared resource.
5479 TEST_F(SetUpTestCaseTest, Test2) {
5480 EXPECT_STREQ("123", shared_resource_);
5482 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5484 // Tests SetupTestSuite/TearDown TestSuite
5485 class SetUpTestSuiteTest : public Test {
5487 // This will be called once before the first test in this test case
5489 static void SetUpTestSuite() {
5490 printf("Setting up the test suite . . .\n");
5492 // Initializes some shared resource. In this simple example, we
5493 // just create a C string. More complex stuff can be done if
5495 shared_resource_ = "123";
5497 // Increments the number of test cases that have been set up.
5500 // SetUpTestSuite() should be called only once.
5501 EXPECT_EQ(1, counter_);
5504 // This will be called once after the last test in this test case is
5506 static void TearDownTestSuite() {
5507 printf("Tearing down the test suite . . .\n");
5509 // Decrements the number of test suites that have been set up.
5512 // TearDownTestSuite() should be called only once.
5513 EXPECT_EQ(0, counter_);
5515 // Cleans up the shared resource.
5516 shared_resource_ = nullptr;
5519 // This will be called before each test in this test case.
5520 void SetUp() override {
5521 // SetUpTestSuite() should be called only once, so counter_ should
5523 EXPECT_EQ(1, counter_);
5526 // Number of test suites that have been set up.
5527 static int counter_;
5529 // Some resource to be shared by all tests in this test case.
5530 static const char* shared_resource_;
5533 int SetUpTestSuiteTest::counter_ = 0;
5534 const char* SetUpTestSuiteTest::shared_resource_ = nullptr;
5536 // A test that uses the shared resource.
5537 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) {
5538 EXPECT_STRNE(nullptr, shared_resource_);
5541 // Another test that uses the shared resource.
5542 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
5543 EXPECT_STREQ("123", shared_resource_);
5546 // The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.
5548 // The Flags struct stores a copy of all Google Test flags.
5550 // Constructs a Flags struct where each flag has its default value.
5552 : also_run_disabled_tests(false),
5553 break_on_failure(false),
5554 catch_exceptions(false),
5555 death_test_use_fork(false),
5564 recreate_environments_when_repeating(true),
5566 stack_trace_depth(kMaxStackTraceDepth),
5567 stream_result_to(""),
5568 throw_on_failure(false) {}
5572 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5574 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5576 flags.also_run_disabled_tests = also_run_disabled_tests;
5580 // Creates a Flags struct where the gtest_break_on_failure flag has
5582 static Flags BreakOnFailure(bool break_on_failure) {
5584 flags.break_on_failure = break_on_failure;
5588 // Creates a Flags struct where the gtest_catch_exceptions flag has
5590 static Flags CatchExceptions(bool catch_exceptions) {
5592 flags.catch_exceptions = catch_exceptions;
5596 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5598 static Flags DeathTestUseFork(bool death_test_use_fork) {
5600 flags.death_test_use_fork = death_test_use_fork;
5604 // Creates a Flags struct where the gtest_fail_fast flag has
5606 static Flags FailFast(bool fail_fast) {
5608 flags.fail_fast = fail_fast;
5612 // Creates a Flags struct where the gtest_filter flag has the given
5614 static Flags Filter(const char* filter) {
5616 flags.filter = filter;
5620 // Creates a Flags struct where the gtest_list_tests flag has the
5622 static Flags ListTests(bool list_tests) {
5624 flags.list_tests = list_tests;
5628 // Creates a Flags struct where the gtest_output flag has the given
5630 static Flags Output(const char* output) {
5632 flags.output = output;
5636 // Creates a Flags struct where the gtest_brief flag has the given
5638 static Flags Brief(bool brief) {
5640 flags.brief = brief;
5644 // Creates a Flags struct where the gtest_print_time flag has the given
5646 static Flags PrintTime(bool print_time) {
5648 flags.print_time = print_time;
5652 // Creates a Flags struct where the gtest_random_seed flag has the given
5654 static Flags RandomSeed(int32_t random_seed) {
5656 flags.random_seed = random_seed;
5660 // Creates a Flags struct where the gtest_repeat flag has the given
5662 static Flags Repeat(int32_t repeat) {
5664 flags.repeat = repeat;
5668 // Creates a Flags struct where the gtest_recreate_environments_when_repeating
5669 // flag has the given value.
5670 static Flags RecreateEnvironmentsWhenRepeating(
5671 bool recreate_environments_when_repeating) {
5673 flags.recreate_environments_when_repeating =
5674 recreate_environments_when_repeating;
5678 // Creates a Flags struct where the gtest_shuffle flag has the given
5680 static Flags Shuffle(bool shuffle) {
5682 flags.shuffle = shuffle;
5686 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5688 static Flags StackTraceDepth(int32_t stack_trace_depth) {
5690 flags.stack_trace_depth = stack_trace_depth;
5694 // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5696 static Flags StreamResultTo(const char* stream_result_to) {
5698 flags.stream_result_to = stream_result_to;
5702 // Creates a Flags struct where the gtest_throw_on_failure flag has
5704 static Flags ThrowOnFailure(bool throw_on_failure) {
5706 flags.throw_on_failure = throw_on_failure;
5710 // These fields store the flag values.
5711 bool also_run_disabled_tests;
5712 bool break_on_failure;
5713 bool catch_exceptions;
5714 bool death_test_use_fork;
5721 int32_t random_seed;
5723 bool recreate_environments_when_repeating;
5725 int32_t stack_trace_depth;
5726 const char* stream_result_to;
5727 bool throw_on_failure;
5730 // Fixture for testing ParseGoogleTestFlagsOnly().
5731 class ParseFlagsTest : public Test {
5733 // Clears the flags before each test.
5734 void SetUp() override {
5735 GTEST_FLAG_SET(also_run_disabled_tests, false);
5736 GTEST_FLAG_SET(break_on_failure, false);
5737 GTEST_FLAG_SET(catch_exceptions, false);
5738 GTEST_FLAG_SET(death_test_use_fork, false);
5739 GTEST_FLAG_SET(fail_fast, false);
5740 GTEST_FLAG_SET(filter, "");
5741 GTEST_FLAG_SET(list_tests, false);
5742 GTEST_FLAG_SET(output, "");
5743 GTEST_FLAG_SET(brief, false);
5744 GTEST_FLAG_SET(print_time, true);
5745 GTEST_FLAG_SET(random_seed, 0);
5746 GTEST_FLAG_SET(repeat, 1);
5747 GTEST_FLAG_SET(recreate_environments_when_repeating, true);
5748 GTEST_FLAG_SET(shuffle, false);
5749 GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
5750 GTEST_FLAG_SET(stream_result_to, "");
5751 GTEST_FLAG_SET(throw_on_failure, false);
5754 // Asserts that two narrow or wide string arrays are equal.
5755 template <typename CharType>
5756 static void AssertStringArrayEq(int size1, CharType** array1, int size2,
5757 CharType** array2) {
5758 ASSERT_EQ(size1, size2) << " Array sizes different.";
5760 for (int i = 0; i != size1; i++) {
5761 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5765 // Verifies that the flag values match the expected values.
5766 static void CheckFlags(const Flags& expected) {
5767 EXPECT_EQ(expected.also_run_disabled_tests,
5768 GTEST_FLAG_GET(also_run_disabled_tests));
5769 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure));
5770 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions));
5771 EXPECT_EQ(expected.death_test_use_fork,
5772 GTEST_FLAG_GET(death_test_use_fork));
5773 EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast));
5774 EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str());
5775 EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests));
5776 EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str());
5777 EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief));
5778 EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time));
5779 EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed));
5780 EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat));
5781 EXPECT_EQ(expected.recreate_environments_when_repeating,
5782 GTEST_FLAG_GET(recreate_environments_when_repeating));
5783 EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle));
5784 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth));
5785 EXPECT_STREQ(expected.stream_result_to,
5786 GTEST_FLAG_GET(stream_result_to).c_str());
5787 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure));
5790 // Parses a command line (specified by argc1 and argv1), then
5791 // verifies that the flag values are expected and that the
5792 // recognized flags are removed from the command line.
5793 template <typename CharType>
5794 static void TestParsingFlags(int argc1, const CharType** argv1,
5795 int argc2, const CharType** argv2,
5796 const Flags& expected, bool should_print_help) {
5797 const bool saved_help_flag = ::testing::internal::g_help_flag;
5798 ::testing::internal::g_help_flag = false;
5800 # if GTEST_HAS_STREAM_REDIRECTION
5804 // Parses the command line.
5805 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5807 # if GTEST_HAS_STREAM_REDIRECTION
5808 const std::string captured_stdout = GetCapturedStdout();
5811 // Verifies the flag values.
5812 CheckFlags(expected);
5814 // Verifies that the recognized flags are removed from the command
5816 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5818 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5819 // help message for the flags it recognizes.
5820 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5822 # if GTEST_HAS_STREAM_REDIRECTION
5823 const char* const expected_help_fragment =
5824 "This program contains tests written using";
5825 if (should_print_help) {
5826 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5828 EXPECT_PRED_FORMAT2(IsNotSubstring,
5829 expected_help_fragment, captured_stdout);
5831 # endif // GTEST_HAS_STREAM_REDIRECTION
5833 ::testing::internal::g_help_flag = saved_help_flag;
5836 // This macro wraps TestParsingFlags s.t. the user doesn't need
5837 // to specify the array sizes.
5839 # define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5840 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5841 sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5842 expected, should_print_help)
5845 // Tests parsing an empty command line.
5846 TEST_F(ParseFlagsTest, Empty) {
5847 const char* argv[] = {nullptr};
5849 const char* argv2[] = {nullptr};
5851 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5854 // Tests parsing a command line that has no flag.
5855 TEST_F(ParseFlagsTest, NoFlag) {
5856 const char* argv[] = {"foo.exe", nullptr};
5858 const char* argv2[] = {"foo.exe", nullptr};
5860 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5863 // Tests parsing --gtest_fail_fast.
5864 TEST_F(ParseFlagsTest, FailFast) {
5865 const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
5867 const char* argv2[] = {"foo.exe", nullptr};
5869 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
5872 // Tests parsing a bad --gtest_filter flag.
5873 TEST_F(ParseFlagsTest, FilterBad) {
5874 const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
5876 const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
5878 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
5881 // Tests parsing an empty --gtest_filter flag.
5882 TEST_F(ParseFlagsTest, FilterEmpty) {
5883 const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
5885 const char* argv2[] = {"foo.exe", nullptr};
5887 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5890 // Tests parsing a non-empty --gtest_filter flag.
5891 TEST_F(ParseFlagsTest, FilterNonEmpty) {
5892 const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr};
5894 const char* argv2[] = {"foo.exe", nullptr};
5896 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5899 // Tests parsing --gtest_break_on_failure.
5900 TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {
5901 const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr};
5903 const char* argv2[] = {"foo.exe", nullptr};
5905 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5908 // Tests parsing --gtest_break_on_failure=0.
5909 TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {
5910 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr};
5912 const char* argv2[] = {"foo.exe", nullptr};
5914 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5917 // Tests parsing --gtest_break_on_failure=f.
5918 TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {
5919 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr};
5921 const char* argv2[] = {"foo.exe", nullptr};
5923 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5926 // Tests parsing --gtest_break_on_failure=F.
5927 TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {
5928 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr};
5930 const char* argv2[] = {"foo.exe", nullptr};
5932 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5935 // Tests parsing a --gtest_break_on_failure flag that has a "true"
5937 TEST_F(ParseFlagsTest, BreakOnFailureTrue) {
5938 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr};
5940 const char* argv2[] = {"foo.exe", nullptr};
5942 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5945 // Tests parsing --gtest_catch_exceptions.
5946 TEST_F(ParseFlagsTest, CatchExceptions) {
5947 const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr};
5949 const char* argv2[] = {"foo.exe", nullptr};
5951 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5954 // Tests parsing --gtest_death_test_use_fork.
5955 TEST_F(ParseFlagsTest, DeathTestUseFork) {
5956 const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr};
5958 const char* argv2[] = {"foo.exe", nullptr};
5960 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5963 // Tests having the same flag twice with different values. The
5964 // expected behavior is that the one coming last takes precedence.
5965 TEST_F(ParseFlagsTest, DuplicatedFlags) {
5966 const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b",
5969 const char* argv2[] = {"foo.exe", nullptr};
5971 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5974 // Tests having an unrecognized flag on the command line.
5975 TEST_F(ParseFlagsTest, UnrecognizedFlag) {
5976 const char* argv[] = {"foo.exe", "--gtest_break_on_failure",
5977 "bar", // Unrecognized by Google Test.
5978 "--gtest_filter=b", nullptr};
5980 const char* argv2[] = {"foo.exe", "bar", nullptr};
5983 flags.break_on_failure = true;
5985 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5988 // Tests having a --gtest_list_tests flag
5989 TEST_F(ParseFlagsTest, ListTestsFlag) {
5990 const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr};
5992 const char* argv2[] = {"foo.exe", nullptr};
5994 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5997 // Tests having a --gtest_list_tests flag with a "true" value
5998 TEST_F(ParseFlagsTest, ListTestsTrue) {
5999 const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr};
6001 const char* argv2[] = {"foo.exe", nullptr};
6003 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
6006 // Tests having a --gtest_list_tests flag with a "false" value
6007 TEST_F(ParseFlagsTest, ListTestsFalse) {
6008 const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr};
6010 const char* argv2[] = {"foo.exe", nullptr};
6012 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6015 // Tests parsing --gtest_list_tests=f.
6016 TEST_F(ParseFlagsTest, ListTestsFalse_f) {
6017 const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr};
6019 const char* argv2[] = {"foo.exe", nullptr};
6021 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6024 // Tests parsing --gtest_list_tests=F.
6025 TEST_F(ParseFlagsTest, ListTestsFalse_F) {
6026 const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr};
6028 const char* argv2[] = {"foo.exe", nullptr};
6030 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6033 // Tests parsing --gtest_output (invalid).
6034 TEST_F(ParseFlagsTest, OutputEmpty) {
6035 const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
6037 const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
6039 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
6042 // Tests parsing --gtest_output=xml
6043 TEST_F(ParseFlagsTest, OutputXml) {
6044 const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
6046 const char* argv2[] = {"foo.exe", nullptr};
6048 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
6051 // Tests parsing --gtest_output=xml:file
6052 TEST_F(ParseFlagsTest, OutputXmlFile) {
6053 const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr};
6055 const char* argv2[] = {"foo.exe", nullptr};
6057 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
6060 // Tests parsing --gtest_output=xml:directory/path/
6061 TEST_F(ParseFlagsTest, OutputXmlDirectory) {
6062 const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/",
6065 const char* argv2[] = {"foo.exe", nullptr};
6067 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6068 Flags::Output("xml:directory/path/"), false);
6071 // Tests having a --gtest_brief flag
6072 TEST_F(ParseFlagsTest, BriefFlag) {
6073 const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
6075 const char* argv2[] = {"foo.exe", nullptr};
6077 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
6080 // Tests having a --gtest_brief flag with a "true" value
6081 TEST_F(ParseFlagsTest, BriefFlagTrue) {
6082 const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
6084 const char* argv2[] = {"foo.exe", nullptr};
6086 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
6089 // Tests having a --gtest_brief flag with a "false" value
6090 TEST_F(ParseFlagsTest, BriefFlagFalse) {
6091 const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
6093 const char* argv2[] = {"foo.exe", nullptr};
6095 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
6098 // Tests having a --gtest_print_time flag
6099 TEST_F(ParseFlagsTest, PrintTimeFlag) {
6100 const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
6102 const char* argv2[] = {"foo.exe", nullptr};
6104 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6107 // Tests having a --gtest_print_time flag with a "true" value
6108 TEST_F(ParseFlagsTest, PrintTimeTrue) {
6109 const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr};
6111 const char* argv2[] = {"foo.exe", nullptr};
6113 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6116 // Tests having a --gtest_print_time flag with a "false" value
6117 TEST_F(ParseFlagsTest, PrintTimeFalse) {
6118 const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr};
6120 const char* argv2[] = {"foo.exe", nullptr};
6122 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6125 // Tests parsing --gtest_print_time=f.
6126 TEST_F(ParseFlagsTest, PrintTimeFalse_f) {
6127 const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr};
6129 const char* argv2[] = {"foo.exe", nullptr};
6131 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6134 // Tests parsing --gtest_print_time=F.
6135 TEST_F(ParseFlagsTest, PrintTimeFalse_F) {
6136 const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr};
6138 const char* argv2[] = {"foo.exe", nullptr};
6140 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6143 // Tests parsing --gtest_random_seed=number
6144 TEST_F(ParseFlagsTest, RandomSeed) {
6145 const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr};
6147 const char* argv2[] = {"foo.exe", nullptr};
6149 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6152 // Tests parsing --gtest_repeat=number
6153 TEST_F(ParseFlagsTest, Repeat) {
6154 const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr};
6156 const char* argv2[] = {"foo.exe", nullptr};
6158 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
6161 // Tests parsing --gtest_recreate_environments_when_repeating
6162 TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) {
6163 const char* argv[] = {
6165 "--gtest_recreate_environments_when_repeating=0",
6169 const char* argv2[] = {"foo.exe", nullptr};
6171 GTEST_TEST_PARSING_FLAGS_(
6172 argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false);
6175 // Tests having a --gtest_also_run_disabled_tests flag
6176 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
6177 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
6179 const char* argv2[] = {"foo.exe", nullptr};
6181 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
6185 // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6186 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {
6187 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1",
6190 const char* argv2[] = {"foo.exe", nullptr};
6192 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
6196 // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6197 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {
6198 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0",
6201 const char* argv2[] = {"foo.exe", nullptr};
6203 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false),
6207 // Tests parsing --gtest_shuffle.
6208 TEST_F(ParseFlagsTest, ShuffleWithoutValue) {
6209 const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr};
6211 const char* argv2[] = {"foo.exe", nullptr};
6213 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6216 // Tests parsing --gtest_shuffle=0.
6217 TEST_F(ParseFlagsTest, ShuffleFalse_0) {
6218 const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr};
6220 const char* argv2[] = {"foo.exe", nullptr};
6222 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6225 // Tests parsing a --gtest_shuffle flag that has a "true" definition.
6226 TEST_F(ParseFlagsTest, ShuffleTrue) {
6227 const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr};
6229 const char* argv2[] = {"foo.exe", nullptr};
6231 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6234 // Tests parsing --gtest_stack_trace_depth=number.
6235 TEST_F(ParseFlagsTest, StackTraceDepth) {
6236 const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr};
6238 const char* argv2[] = {"foo.exe", nullptr};
6240 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6243 TEST_F(ParseFlagsTest, StreamResultTo) {
6244 const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234",
6247 const char* argv2[] = {"foo.exe", nullptr};
6249 GTEST_TEST_PARSING_FLAGS_(
6250 argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
6253 // Tests parsing --gtest_throw_on_failure.
6254 TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
6255 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr};
6257 const char* argv2[] = {"foo.exe", nullptr};
6259 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6262 // Tests parsing --gtest_throw_on_failure=0.
6263 TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {
6264 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr};
6266 const char* argv2[] = {"foo.exe", nullptr};
6268 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
6271 // Tests parsing a --gtest_throw_on_failure flag that has a "true"
6273 TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
6274 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr};
6276 const char* argv2[] = {"foo.exe", nullptr};
6278 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6281 # if GTEST_OS_WINDOWS
6282 // Tests parsing wide strings.
6283 TEST_F(ParseFlagsTest, WideStrings) {
6284 const wchar_t* argv[] = {
6286 L"--gtest_filter=Foo*",
6287 L"--gtest_list_tests=1",
6288 L"--gtest_break_on_failure",
6289 L"--non_gtest_flag",
6293 const wchar_t* argv2[] = {
6295 L"--non_gtest_flag",
6299 Flags expected_flags;
6300 expected_flags.break_on_failure = true;
6301 expected_flags.filter = "Foo*";
6302 expected_flags.list_tests = true;
6304 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6306 # endif // GTEST_OS_WINDOWS
6308 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6309 class FlagfileTest : public ParseFlagsTest {
6311 void SetUp() override {
6312 ParseFlagsTest::SetUp();
6314 testdata_path_.Set(internal::FilePath(
6315 testing::TempDir() + internal::GetCurrentExecutableName().string() +
6317 testing::internal::posix::RmDir(testdata_path_.c_str());
6318 EXPECT_TRUE(testdata_path_.CreateFolder());
6321 void TearDown() override {
6322 testing::internal::posix::RmDir(testdata_path_.c_str());
6323 ParseFlagsTest::TearDown();
6326 internal::FilePath CreateFlagfile(const char* contents) {
6327 internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
6328 testdata_path_, internal::FilePath("unique"), "txt"));
6329 FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
6330 fprintf(f, "%s", contents);
6336 internal::FilePath testdata_path_;
6339 // Tests an empty flagfile.
6340 TEST_F(FlagfileTest, Empty) {
6341 internal::FilePath flagfile_path(CreateFlagfile(""));
6342 std::string flagfile_flag =
6343 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6345 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6347 const char* argv2[] = {"foo.exe", nullptr};
6349 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
6352 // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
6353 TEST_F(FlagfileTest, FilterNonEmpty) {
6354 internal::FilePath flagfile_path(CreateFlagfile(
6355 "--" GTEST_FLAG_PREFIX_ "filter=abc"));
6356 std::string flagfile_flag =
6357 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6359 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6361 const char* argv2[] = {"foo.exe", nullptr};
6363 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
6366 // Tests passing several flags via --gtest_flagfile.
6367 TEST_F(FlagfileTest, SeveralFlags) {
6368 internal::FilePath flagfile_path(CreateFlagfile(
6369 "--" GTEST_FLAG_PREFIX_ "filter=abc\n"
6370 "--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
6371 "--" GTEST_FLAG_PREFIX_ "list_tests"));
6372 std::string flagfile_flag =
6373 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6375 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6377 const char* argv2[] = {"foo.exe", nullptr};
6379 Flags expected_flags;
6380 expected_flags.break_on_failure = true;
6381 expected_flags.filter = "abc";
6382 expected_flags.list_tests = true;
6384 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6386 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6388 // Tests current_test_info() in UnitTest.
6389 class CurrentTestInfoTest : public Test {
6391 // Tests that current_test_info() returns NULL before the first test in
6392 // the test case is run.
6393 static void SetUpTestSuite() {
6394 // There should be no tests running at this point.
6395 const TestInfo* test_info =
6396 UnitTest::GetInstance()->current_test_info();
6397 EXPECT_TRUE(test_info == nullptr)
6398 << "There should be no tests running at this point.";
6401 // Tests that current_test_info() returns NULL after the last test in
6402 // the test case has run.
6403 static void TearDownTestSuite() {
6404 const TestInfo* test_info =
6405 UnitTest::GetInstance()->current_test_info();
6406 EXPECT_TRUE(test_info == nullptr)
6407 << "There should be no tests running at this point.";
6411 // Tests that current_test_info() returns TestInfo for currently running
6412 // test by checking the expected test name against the actual one.
6413 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
6414 const TestInfo* test_info =
6415 UnitTest::GetInstance()->current_test_info();
6416 ASSERT_TRUE(nullptr != test_info)
6417 << "There is a test running so we should have a valid TestInfo.";
6418 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6419 << "Expected the name of the currently running test suite.";
6420 EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
6421 << "Expected the name of the currently running test.";
6424 // Tests that current_test_info() returns TestInfo for currently running
6425 // test by checking the expected test name against the actual one. We
6426 // use this test to see that the TestInfo object actually changed from
6427 // the previous invocation.
6428 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
6429 const TestInfo* test_info =
6430 UnitTest::GetInstance()->current_test_info();
6431 ASSERT_TRUE(nullptr != test_info)
6432 << "There is a test running so we should have a valid TestInfo.";
6433 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6434 << "Expected the name of the currently running test suite.";
6435 EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
6436 << "Expected the name of the currently running test.";
6439 } // namespace testing
6442 // These two lines test that we can define tests in a namespace that
6443 // has the name "testing" and is nested in another namespace.
6444 namespace my_namespace {
6447 // Makes sure that TEST knows to use ::testing::Test instead of
6448 // ::my_namespace::testing::Test.
6451 // Makes sure that an assertion knows to use ::testing::Message instead of
6452 // ::my_namespace::testing::Message.
6455 // Makes sure that an assertion knows to use
6456 // ::testing::AssertionResult instead of
6457 // ::my_namespace::testing::AssertionResult.
6458 class AssertionResult {};
6460 // Tests that an assertion that should succeed works as expected.
6461 TEST(NestedTestingNamespaceTest, Success) {
6462 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6465 // Tests that an assertion that should fail works as expected.
6466 TEST(NestedTestingNamespaceTest, Failure) {
6467 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6468 "This failure is expected.");
6471 } // namespace testing
6472 } // namespace my_namespace
6474 // Tests that one can call superclass SetUp and TearDown methods--
6475 // that is, that they are not private.
6476 // No tests are based on this fixture; the test "passes" if it compiles
6478 class ProtectedFixtureMethodsTest : public Test {
6480 void SetUp() override { Test::SetUp(); }
6481 void TearDown() override { Test::TearDown(); }
6484 // StreamingAssertionsTest tests the streaming versions of a representative
6485 // sample of assertions.
6486 TEST(StreamingAssertionsTest, Unconditional) {
6487 SUCCEED() << "expected success";
6488 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6489 "expected failure");
6490 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6491 "expected failure");
6495 // Silences warnings: "Condition is always true", "Unreachable code"
6496 # pragma option push -w-ccc -w-rch
6499 TEST(StreamingAssertionsTest, Truth) {
6500 EXPECT_TRUE(true) << "unexpected failure";
6501 ASSERT_TRUE(true) << "unexpected failure";
6502 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6503 "expected failure");
6504 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6505 "expected failure");
6508 TEST(StreamingAssertionsTest, Truth2) {
6509 EXPECT_FALSE(false) << "unexpected failure";
6510 ASSERT_FALSE(false) << "unexpected failure";
6511 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6512 "expected failure");
6513 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6514 "expected failure");
6518 // Restores warnings after previous "#pragma option push" suppressed them
6522 TEST(StreamingAssertionsTest, IntegerEquals) {
6523 EXPECT_EQ(1, 1) << "unexpected failure";
6524 ASSERT_EQ(1, 1) << "unexpected failure";
6525 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6526 "expected failure");
6527 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6528 "expected failure");
6531 TEST(StreamingAssertionsTest, IntegerLessThan) {
6532 EXPECT_LT(1, 2) << "unexpected failure";
6533 ASSERT_LT(1, 2) << "unexpected failure";
6534 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6535 "expected failure");
6536 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6537 "expected failure");
6540 TEST(StreamingAssertionsTest, StringsEqual) {
6541 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6542 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6543 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6544 "expected failure");
6545 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6546 "expected failure");
6549 TEST(StreamingAssertionsTest, StringsNotEqual) {
6550 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6551 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6552 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6553 "expected failure");
6554 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6555 "expected failure");
6558 TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6559 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6560 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6561 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6562 "expected failure");
6563 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6564 "expected failure");
6567 TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6568 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6569 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6570 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6571 "expected failure");
6572 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6573 "expected failure");
6576 TEST(StreamingAssertionsTest, FloatingPointEquals) {
6577 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6578 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6579 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6580 "expected failure");
6581 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6582 "expected failure");
6585 #if GTEST_HAS_EXCEPTIONS
6587 TEST(StreamingAssertionsTest, Throw) {
6588 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6589 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6590 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6591 "expected failure", "expected failure");
6592 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6593 "expected failure", "expected failure");
6596 TEST(StreamingAssertionsTest, NoThrow) {
6597 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6598 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6599 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6600 "expected failure", "expected failure");
6601 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6602 "expected failure", "expected failure");
6605 TEST(StreamingAssertionsTest, AnyThrow) {
6606 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6607 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6608 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
6609 "expected failure", "expected failure");
6610 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
6611 "expected failure", "expected failure");
6614 #endif // GTEST_HAS_EXCEPTIONS
6616 // Tests that Google Test correctly decides whether to use colors in the output.
6618 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6619 GTEST_FLAG_SET(color, "yes");
6621 SetEnv("TERM", "xterm"); // TERM supports colors.
6622 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6623 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6625 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6626 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6627 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6630 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6631 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6633 GTEST_FLAG_SET(color, "True");
6634 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6636 GTEST_FLAG_SET(color, "t");
6637 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6639 GTEST_FLAG_SET(color, "1");
6640 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6643 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6644 GTEST_FLAG_SET(color, "no");
6646 SetEnv("TERM", "xterm"); // TERM supports colors.
6647 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6648 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6650 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6651 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6652 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6655 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6656 SetEnv("TERM", "xterm"); // TERM supports colors.
6658 GTEST_FLAG_SET(color, "F");
6659 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6661 GTEST_FLAG_SET(color, "0");
6662 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6664 GTEST_FLAG_SET(color, "unknown");
6665 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6668 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6669 GTEST_FLAG_SET(color, "auto");
6671 SetEnv("TERM", "xterm"); // TERM supports colors.
6672 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6673 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6676 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6677 GTEST_FLAG_SET(color, "auto");
6679 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
6680 // On Windows, we ignore the TERM variable as it's usually not set.
6682 SetEnv("TERM", "dumb");
6683 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6686 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6688 SetEnv("TERM", "xterm");
6689 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6691 // On non-Windows platforms, we rely on TERM to determine if the
6692 // terminal supports colors.
6694 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6695 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6697 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6698 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6700 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6701 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6703 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6704 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6706 SetEnv("TERM", "xterm"); // TERM supports colors.
6707 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6709 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6710 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6712 SetEnv("TERM", "xterm-256color"); // TERM supports colors.
6713 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6715 SetEnv("TERM", "screen"); // TERM supports colors.
6716 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6718 SetEnv("TERM", "screen-256color"); // TERM supports colors.
6719 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6721 SetEnv("TERM", "tmux"); // TERM supports colors.
6722 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6724 SetEnv("TERM", "tmux-256color"); // TERM supports colors.
6725 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6727 SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
6728 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6730 SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
6731 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6733 SetEnv("TERM", "linux"); // TERM supports colors.
6734 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6736 SetEnv("TERM", "cygwin"); // TERM supports colors.
6737 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6738 #endif // GTEST_OS_WINDOWS
6741 // Verifies that StaticAssertTypeEq works in a namespace scope.
6743 static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6744 static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6745 StaticAssertTypeEq<const int, const int>();
6747 // Verifies that StaticAssertTypeEq works in a class.
6749 template <typename T>
6750 class StaticAssertTypeEqTestHelper {
6752 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6755 TEST(StaticAssertTypeEqTest, WorksInClass) {
6756 StaticAssertTypeEqTestHelper<bool>();
6759 // Verifies that StaticAssertTypeEq works inside a function.
6761 typedef int IntAlias;
6763 TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6764 StaticAssertTypeEq<int, IntAlias>();
6765 StaticAssertTypeEq<int*, IntAlias*>();
6768 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6769 EXPECT_FALSE(HasNonfatalFailure());
6772 static void FailFatally() { FAIL(); }
6774 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6776 const bool has_nonfatal_failure = HasNonfatalFailure();
6777 ClearCurrentTestPartResults();
6778 EXPECT_FALSE(has_nonfatal_failure);
6781 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6783 const bool has_nonfatal_failure = HasNonfatalFailure();
6784 ClearCurrentTestPartResults();
6785 EXPECT_TRUE(has_nonfatal_failure);
6788 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6791 const bool has_nonfatal_failure = HasNonfatalFailure();
6792 ClearCurrentTestPartResults();
6793 EXPECT_TRUE(has_nonfatal_failure);
6796 // A wrapper for calling HasNonfatalFailure outside of a test body.
6797 static bool HasNonfatalFailureHelper() {
6798 return testing::Test::HasNonfatalFailure();
6801 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6802 EXPECT_FALSE(HasNonfatalFailureHelper());
6805 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6807 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6808 ClearCurrentTestPartResults();
6809 EXPECT_TRUE(has_nonfatal_failure);
6812 TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6813 EXPECT_FALSE(HasFailure());
6816 TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6818 const bool has_failure = HasFailure();
6819 ClearCurrentTestPartResults();
6820 EXPECT_TRUE(has_failure);
6823 TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6825 const bool has_failure = HasFailure();
6826 ClearCurrentTestPartResults();
6827 EXPECT_TRUE(has_failure);
6830 TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6833 const bool has_failure = HasFailure();
6834 ClearCurrentTestPartResults();
6835 EXPECT_TRUE(has_failure);
6838 // A wrapper for calling HasFailure outside of a test body.
6839 static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6841 TEST(HasFailureTest, WorksOutsideOfTestBody) {
6842 EXPECT_FALSE(HasFailureHelper());
6845 TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6847 const bool has_failure = HasFailureHelper();
6848 ClearCurrentTestPartResults();
6849 EXPECT_TRUE(has_failure);
6852 class TestListener : public EmptyTestEventListener {
6854 TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
6855 TestListener(int* on_start_counter, bool* is_destroyed)
6856 : on_start_counter_(on_start_counter),
6857 is_destroyed_(is_destroyed) {}
6859 ~TestListener() override {
6861 *is_destroyed_ = true;
6865 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6866 if (on_start_counter_ != nullptr) (*on_start_counter_)++;
6870 int* on_start_counter_;
6871 bool* is_destroyed_;
6874 // Tests the constructor.
6875 TEST(TestEventListenersTest, ConstructionWorks) {
6876 TestEventListeners listeners;
6878 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr);
6879 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
6880 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
6883 // Tests that the TestEventListeners destructor deletes all the listeners it
6885 TEST(TestEventListenersTest, DestructionWorks) {
6886 bool default_result_printer_is_destroyed = false;
6887 bool default_xml_printer_is_destroyed = false;
6888 bool extra_listener_is_destroyed = false;
6889 TestListener* default_result_printer =
6890 new TestListener(nullptr, &default_result_printer_is_destroyed);
6891 TestListener* default_xml_printer =
6892 new TestListener(nullptr, &default_xml_printer_is_destroyed);
6893 TestListener* extra_listener =
6894 new TestListener(nullptr, &extra_listener_is_destroyed);
6897 TestEventListeners listeners;
6898 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
6899 default_result_printer);
6900 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
6901 default_xml_printer);
6902 listeners.Append(extra_listener);
6904 EXPECT_TRUE(default_result_printer_is_destroyed);
6905 EXPECT_TRUE(default_xml_printer_is_destroyed);
6906 EXPECT_TRUE(extra_listener_is_destroyed);
6909 // Tests that a listener Append'ed to a TestEventListeners list starts
6910 // receiving events.
6911 TEST(TestEventListenersTest, Append) {
6912 int on_start_counter = 0;
6913 bool is_destroyed = false;
6914 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6916 TestEventListeners listeners;
6917 listeners.Append(listener);
6918 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6919 *UnitTest::GetInstance());
6920 EXPECT_EQ(1, on_start_counter);
6922 EXPECT_TRUE(is_destroyed);
6925 // Tests that listeners receive events in the order they were appended to
6926 // the list, except for *End requests, which must be received in the reverse
6928 class SequenceTestingListener : public EmptyTestEventListener {
6930 SequenceTestingListener(std::vector<std::string>* vector, const char* id)
6931 : vector_(vector), id_(id) {}
6934 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6935 vector_->push_back(GetEventDescription("OnTestProgramStart"));
6938 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {
6939 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
6942 void OnTestIterationStart(const UnitTest& /*unit_test*/,
6943 int /*iteration*/) override {
6944 vector_->push_back(GetEventDescription("OnTestIterationStart"));
6947 void OnTestIterationEnd(const UnitTest& /*unit_test*/,
6948 int /*iteration*/) override {
6949 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
6953 std::string GetEventDescription(const char* method) {
6955 message << id_ << "." << method;
6956 return message.GetString();
6959 std::vector<std::string>* vector_;
6960 const char* const id_;
6962 GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
6965 TEST(EventListenerTest, AppendKeepsOrder) {
6966 std::vector<std::string> vec;
6967 TestEventListeners listeners;
6968 listeners.Append(new SequenceTestingListener(&vec, "1st"));
6969 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
6970 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
6972 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6973 *UnitTest::GetInstance());
6974 ASSERT_EQ(3U, vec.size());
6975 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
6976 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
6977 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
6980 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
6981 *UnitTest::GetInstance());
6982 ASSERT_EQ(3U, vec.size());
6983 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
6984 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
6985 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
6988 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
6989 *UnitTest::GetInstance(), 0);
6990 ASSERT_EQ(3U, vec.size());
6991 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
6992 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
6993 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
6996 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
6997 *UnitTest::GetInstance(), 0);
6998 ASSERT_EQ(3U, vec.size());
6999 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
7000 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
7001 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
7004 // Tests that a listener removed from a TestEventListeners list stops receiving
7005 // events and is not deleted when the list is destroyed.
7006 TEST(TestEventListenersTest, Release) {
7007 int on_start_counter = 0;
7008 bool is_destroyed = false;
7009 // Although Append passes the ownership of this object to the list,
7010 // the following calls release it, and we need to delete it before the
7012 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7014 TestEventListeners listeners;
7015 listeners.Append(listener);
7016 EXPECT_EQ(listener, listeners.Release(listener));
7017 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7018 *UnitTest::GetInstance());
7019 EXPECT_TRUE(listeners.Release(listener) == nullptr);
7021 EXPECT_EQ(0, on_start_counter);
7022 EXPECT_FALSE(is_destroyed);
7026 // Tests that no events are forwarded when event forwarding is disabled.
7027 TEST(EventListenerTest, SuppressEventForwarding) {
7028 int on_start_counter = 0;
7029 TestListener* listener = new TestListener(&on_start_counter, nullptr);
7031 TestEventListeners listeners;
7032 listeners.Append(listener);
7033 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7034 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
7035 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7036 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7037 *UnitTest::GetInstance());
7038 EXPECT_EQ(0, on_start_counter);
7041 // Tests that events generated by Google Test are not forwarded in
7042 // death test subprocesses.
7043 TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
7044 EXPECT_DEATH_IF_SUPPORTED({
7045 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
7046 *GetUnitTestImpl()->listeners())) << "expected failure";},
7047 "expected failure");
7050 // Tests that a listener installed via SetDefaultResultPrinter() starts
7051 // receiving events and is returned via default_result_printer() and that
7052 // the previous default_result_printer is removed from the list and deleted.
7053 TEST(EventListenerTest, default_result_printer) {
7054 int on_start_counter = 0;
7055 bool is_destroyed = false;
7056 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7058 TestEventListeners listeners;
7059 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7061 EXPECT_EQ(listener, listeners.default_result_printer());
7063 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7064 *UnitTest::GetInstance());
7066 EXPECT_EQ(1, on_start_counter);
7068 // Replacing default_result_printer with something else should remove it
7069 // from the list and destroy it.
7070 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr);
7072 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7073 EXPECT_TRUE(is_destroyed);
7075 // After broadcasting an event the counter is still the same, indicating
7076 // the listener is not in the list anymore.
7077 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7078 *UnitTest::GetInstance());
7079 EXPECT_EQ(1, on_start_counter);
7082 // Tests that the default_result_printer listener stops receiving events
7083 // when removed via Release and that is not owned by the list anymore.
7084 TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
7085 int on_start_counter = 0;
7086 bool is_destroyed = false;
7087 // Although Append passes the ownership of this object to the list,
7088 // the following calls release it, and we need to delete it before the
7090 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7092 TestEventListeners listeners;
7093 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7095 EXPECT_EQ(listener, listeners.Release(listener));
7096 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7097 EXPECT_FALSE(is_destroyed);
7099 // Broadcasting events now should not affect default_result_printer.
7100 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7101 *UnitTest::GetInstance());
7102 EXPECT_EQ(0, on_start_counter);
7104 // Destroying the list should not affect the listener now, too.
7105 EXPECT_FALSE(is_destroyed);
7109 // Tests that a listener installed via SetDefaultXmlGenerator() starts
7110 // receiving events and is returned via default_xml_generator() and that
7111 // the previous default_xml_generator is removed from the list and deleted.
7112 TEST(EventListenerTest, default_xml_generator) {
7113 int on_start_counter = 0;
7114 bool is_destroyed = false;
7115 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7117 TestEventListeners listeners;
7118 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7120 EXPECT_EQ(listener, listeners.default_xml_generator());
7122 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7123 *UnitTest::GetInstance());
7125 EXPECT_EQ(1, on_start_counter);
7127 // Replacing default_xml_generator with something else should remove it
7128 // from the list and destroy it.
7129 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr);
7131 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7132 EXPECT_TRUE(is_destroyed);
7134 // After broadcasting an event the counter is still the same, indicating
7135 // the listener is not in the list anymore.
7136 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7137 *UnitTest::GetInstance());
7138 EXPECT_EQ(1, on_start_counter);
7141 // Tests that the default_xml_generator listener stops receiving events
7142 // when removed via Release and that is not owned by the list anymore.
7143 TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
7144 int on_start_counter = 0;
7145 bool is_destroyed = false;
7146 // Although Append passes the ownership of this object to the list,
7147 // the following calls release it, and we need to delete it before the
7149 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7151 TestEventListeners listeners;
7152 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7154 EXPECT_EQ(listener, listeners.Release(listener));
7155 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7156 EXPECT_FALSE(is_destroyed);
7158 // Broadcasting events now should not affect default_xml_generator.
7159 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7160 *UnitTest::GetInstance());
7161 EXPECT_EQ(0, on_start_counter);
7163 // Destroying the list should not affect the listener now, too.
7164 EXPECT_FALSE(is_destroyed);
7168 // Sanity tests to ensure that the alternative, verbose spellings of
7169 // some of the macros work. We don't test them thoroughly as that
7170 // would be quite involved. Since their implementations are
7171 // straightforward, and they are rarely used, we'll just rely on the
7172 // users to tell us when they are broken.
7173 GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
7174 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
7176 // GTEST_FAIL is the same as FAIL.
7177 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
7178 "An expected failure");
7180 // GTEST_ASSERT_XY is the same as ASSERT_XY.
7182 GTEST_ASSERT_EQ(0, 0);
7183 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
7184 "An expected failure");
7185 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
7186 "An expected failure");
7188 GTEST_ASSERT_NE(0, 1);
7189 GTEST_ASSERT_NE(1, 0);
7190 EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
7191 "An expected failure");
7193 GTEST_ASSERT_LE(0, 0);
7194 GTEST_ASSERT_LE(0, 1);
7195 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
7196 "An expected failure");
7198 GTEST_ASSERT_LT(0, 1);
7199 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
7200 "An expected failure");
7201 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
7202 "An expected failure");
7204 GTEST_ASSERT_GE(0, 0);
7205 GTEST_ASSERT_GE(1, 0);
7206 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
7207 "An expected failure");
7209 GTEST_ASSERT_GT(1, 0);
7210 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
7211 "An expected failure");
7212 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
7213 "An expected failure");
7216 // Tests for internal utilities necessary for implementation of the universal
7219 class ConversionHelperBase {};
7220 class ConversionHelperDerived : public ConversionHelperBase {};
7222 struct HasDebugStringMethods {
7223 std::string DebugString() const { return ""; }
7224 std::string ShortDebugString() const { return ""; }
7227 struct InheritsDebugStringMethods : public HasDebugStringMethods {};
7229 struct WrongTypeDebugStringMethod {
7230 std::string DebugString() const { return ""; }
7231 int ShortDebugString() const { return 1; }
7234 struct NotConstDebugStringMethod {
7235 std::string DebugString() { return ""; }
7236 std::string ShortDebugString() const { return ""; }
7239 struct MissingDebugStringMethod {
7240 std::string DebugString() { return ""; }
7243 struct IncompleteType;
7245 // Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
7247 TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
7248 GTEST_COMPILE_ASSERT_(
7249 HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
7251 GTEST_COMPILE_ASSERT_(
7252 HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
7254 GTEST_COMPILE_ASSERT_(HasDebugStringAndShortDebugString<
7255 const InheritsDebugStringMethods>::value,
7257 GTEST_COMPILE_ASSERT_(
7258 !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
7260 GTEST_COMPILE_ASSERT_(
7261 !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
7263 GTEST_COMPILE_ASSERT_(
7264 !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
7266 GTEST_COMPILE_ASSERT_(
7267 !HasDebugStringAndShortDebugString<IncompleteType>::value, const_false);
7268 GTEST_COMPILE_ASSERT_(!HasDebugStringAndShortDebugString<int>::value,
7272 // Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
7274 TEST(HasDebugStringAndShortDebugStringTest,
7275 ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
7277 HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
7280 // Tests that HasDebugStringAndShortDebugString<T>::value is false when T
7281 // doesn't have needed methods.
7282 TEST(HasDebugStringAndShortDebugStringTest,
7283 ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7284 EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);
7286 HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);
7289 // Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7291 template <typename T1, typename T2>
7292 void TestGTestRemoveReferenceAndConst() {
7293 static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value,
7294 "GTEST_REMOVE_REFERENCE_AND_CONST_ failed.");
7297 TEST(RemoveReferenceToConstTest, Works) {
7298 TestGTestRemoveReferenceAndConst<int, int>();
7299 TestGTestRemoveReferenceAndConst<double, double&>();
7300 TestGTestRemoveReferenceAndConst<char, const char>();
7301 TestGTestRemoveReferenceAndConst<char, const char&>();
7302 TestGTestRemoveReferenceAndConst<const char*, const char*>();
7305 // Tests GTEST_REFERENCE_TO_CONST_.
7307 template <typename T1, typename T2>
7308 void TestGTestReferenceToConst() {
7309 static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value,
7310 "GTEST_REFERENCE_TO_CONST_ failed.");
7313 TEST(GTestReferenceToConstTest, Works) {
7314 TestGTestReferenceToConst<const char&, char>();
7315 TestGTestReferenceToConst<const int&, const int>();
7316 TestGTestReferenceToConst<const double&, double>();
7317 TestGTestReferenceToConst<const std::string&, const std::string&>();
7321 // Tests IsContainerTest.
7323 class NonContainer {};
7325 TEST(IsContainerTestTest, WorksForNonContainer) {
7326 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7327 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7328 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7331 TEST(IsContainerTestTest, WorksForContainer) {
7332 EXPECT_EQ(sizeof(IsContainer),
7333 sizeof(IsContainerTest<std::vector<bool> >(0)));
7334 EXPECT_EQ(sizeof(IsContainer),
7335 sizeof(IsContainerTest<std::map<int, double> >(0)));
7338 struct ConstOnlyContainerWithPointerIterator {
7339 using const_iterator = int*;
7340 const_iterator begin() const;
7341 const_iterator end() const;
7344 struct ConstOnlyContainerWithClassIterator {
7345 struct const_iterator {
7346 const int& operator*() const;
7347 const_iterator& operator++(/* pre-increment */);
7349 const_iterator begin() const;
7350 const_iterator end() const;
7353 TEST(IsContainerTestTest, ConstOnlyContainer) {
7354 EXPECT_EQ(sizeof(IsContainer),
7355 sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
7356 EXPECT_EQ(sizeof(IsContainer),
7357 sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
7360 // Tests IsHashTable.
7362 typedef void hasher;
7364 struct NotReallyAHashTable {
7365 typedef void hasher;
7366 typedef void reverse_iterator;
7368 TEST(IsHashTable, Basic) {
7369 EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value);
7370 EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value);
7371 EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value);
7372 EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value);
7377 TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7378 EXPECT_TRUE(ArrayEq(5, 5L));
7379 EXPECT_FALSE(ArrayEq('a', 0));
7382 TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7383 // Note that a and b are distinct but compatible types.
7384 const int a[] = { 0, 1 };
7385 long b[] = { 0, 1 };
7386 EXPECT_TRUE(ArrayEq(a, b));
7387 EXPECT_TRUE(ArrayEq(a, 2, b));
7390 EXPECT_FALSE(ArrayEq(a, b));
7391 EXPECT_FALSE(ArrayEq(a, 1, b));
7394 TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7395 const char a[][3] = { "hi", "lo" };
7396 const char b[][3] = { "hi", "lo" };
7397 const char c[][3] = { "hi", "li" };
7399 EXPECT_TRUE(ArrayEq(a, b));
7400 EXPECT_TRUE(ArrayEq(a, 2, b));
7402 EXPECT_FALSE(ArrayEq(a, c));
7403 EXPECT_FALSE(ArrayEq(a, 2, c));
7406 // Tests ArrayAwareFind().
7408 TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7409 const char a[] = "hello";
7410 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7411 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7414 TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7415 int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
7416 const int b[2] = { 2, 3 };
7417 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7419 const int c[2] = { 6, 7 };
7420 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7423 // Tests CopyArray().
7425 TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7431 TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7432 const char a[3] = "hi";
7434 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7436 EXPECT_TRUE(ArrayEq(a, b));
7441 EXPECT_TRUE(ArrayEq(a, c));
7444 TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7445 const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
7447 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7449 EXPECT_TRUE(ArrayEq(a, b));
7454 EXPECT_TRUE(ArrayEq(a, c));
7457 // Tests NativeArray.
7459 TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7460 const int a[3] = { 0, 1, 2 };
7461 NativeArray<int> na(a, 3, RelationToSourceReference());
7462 EXPECT_EQ(3U, na.size());
7463 EXPECT_EQ(a, na.begin());
7466 TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7467 typedef int Array[2];
7468 Array* a = new Array[1];
7471 NativeArray<int> na(*a, 2, RelationToSourceCopy());
7472 EXPECT_NE(*a, na.begin());
7474 EXPECT_EQ(0, na.begin()[0]);
7475 EXPECT_EQ(1, na.begin()[1]);
7477 // We rely on the heap checker to verify that na deletes the copy of
7481 TEST(NativeArrayTest, TypeMembersAreCorrect) {
7482 StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7483 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7485 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7486 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7489 TEST(NativeArrayTest, MethodsWork) {
7490 const int a[3] = { 0, 1, 2 };
7491 NativeArray<int> na(a, 3, RelationToSourceCopy());
7492 ASSERT_EQ(3U, na.size());
7493 EXPECT_EQ(3, na.end() - na.begin());
7495 NativeArray<int>::const_iterator it = na.begin();
7502 EXPECT_EQ(na.end(), it);
7504 EXPECT_TRUE(na == na);
7506 NativeArray<int> na2(a, 3, RelationToSourceReference());
7507 EXPECT_TRUE(na == na2);
7509 const int b1[3] = { 0, 1, 1 };
7510 const int b2[4] = { 0, 1, 2, 3 };
7511 EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
7512 EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
7515 TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7516 const char a[2][3] = { "hi", "lo" };
7517 NativeArray<char[3]> na(a, 2, RelationToSourceReference());
7518 ASSERT_EQ(2U, na.size());
7519 EXPECT_EQ(a, na.begin());
7523 TEST(IndexSequence, MakeIndexSequence) {
7524 using testing::internal::IndexSequence;
7525 using testing::internal::MakeIndexSequence;
7527 (std::is_same<IndexSequence<>, MakeIndexSequence<0>::type>::value));
7529 (std::is_same<IndexSequence<0>, MakeIndexSequence<1>::type>::value));
7531 (std::is_same<IndexSequence<0, 1>, MakeIndexSequence<2>::type>::value));
7533 std::is_same<IndexSequence<0, 1, 2>, MakeIndexSequence<3>::type>::value));
7535 (std::is_base_of<IndexSequence<0, 1, 2>, MakeIndexSequence<3>>::value));
7539 TEST(ElemFromList, Basic) {
7540 using testing::internal::ElemFromList;
7542 (std::is_same<int, ElemFromList<0, int, double, char>::type>::value));
7544 (std::is_same<double, ElemFromList<1, int, double, char>::type>::value));
7546 (std::is_same<char, ElemFromList<2, int, double, char>::type>::value));
7548 std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int,
7549 char, int, int, int, int>::type>::value));
7553 TEST(FlatTuple, Basic) {
7554 using testing::internal::FlatTuple;
7556 FlatTuple<int, double, const char*> tuple = {};
7557 EXPECT_EQ(0, tuple.Get<0>());
7558 EXPECT_EQ(0.0, tuple.Get<1>());
7559 EXPECT_EQ(nullptr, tuple.Get<2>());
7561 tuple = FlatTuple<int, double, const char*>(
7562 testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo");
7563 EXPECT_EQ(7, tuple.Get<0>());
7564 EXPECT_EQ(3.2, tuple.Get<1>());
7565 EXPECT_EQ(std::string("Foo"), tuple.Get<2>());
7567 tuple.Get<1>() = 5.1;
7568 EXPECT_EQ(5.1, tuple.Get<1>());
7572 std::string AddIntToString(int i, const std::string& s) {
7573 return s + std::to_string(i);
7577 TEST(FlatTuple, Apply) {
7578 using testing::internal::FlatTuple;
7580 FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},
7584 EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
7585 return i == static_cast<int>(s.size());
7589 EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
7591 // Mutating operations.
7592 tuple.Apply([](int& i, std::string& s) {
7596 EXPECT_EQ(tuple.Get<0>(), 6);
7597 EXPECT_EQ(tuple.Get<1>(), "HelloHello");
7600 struct ConstructionCounting {
7601 ConstructionCounting() { ++default_ctor_calls; }
7602 ~ConstructionCounting() { ++dtor_calls; }
7603 ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }
7604 ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }
7605 ConstructionCounting& operator=(const ConstructionCounting&) {
7606 ++copy_assignment_calls;
7609 ConstructionCounting& operator=(ConstructionCounting&&) noexcept {
7610 ++move_assignment_calls;
7614 static void Reset() {
7615 default_ctor_calls = 0;
7617 copy_ctor_calls = 0;
7618 move_ctor_calls = 0;
7619 copy_assignment_calls = 0;
7620 move_assignment_calls = 0;
7623 static int default_ctor_calls;
7624 static int dtor_calls;
7625 static int copy_ctor_calls;
7626 static int move_ctor_calls;
7627 static int copy_assignment_calls;
7628 static int move_assignment_calls;
7631 int ConstructionCounting::default_ctor_calls = 0;
7632 int ConstructionCounting::dtor_calls = 0;
7633 int ConstructionCounting::copy_ctor_calls = 0;
7634 int ConstructionCounting::move_ctor_calls = 0;
7635 int ConstructionCounting::copy_assignment_calls = 0;
7636 int ConstructionCounting::move_assignment_calls = 0;
7638 TEST(FlatTuple, ConstructorCalls) {
7639 using testing::internal::FlatTuple;
7641 // Default construction.
7642 ConstructionCounting::Reset();
7643 { FlatTuple<ConstructionCounting> tuple; }
7644 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7645 EXPECT_EQ(ConstructionCounting::dtor_calls, 1);
7646 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7647 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7648 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7649 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7651 // Copy construction.
7652 ConstructionCounting::Reset();
7654 ConstructionCounting elem;
7655 FlatTuple<ConstructionCounting> tuple{
7656 testing::internal::FlatTupleConstructTag{}, elem};
7658 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7659 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7660 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);
7661 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7662 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7663 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7665 // Move construction.
7666 ConstructionCounting::Reset();
7668 FlatTuple<ConstructionCounting> tuple{
7669 testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}};
7671 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7672 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7673 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7674 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);
7675 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7676 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7679 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7681 ConstructionCounting::Reset();
7683 FlatTuple<ConstructionCounting> tuple;
7684 ConstructionCounting elem;
7685 tuple.Get<0>() = elem;
7687 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
7688 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7689 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7690 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7691 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);
7692 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7695 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7697 ConstructionCounting::Reset();
7699 FlatTuple<ConstructionCounting> tuple;
7700 tuple.Get<0>() = ConstructionCounting{};
7702 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
7703 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7704 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7705 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7706 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7707 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);
7709 ConstructionCounting::Reset();
7712 TEST(FlatTuple, ManyTypes) {
7713 using testing::internal::FlatTuple;
7715 // Instantiate FlatTuple with 257 ints.
7716 // Tests show that we can do it with thousands of elements, but very long
7717 // compile times makes it unusuitable for this test.
7718 #define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int,
7719 #define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8
7720 #define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16
7721 #define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32
7722 #define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64
7723 #define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128
7725 // Let's make sure that we can have a very long list of types without blowing
7726 // up the template instantiation depth.
7727 FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple;
7730 tuple.Get<99>() = 17;
7731 tuple.Get<256>() = 1000;
7732 EXPECT_EQ(7, tuple.Get<0>());
7733 EXPECT_EQ(17, tuple.Get<99>());
7734 EXPECT_EQ(1000, tuple.Get<256>());
7737 // Tests SkipPrefix().
7739 TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7740 const char* const str = "hello";
7742 const char* p = str;
7743 EXPECT_TRUE(SkipPrefix("", &p));
7747 EXPECT_TRUE(SkipPrefix("hell", &p));
7748 EXPECT_EQ(str + 4, p);
7751 TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7752 const char* const str = "world";
7754 const char* p = str;
7755 EXPECT_FALSE(SkipPrefix("W", &p));
7759 EXPECT_FALSE(SkipPrefix("world!", &p));
7763 // Tests ad_hoc_test_result().
7764 TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
7765 const testing::TestResult& test_result =
7766 testing::UnitTest::GetInstance()->ad_hoc_test_result();
7767 EXPECT_FALSE(test_result.Failed());
7770 class DynamicUnitTestFixture : public testing::Test {};
7772 class DynamicTest : public DynamicUnitTestFixture {
7773 void TestBody() override { EXPECT_TRUE(true); }
7776 auto* dynamic_test = testing::RegisterTest(
7777 "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__,
7778 __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });
7780 TEST(RegisterTest, WasRegistered) {
7781 auto* unittest = testing::UnitTest::GetInstance();
7782 for (int i = 0; i < unittest->total_test_suite_count(); ++i) {
7783 auto* tests = unittest->GetTestSuite(i);
7784 if (tests->name() != std::string("DynamicUnitTestFixture")) continue;
7785 for (int j = 0; j < tests->total_test_count(); ++j) {
7786 if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue;
7788 EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE");
7789 EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE");
7794 FAIL() << "Didn't find the test!";