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, OnTestSuiteStart) {
116 streamer_.OnTestSuiteStart(TestSuite("FooTest", "Bar", nullptr, nullptr));
117 EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
120 TEST_F(StreamingListenerTest, OnTestSuiteEnd) {
122 streamer_.OnTestSuiteEnd(TestSuite("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(TestPartResult::kFatalFailure,
141 "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> {};
277 ::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) {
279 for (size_t i = 0; i < vector.size(); i++) {
280 os << vector[i] << " ";
286 // This line tests that we can define tests in an unnamed namespace.
289 TEST(GetRandomSeedFromFlagTest, HandlesZero) {
290 const int seed = GetRandomSeedFromFlag(0);
292 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
295 TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
296 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
297 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
298 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
299 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
300 GetRandomSeedFromFlag(kMaxRandomSeed));
303 TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
304 const int seed1 = GetRandomSeedFromFlag(-1);
306 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
308 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
310 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
313 TEST(GetNextRandomSeedTest, WorksForValidInput) {
314 EXPECT_EQ(2, GetNextRandomSeed(1));
315 EXPECT_EQ(3, GetNextRandomSeed(2));
316 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
317 GetNextRandomSeed(kMaxRandomSeed - 1));
318 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
320 // We deliberately don't test GetNextRandomSeed() with invalid
321 // inputs, as that requires death tests, which are expensive. This
322 // is fine as GetNextRandomSeed() is internal and has a
323 // straightforward definition.
326 static void ClearCurrentTestPartResults() {
327 TestResultAccessor::ClearTestPartResults(
328 GetUnitTestImpl()->current_test_result());
333 TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
334 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
335 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
338 class SubClassOfTest : public Test {};
339 class AnotherSubClassOfTest : public Test {};
341 TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
342 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
343 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
344 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
345 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
346 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
347 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
350 // Verifies that GetTestTypeId() returns the same value, no matter it
351 // is called from inside Google Test or outside of it.
352 TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
353 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
356 // Tests CanonicalizeForStdLibVersioning.
358 using ::testing::internal::CanonicalizeForStdLibVersioning;
360 TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) {
361 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind"));
362 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_"));
363 EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo"));
364 EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x"));
365 EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x"));
366 EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x"));
369 TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
370 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind"));
371 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_"));
373 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind"));
374 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_"));
376 EXPECT_EQ("std::bind",
377 CanonicalizeForStdLibVersioning("std::__google::bind"));
378 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_"));
381 // Tests FormatTimeInMillisAsSeconds().
383 TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
384 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
387 TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
388 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
389 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
390 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
391 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
392 EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
395 TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
396 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
397 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
398 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
399 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
400 EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
403 // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
404 // for particular dates below was verified in Python using
405 // datetime.datetime.fromutctimestamp(<timestamp>/1000).
407 // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
408 // have to set up a particular timezone to obtain predictable results.
409 class FormatEpochTimeInMillisAsIso8601Test : public Test {
411 // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
412 // 32 bits, even when 64-bit integer types are available. We have to
413 // force the constants to have a 64-bit type here.
414 static const TimeInMillis kMillisPerSec = 1000;
417 void SetUp() override {
420 GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
421 if (getenv("TZ")) saved_tz_ = strdup(getenv("TZ"));
422 GTEST_DISABLE_MSC_DEPRECATED_POP_()
424 // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
425 // cannot use the local time zone because the function's output depends
427 SetTimeZone("UTC+00");
430 void TearDown() override {
431 SetTimeZone(saved_tz_);
432 free(const_cast<char*>(saved_tz_));
436 static void SetTimeZone(const char* time_zone) {
437 // tzset() distinguishes between the TZ variable being present and empty
438 // and not being present, so we have to consider the case of time_zone
440 #if _MSC_VER || GTEST_OS_WINDOWS_MINGW
441 // ...Unless it's MSVC, whose standard library's _putenv doesn't
442 // distinguish between an empty and a missing variable.
443 const std::string env_var =
444 std::string("TZ=") + (time_zone ? time_zone : "");
445 _putenv(env_var.c_str());
446 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
448 GTEST_DISABLE_MSC_WARNINGS_POP_()
450 #if GTEST_OS_LINUX_ANDROID && __ANDROID_API__ < 21
451 // Work around KitKat bug in tzset by setting "UTC" before setting "UTC+00".
452 // See https://github.com/android/ndk/issues/1604.
453 setenv("TZ", "UTC", 1);
457 setenv(("TZ"), time_zone, 1);
465 const char* saved_tz_;
468 const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
470 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
471 EXPECT_EQ("2011-10-31T18:52:42.000",
472 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
475 TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
476 EXPECT_EQ("2011-10-31T18:52:42.234",
477 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
480 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
481 EXPECT_EQ("2011-09-03T05:07:02.000",
482 FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
485 TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
486 EXPECT_EQ("2011-09-28T17:08:22.000",
487 FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
490 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
491 EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
495 // Silences warnings: "Condition is always true", "Unreachable code"
496 #pragma option push -w-ccc -w-rch
499 // Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal
500 // when the RHS is a pointer type.
501 TEST(NullLiteralTest, LHSAllowsNullLiterals) {
502 EXPECT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
503 ASSERT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
504 EXPECT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
505 ASSERT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
506 EXPECT_EQ(nullptr, static_cast<void*>(nullptr));
507 ASSERT_EQ(nullptr, static_cast<void*>(nullptr));
509 const int* const p = nullptr;
510 EXPECT_EQ(0, p); // NOLINT
511 ASSERT_EQ(0, p); // NOLINT
512 EXPECT_EQ(NULL, p); // NOLINT
513 ASSERT_EQ(NULL, p); // NOLINT
514 EXPECT_EQ(nullptr, p);
515 ASSERT_EQ(nullptr, p);
518 struct ConvertToAll {
519 template <typename T>
520 operator T() const { // NOLINT
525 struct ConvertToPointer {
527 operator T*() const { // NOLINT
532 struct ConvertToAllButNoPointers {
533 template <typename T,
534 typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0>
535 operator T() const { // NOLINT
541 inline bool operator==(MyType const&, MyType const&) { return true; }
543 TEST(NullLiteralTest, ImplicitConversion) {
544 EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr));
545 #if !defined(__GNUC__) || defined(__clang__)
546 // Disabled due to GCC bug gcc.gnu.org/PR89580
547 EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr));
549 EXPECT_EQ(ConvertToAll{}, MyType{});
550 EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{});
554 #pragma clang diagnostic push
555 #if __has_warning("-Wzero-as-null-pointer-constant")
556 #pragma clang diagnostic error "-Wzero-as-null-pointer-constant"
560 TEST(NullLiteralTest, NoConversionNoWarning) {
561 // Test that gtests detection and handling of null pointer constants
562 // doesn't trigger a warning when '0' isn't actually used as null.
568 #pragma clang diagnostic pop
572 // Restores warnings after previous "#pragma option push" suppressed them.
577 // Tests CodePointToUtf8().
579 // Tests that the NUL character L'\0' is encoded correctly.
580 TEST(CodePointToUtf8Test, CanEncodeNul) {
581 EXPECT_EQ("", CodePointToUtf8(L'\0'));
584 // Tests that ASCII characters are encoded correctly.
585 TEST(CodePointToUtf8Test, CanEncodeAscii) {
586 EXPECT_EQ("a", CodePointToUtf8(L'a'));
587 EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
588 EXPECT_EQ("&", CodePointToUtf8(L'&'));
589 EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
592 // Tests that Unicode code-points that have 8 to 11 bits are encoded
593 // as 110xxxxx 10xxxxxx.
594 TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
595 // 000 1101 0011 => 110-00011 10-010011
596 EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
598 // 101 0111 0110 => 110-10101 10-110110
599 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
600 // in wide strings and wide chars. In order to accommodate them, we have to
601 // introduce such character constants as integers.
602 EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576)));
605 // Tests that Unicode code-points that have 12 to 16 bits are encoded
606 // as 1110xxxx 10xxxxxx 10xxxxxx.
607 TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
608 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
609 EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
611 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
612 EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
615 #if !GTEST_WIDE_STRING_USES_UTF16_
616 // Tests in this group require a wchar_t to hold > 16 bits, and thus
617 // are skipped on Windows, and Cygwin, where a wchar_t is
618 // 16-bit wide. This code may not compile on those systems.
620 // Tests that Unicode code-points that have 17 to 21 bits are encoded
621 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
622 TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
623 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
624 EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
626 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
627 EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
629 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
630 EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
633 // Tests that encoding an invalid code-point generates the expected result.
634 TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
635 EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
638 #endif // !GTEST_WIDE_STRING_USES_UTF16_
640 // Tests WideStringToUtf8().
642 // Tests that the NUL character L'\0' is encoded correctly.
643 TEST(WideStringToUtf8Test, CanEncodeNul) {
644 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
645 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
648 // Tests that ASCII strings are encoded correctly.
649 TEST(WideStringToUtf8Test, CanEncodeAscii) {
650 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
651 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
652 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
653 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
656 // Tests that Unicode code-points that have 8 to 11 bits are encoded
657 // as 110xxxxx 10xxxxxx.
658 TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
659 // 000 1101 0011 => 110-00011 10-010011
660 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
661 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
663 // 101 0111 0110 => 110-10101 10-110110
664 const wchar_t s[] = {0x576, '\0'};
665 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
666 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
669 // Tests that Unicode code-points that have 12 to 16 bits are encoded
670 // as 1110xxxx 10xxxxxx 10xxxxxx.
671 TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
672 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
673 const wchar_t s1[] = {0x8D3, '\0'};
674 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
675 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
677 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
678 const wchar_t s2[] = {0xC74D, '\0'};
679 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
680 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
683 // Tests that the conversion stops when the function encounters \0 character.
684 TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
685 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
688 // Tests that the conversion stops when the function reaches the limit
689 // specified by the 'length' parameter.
690 TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
691 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
694 #if !GTEST_WIDE_STRING_USES_UTF16_
695 // Tests that Unicode code-points that have 17 to 21 bits are encoded
696 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
697 // on the systems using UTF-16 encoding.
698 TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
699 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
700 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
701 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
703 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
704 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
705 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
708 // Tests that encoding an invalid code-point generates the expected result.
709 TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
710 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
711 WideStringToUtf8(L"\xABCDFF", -1).c_str());
713 #else // !GTEST_WIDE_STRING_USES_UTF16_
714 // Tests that surrogate pairs are encoded correctly on the systems using
715 // UTF-16 encoding in the wide strings.
716 TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
717 const wchar_t s[] = {0xD801, 0xDC00, '\0'};
718 EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
721 // Tests that encoding an invalid UTF-16 surrogate pair
722 // generates the expected result.
723 TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
724 // Leading surrogate is at the end of the string.
725 const wchar_t s1[] = {0xD800, '\0'};
726 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
727 // Leading surrogate is not followed by the trailing surrogate.
728 const wchar_t s2[] = {0xD800, 'M', '\0'};
729 EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
730 // Trailing surrogate appearas without a leading surrogate.
731 const wchar_t s3[] = {0xDC00, 'P', 'Q', 'R', '\0'};
732 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
734 #endif // !GTEST_WIDE_STRING_USES_UTF16_
736 // Tests that codepoint concatenation works correctly.
737 #if !GTEST_WIDE_STRING_USES_UTF16_
738 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
739 const wchar_t s[] = {0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
747 WideStringToUtf8(s, -1).c_str());
750 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
751 const wchar_t s[] = {0xC74D, '\n', 0x576, 0x8D3, '\0'};
757 WideStringToUtf8(s, -1).c_str());
759 #endif // !GTEST_WIDE_STRING_USES_UTF16_
761 // Tests the Random class.
763 TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
764 testing::internal::Random random(42);
765 EXPECT_DEATH_IF_SUPPORTED(random.Generate(0),
766 "Cannot generate a number in the range \\[0, 0\\)");
767 EXPECT_DEATH_IF_SUPPORTED(
768 random.Generate(testing::internal::Random::kMaxRange + 1),
769 "Generation of a number in \\[0, 2147483649\\) was requested, "
770 "but this can only generate numbers in \\[0, 2147483648\\)");
773 TEST(RandomTest, GeneratesNumbersWithinRange) {
774 constexpr uint32_t kRange = 10000;
775 testing::internal::Random random(12345);
776 for (int i = 0; i < 10; i++) {
777 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
780 testing::internal::Random random2(testing::internal::Random::kMaxRange);
781 for (int i = 0; i < 10; i++) {
782 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
786 TEST(RandomTest, RepeatsWhenReseeded) {
787 constexpr int kSeed = 123;
788 constexpr int kArraySize = 10;
789 constexpr uint32_t kRange = 10000;
790 uint32_t values[kArraySize];
792 testing::internal::Random random(kSeed);
793 for (int i = 0; i < kArraySize; i++) {
794 values[i] = random.Generate(kRange);
797 random.Reseed(kSeed);
798 for (int i = 0; i < kArraySize; i++) {
799 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
803 // Tests STL container utilities.
807 static bool IsPositive(int n) { return n > 0; }
809 TEST(ContainerUtilityTest, CountIf) {
811 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
815 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
820 EXPECT_EQ(2, CountIf(v, IsPositive));
825 static int g_sum = 0;
826 static void Accumulate(int n) { g_sum += n; }
828 TEST(ContainerUtilityTest, ForEach) {
831 ForEach(v, Accumulate);
832 EXPECT_EQ(0, g_sum); // Works for an empty container;
836 ForEach(v, Accumulate);
837 EXPECT_EQ(1, g_sum); // Works for a container with one element.
842 ForEach(v, Accumulate);
843 EXPECT_EQ(321, g_sum);
846 // Tests GetElementOr().
847 TEST(ContainerUtilityTest, GetElementOr) {
849 EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
853 EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
854 EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
855 EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
856 EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
859 TEST(ContainerUtilityDeathTest, ShuffleRange) {
864 testing::internal::Random random(1);
866 EXPECT_DEATH_IF_SUPPORTED(
867 ShuffleRange(&random, -1, 1, &a),
868 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
869 EXPECT_DEATH_IF_SUPPORTED(
870 ShuffleRange(&random, 4, 4, &a),
871 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
872 EXPECT_DEATH_IF_SUPPORTED(
873 ShuffleRange(&random, 3, 2, &a),
874 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
875 EXPECT_DEATH_IF_SUPPORTED(
876 ShuffleRange(&random, 3, 4, &a),
877 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
880 class VectorShuffleTest : public Test {
882 static const size_t kVectorSize = 20;
884 VectorShuffleTest() : random_(1) {
885 for (int i = 0; i < static_cast<int>(kVectorSize); i++) {
886 vector_.push_back(i);
890 static bool VectorIsCorrupt(const TestingVector& vector) {
891 if (kVectorSize != vector.size()) {
895 bool found_in_vector[kVectorSize] = {false};
896 for (size_t i = 0; i < vector.size(); i++) {
897 const int e = vector[i];
898 if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {
901 found_in_vector[e] = true;
904 // Vector size is correct, elements' range is correct, no
905 // duplicate elements. Therefore no corruption has occurred.
909 static bool VectorIsNotCorrupt(const TestingVector& vector) {
910 return !VectorIsCorrupt(vector);
913 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
914 for (int i = begin; i < end; i++) {
915 if (i != vector[static_cast<size_t>(i)]) {
922 static bool RangeIsUnshuffled(const TestingVector& vector, int begin,
924 return !RangeIsShuffled(vector, begin, end);
927 static bool VectorIsShuffled(const TestingVector& vector) {
928 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
931 static bool VectorIsUnshuffled(const TestingVector& vector) {
932 return !VectorIsShuffled(vector);
935 testing::internal::Random random_;
936 TestingVector vector_;
937 }; // class VectorShuffleTest
939 const size_t VectorShuffleTest::kVectorSize;
941 TEST_F(VectorShuffleTest, HandlesEmptyRange) {
942 // Tests an empty range at the beginning...
943 ShuffleRange(&random_, 0, 0, &vector_);
944 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
945 ASSERT_PRED1(VectorIsUnshuffled, vector_);
947 // ...in the middle...
948 ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2, &vector_);
949 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
950 ASSERT_PRED1(VectorIsUnshuffled, vector_);
953 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
954 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
955 ASSERT_PRED1(VectorIsUnshuffled, vector_);
957 // ...and past the end.
958 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
959 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
960 ASSERT_PRED1(VectorIsUnshuffled, vector_);
963 TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
964 // Tests a size one range at the beginning...
965 ShuffleRange(&random_, 0, 1, &vector_);
966 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
967 ASSERT_PRED1(VectorIsUnshuffled, vector_);
969 // ...in the middle...
970 ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2 + 1, &vector_);
971 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
972 ASSERT_PRED1(VectorIsUnshuffled, vector_);
974 // ...and at the end.
975 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
976 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
977 ASSERT_PRED1(VectorIsUnshuffled, vector_);
980 // Because we use our own random number generator and a fixed seed,
981 // we can guarantee that the following "random" tests will succeed.
983 TEST_F(VectorShuffleTest, ShufflesEntireVector) {
984 Shuffle(&random_, &vector_);
985 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
986 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
988 // Tests the first and last elements in particular to ensure that
989 // there are no off-by-one problems in our shuffle algorithm.
990 EXPECT_NE(0, vector_[0]);
991 EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);
994 TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
995 const int kRangeSize = kVectorSize / 2;
997 ShuffleRange(&random_, 0, kRangeSize, &vector_);
999 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1000 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
1001 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize,
1002 static_cast<int>(kVectorSize));
1005 TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
1006 const int kRangeSize = kVectorSize / 2;
1007 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
1009 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1010 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1011 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize,
1012 static_cast<int>(kVectorSize));
1015 TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
1016 const int kRangeSize = static_cast<int>(kVectorSize) / 3;
1017 ShuffleRange(&random_, kRangeSize, 2 * kRangeSize, &vector_);
1019 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1020 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1021 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2 * kRangeSize);
1022 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,
1023 static_cast<int>(kVectorSize));
1026 TEST_F(VectorShuffleTest, ShufflesRepeatably) {
1027 TestingVector vector2;
1028 for (size_t i = 0; i < kVectorSize; i++) {
1029 vector2.push_back(static_cast<int>(i));
1032 random_.Reseed(1234);
1033 Shuffle(&random_, &vector_);
1034 random_.Reseed(1234);
1035 Shuffle(&random_, &vector2);
1037 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1038 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
1040 for (size_t i = 0; i < kVectorSize; i++) {
1041 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
1045 // Tests the size of the AssertHelper class.
1047 TEST(AssertHelperTest, AssertHelperIsSmall) {
1048 // To avoid breaking clients that use lots of assertions in one
1049 // function, we cannot grow the size of AssertHelper.
1050 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
1053 // Tests String::EndsWithCaseInsensitive().
1054 TEST(StringTest, EndsWithCaseInsensitive) {
1055 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
1056 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
1057 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
1058 EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
1060 EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
1061 EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
1062 EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
1065 // C++Builder's preprocessor is buggy; it fails to expand macros that
1066 // appear in macro parameters after wide char literals. Provide an alias
1067 // for NULL as a workaround.
1068 static const wchar_t* const kNull = nullptr;
1070 // Tests String::CaseInsensitiveWideCStringEquals
1071 TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1072 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr));
1073 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1074 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1075 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1076 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
1077 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1078 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1079 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1082 #if GTEST_OS_WINDOWS
1084 // Tests String::ShowWideCString().
1085 TEST(StringTest, ShowWideCString) {
1086 EXPECT_STREQ("(null)", 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() { FAIL() << "Expected fatal failure."; }
1138 static void AddNonfatalFailure() {
1139 ADD_FAILURE() << "Expected non-fatal failure.";
1142 class ScopedFakeTestPartResultReporterTest : public Test {
1143 public: // Must be public and not protected due to a bug in g++ 3.4.2.
1144 enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
1145 static void AddFailure(FailureMode failure) {
1146 if (failure == FATAL_FAILURE) {
1149 AddNonfatalFailure();
1154 // Tests that ScopedFakeTestPartResultReporter intercepts test
1156 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
1157 TestPartResultArray results;
1159 ScopedFakeTestPartResultReporter reporter(
1160 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1162 AddFailure(NONFATAL_FAILURE);
1163 AddFailure(FATAL_FAILURE);
1166 EXPECT_EQ(2, results.size());
1167 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1168 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1171 TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1172 TestPartResultArray results;
1174 // Tests, that the deprecated constructor still works.
1175 ScopedFakeTestPartResultReporter reporter(&results);
1176 AddFailure(NONFATAL_FAILURE);
1178 EXPECT_EQ(1, results.size());
1181 #if GTEST_IS_THREADSAFE
1183 class ScopedFakeTestPartResultReporterWithThreadsTest
1184 : public ScopedFakeTestPartResultReporterTest {
1186 static void AddFailureInOtherThread(FailureMode failure) {
1187 ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
1192 TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1193 InterceptsTestFailuresInAllThreads) {
1194 TestPartResultArray results;
1196 ScopedFakeTestPartResultReporter reporter(
1197 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1198 AddFailure(NONFATAL_FAILURE);
1199 AddFailure(FATAL_FAILURE);
1200 AddFailureInOtherThread(NONFATAL_FAILURE);
1201 AddFailureInOtherThread(FATAL_FAILURE);
1204 EXPECT_EQ(4, results.size());
1205 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1206 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1207 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1208 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1211 #endif // GTEST_IS_THREADSAFE
1213 // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1214 // work even if the failure is generated in a called function rather than
1215 // the current context.
1217 typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
1219 TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1220 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
1223 TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1224 EXPECT_FATAL_FAILURE(AddFatalFailure(),
1225 ::std::string("Expected fatal failure."));
1228 TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1229 // We have another test below to verify that the macro catches fatal
1230 // failures generated on another thread.
1231 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
1232 "Expected fatal failure.");
1236 // Silences warnings: "Condition is always true"
1237 #pragma option push -w-ccc
1240 // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1241 // function even when the statement in it contains ASSERT_*.
1243 int NonVoidFunction() {
1244 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1245 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1249 TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1253 // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1254 // current function even though 'statement' generates a fatal failure.
1256 void DoesNotAbortHelper(bool* aborted) {
1257 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1258 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1264 // Restores warnings after previous "#pragma option push" suppressed them.
1268 TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1269 bool aborted = true;
1270 DoesNotAbortHelper(&aborted);
1271 EXPECT_FALSE(aborted);
1274 // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1275 // statement that contains a macro which expands to code containing an
1276 // unprotected comma.
1278 static int global_var = 0;
1279 #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1281 TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1282 #ifndef __BORLANDC__
1283 // ICE's in C++Builder.
1284 EXPECT_FATAL_FAILURE(
1286 GTEST_USE_UNPROTECTED_COMMA_;
1292 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(
1294 GTEST_USE_UNPROTECTED_COMMA_;
1300 // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1302 typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1304 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1305 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), "Expected non-fatal failure.");
1308 TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1309 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1310 ::std::string("Expected non-fatal failure."));
1313 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1314 // We have another test below to verify that the macro catches
1315 // non-fatal failures generated on another thread.
1316 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
1317 "Expected non-fatal failure.");
1320 // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1321 // statement that contains a macro which expands to code containing an
1322 // unprotected comma.
1323 TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1324 EXPECT_NONFATAL_FAILURE(
1326 GTEST_USE_UNPROTECTED_COMMA_;
1327 AddNonfatalFailure();
1331 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1333 GTEST_USE_UNPROTECTED_COMMA_;
1334 AddNonfatalFailure();
1339 #if GTEST_IS_THREADSAFE
1341 typedef ScopedFakeTestPartResultReporterWithThreadsTest
1342 ExpectFailureWithThreadsTest;
1344 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1345 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1346 "Expected fatal failure.");
1349 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1350 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1351 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1354 #endif // GTEST_IS_THREADSAFE
1356 // Tests the TestProperty class.
1358 TEST(TestPropertyTest, ConstructorWorks) {
1359 const TestProperty property("key", "value");
1360 EXPECT_STREQ("key", property.key());
1361 EXPECT_STREQ("value", property.value());
1364 TEST(TestPropertyTest, SetValue) {
1365 TestProperty property("key", "value_1");
1366 EXPECT_STREQ("key", property.key());
1367 property.SetValue("value_2");
1368 EXPECT_STREQ("key", property.key());
1369 EXPECT_STREQ("value_2", property.value());
1372 // Tests the TestResult class
1374 // The test fixture for testing TestResult.
1375 class TestResultTest : public Test {
1377 typedef std::vector<TestPartResult> TPRVector;
1379 // We make use of 2 TestPartResult objects,
1380 TestPartResult *pr1, *pr2;
1382 // ... and 3 TestResult objects.
1383 TestResult *r0, *r1, *r2;
1385 void SetUp() override {
1386 // pr1 is for success.
1387 pr1 = new TestPartResult(TestPartResult::kSuccess, "foo/bar.cc", 10,
1390 // pr2 is for fatal failure.
1391 pr2 = new TestPartResult(TestPartResult::kFatalFailure, "foo/bar.cc",
1392 -1, // This line number means "unknown"
1395 // Creates the TestResult objects.
1396 r0 = new TestResult();
1397 r1 = new TestResult();
1398 r2 = new TestResult();
1400 // In order to test TestResult, we need to modify its internal
1401 // state, in particular the TestPartResult vector it holds.
1402 // test_part_results() returns a const reference to this vector.
1403 // We cast it to a non-const object s.t. it can be modified
1404 TPRVector* results1 =
1405 const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r1));
1406 TPRVector* results2 =
1407 const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r2));
1409 // r0 is an empty TestResult.
1411 // r1 contains a single SUCCESS TestPartResult.
1412 results1->push_back(*pr1);
1414 // r2 contains a SUCCESS, and a FAILURE.
1415 results2->push_back(*pr1);
1416 results2->push_back(*pr2);
1419 void TearDown() override {
1428 // Helper that compares two TestPartResults.
1429 static void CompareTestPartResult(const TestPartResult& expected,
1430 const TestPartResult& actual) {
1431 EXPECT_EQ(expected.type(), actual.type());
1432 EXPECT_STREQ(expected.file_name(), actual.file_name());
1433 EXPECT_EQ(expected.line_number(), actual.line_number());
1434 EXPECT_STREQ(expected.summary(), actual.summary());
1435 EXPECT_STREQ(expected.message(), actual.message());
1436 EXPECT_EQ(expected.passed(), actual.passed());
1437 EXPECT_EQ(expected.failed(), actual.failed());
1438 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1439 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
1443 // Tests TestResult::total_part_count().
1444 TEST_F(TestResultTest, total_part_count) {
1445 ASSERT_EQ(0, r0->total_part_count());
1446 ASSERT_EQ(1, r1->total_part_count());
1447 ASSERT_EQ(2, r2->total_part_count());
1450 // Tests TestResult::Passed().
1451 TEST_F(TestResultTest, Passed) {
1452 ASSERT_TRUE(r0->Passed());
1453 ASSERT_TRUE(r1->Passed());
1454 ASSERT_FALSE(r2->Passed());
1457 // Tests TestResult::Failed().
1458 TEST_F(TestResultTest, Failed) {
1459 ASSERT_FALSE(r0->Failed());
1460 ASSERT_FALSE(r1->Failed());
1461 ASSERT_TRUE(r2->Failed());
1464 // Tests TestResult::GetTestPartResult().
1466 typedef TestResultTest TestResultDeathTest;
1468 TEST_F(TestResultDeathTest, GetTestPartResult) {
1469 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1470 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1471 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1472 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
1475 // Tests TestResult has no properties when none are added.
1476 TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1477 TestResult test_result;
1478 ASSERT_EQ(0, test_result.test_property_count());
1481 // Tests TestResult has the expected property when added.
1482 TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1483 TestResult test_result;
1484 TestProperty property("key_1", "1");
1485 TestResultAccessor::RecordProperty(&test_result, "testcase", property);
1486 ASSERT_EQ(1, test_result.test_property_count());
1487 const TestProperty& actual_property = test_result.GetTestProperty(0);
1488 EXPECT_STREQ("key_1", actual_property.key());
1489 EXPECT_STREQ("1", actual_property.value());
1492 // Tests TestResult has multiple properties when added.
1493 TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1494 TestResult test_result;
1495 TestProperty property_1("key_1", "1");
1496 TestProperty property_2("key_2", "2");
1497 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1498 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1499 ASSERT_EQ(2, test_result.test_property_count());
1500 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1501 EXPECT_STREQ("key_1", actual_property_1.key());
1502 EXPECT_STREQ("1", actual_property_1.value());
1504 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1505 EXPECT_STREQ("key_2", actual_property_2.key());
1506 EXPECT_STREQ("2", actual_property_2.value());
1509 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
1510 TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1511 TestResult test_result;
1512 TestProperty property_1_1("key_1", "1");
1513 TestProperty property_2_1("key_2", "2");
1514 TestProperty property_1_2("key_1", "12");
1515 TestProperty property_2_2("key_2", "22");
1516 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
1517 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
1518 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
1519 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
1521 ASSERT_EQ(2, test_result.test_property_count());
1522 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1523 EXPECT_STREQ("key_1", actual_property_1.key());
1524 EXPECT_STREQ("12", actual_property_1.value());
1526 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1527 EXPECT_STREQ("key_2", actual_property_2.key());
1528 EXPECT_STREQ("22", actual_property_2.value());
1531 // Tests TestResult::GetTestProperty().
1532 TEST(TestResultPropertyTest, GetTestProperty) {
1533 TestResult test_result;
1534 TestProperty property_1("key_1", "1");
1535 TestProperty property_2("key_2", "2");
1536 TestProperty property_3("key_3", "3");
1537 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1538 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1539 TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
1541 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1542 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1543 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
1545 EXPECT_STREQ("key_1", fetched_property_1.key());
1546 EXPECT_STREQ("1", fetched_property_1.value());
1548 EXPECT_STREQ("key_2", fetched_property_2.key());
1549 EXPECT_STREQ("2", fetched_property_2.value());
1551 EXPECT_STREQ("key_3", fetched_property_3.key());
1552 EXPECT_STREQ("3", fetched_property_3.value());
1554 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1555 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
1558 // Tests the Test class.
1560 // It's difficult to test every public method of this class (we are
1561 // already stretching the limit of Google Test by using it to test itself!).
1562 // Fortunately, we don't have to do that, as we are already testing
1563 // the functionalities of the Test class extensively by using Google Test
1566 // Therefore, this section only contains one test.
1568 // Tests that GTestFlagSaver works on Windows and Mac.
1570 class GTestFlagSaverTest : public Test {
1572 // Saves the Google Test flags such that we can restore them later, and
1573 // then sets them to their default values. This will be called
1574 // before the first test in this test case is run.
1575 static void SetUpTestSuite() {
1576 saver_ = new GTestFlagSaver;
1578 GTEST_FLAG_SET(also_run_disabled_tests, false);
1579 GTEST_FLAG_SET(break_on_failure, false);
1580 GTEST_FLAG_SET(catch_exceptions, false);
1581 GTEST_FLAG_SET(death_test_use_fork, false);
1582 GTEST_FLAG_SET(color, "auto");
1583 GTEST_FLAG_SET(fail_fast, false);
1584 GTEST_FLAG_SET(filter, "");
1585 GTEST_FLAG_SET(list_tests, false);
1586 GTEST_FLAG_SET(output, "");
1587 GTEST_FLAG_SET(brief, false);
1588 GTEST_FLAG_SET(print_time, true);
1589 GTEST_FLAG_SET(random_seed, 0);
1590 GTEST_FLAG_SET(repeat, 1);
1591 GTEST_FLAG_SET(recreate_environments_when_repeating, true);
1592 GTEST_FLAG_SET(shuffle, false);
1593 GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
1594 GTEST_FLAG_SET(stream_result_to, "");
1595 GTEST_FLAG_SET(throw_on_failure, false);
1598 // Restores the Google Test flags that the tests have modified. This will
1599 // be called after the last test in this test case is run.
1600 static void TearDownTestSuite() {
1605 // Verifies that the Google Test flags have their default values, and then
1606 // modifies each of them.
1607 void VerifyAndModifyFlags() {
1608 EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests));
1609 EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure));
1610 EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions));
1611 EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str());
1612 EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork));
1613 EXPECT_FALSE(GTEST_FLAG_GET(fail_fast));
1614 EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str());
1615 EXPECT_FALSE(GTEST_FLAG_GET(list_tests));
1616 EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str());
1617 EXPECT_FALSE(GTEST_FLAG_GET(brief));
1618 EXPECT_TRUE(GTEST_FLAG_GET(print_time));
1619 EXPECT_EQ(0, GTEST_FLAG_GET(random_seed));
1620 EXPECT_EQ(1, GTEST_FLAG_GET(repeat));
1621 EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating));
1622 EXPECT_FALSE(GTEST_FLAG_GET(shuffle));
1623 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth));
1624 EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str());
1625 EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure));
1627 GTEST_FLAG_SET(also_run_disabled_tests, true);
1628 GTEST_FLAG_SET(break_on_failure, true);
1629 GTEST_FLAG_SET(catch_exceptions, true);
1630 GTEST_FLAG_SET(color, "no");
1631 GTEST_FLAG_SET(death_test_use_fork, true);
1632 GTEST_FLAG_SET(fail_fast, true);
1633 GTEST_FLAG_SET(filter, "abc");
1634 GTEST_FLAG_SET(list_tests, true);
1635 GTEST_FLAG_SET(output, "xml:foo.xml");
1636 GTEST_FLAG_SET(brief, true);
1637 GTEST_FLAG_SET(print_time, false);
1638 GTEST_FLAG_SET(random_seed, 1);
1639 GTEST_FLAG_SET(repeat, 100);
1640 GTEST_FLAG_SET(recreate_environments_when_repeating, false);
1641 GTEST_FLAG_SET(shuffle, true);
1642 GTEST_FLAG_SET(stack_trace_depth, 1);
1643 GTEST_FLAG_SET(stream_result_to, "localhost:1234");
1644 GTEST_FLAG_SET(throw_on_failure, true);
1648 // For saving Google Test flags during this test case.
1649 static GTestFlagSaver* saver_;
1652 GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;
1654 // Google Test doesn't guarantee the order of tests. The following two
1655 // tests are designed to work regardless of their order.
1657 // Modifies the Google Test flags in the test body.
1658 TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); }
1660 // Verifies that the Google Test flags in the body of the previous test were
1661 // restored to their original values.
1662 TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); }
1664 // Sets an environment variable with the given name to the given
1665 // value. If the value argument is "", unsets the environment
1666 // variable. The caller must ensure that both arguments are not NULL.
1667 static void SetEnv(const char* name, const char* value) {
1668 #if GTEST_OS_WINDOWS_MOBILE
1669 // Environment variables are not supported on Windows CE.
1671 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1672 // C++Builder's putenv only stores a pointer to its parameter; we have to
1673 // ensure that the string remains valid as long as it might be needed.
1674 // We use an std::map to do so.
1675 static std::map<std::string, std::string*> added_env;
1677 // Because putenv stores a pointer to the string buffer, we can't delete the
1678 // previous string (if present) until after it's replaced.
1679 std::string* prev_env = NULL;
1680 if (added_env.find(name) != added_env.end()) {
1681 prev_env = added_env[name];
1684 new std::string((Message() << name << "=" << value).GetString());
1686 // The standard signature of putenv accepts a 'char*' argument. Other
1687 // implementations, like C++Builder's, accept a 'const char*'.
1688 // We cast away the 'const' since that would work for both variants.
1689 putenv(const_cast<char*>(added_env[name]->c_str()));
1691 #elif GTEST_OS_WINDOWS // If we are on Windows proper.
1692 _putenv((Message() << name << "=" << value).GetString().c_str());
1694 if (*value == '\0') {
1697 setenv(name, value, 1);
1699 #endif // GTEST_OS_WINDOWS_MOBILE
1702 #if !GTEST_OS_WINDOWS_MOBILE
1703 // Environment variables are not supported on Windows CE.
1705 using testing::internal::Int32FromGTestEnv;
1707 // Tests Int32FromGTestEnv().
1709 // Tests that Int32FromGTestEnv() returns the default value when the
1710 // environment variable is not set.
1711 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1712 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1713 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1716 #if !defined(GTEST_GET_INT32_FROM_ENV_)
1718 // Tests that Int32FromGTestEnv() returns the default value when the
1719 // environment variable overflows as an Int32.
1720 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1721 printf("(expecting 2 warnings)\n");
1723 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1724 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1726 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1727 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1730 // Tests that Int32FromGTestEnv() returns the default value when the
1731 // environment variable does not represent a valid decimal integer.
1732 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1733 printf("(expecting 2 warnings)\n");
1735 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1736 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1738 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1739 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1742 #endif // !defined(GTEST_GET_INT32_FROM_ENV_)
1744 // Tests that Int32FromGTestEnv() parses and returns the value of the
1745 // environment variable when it represents a valid decimal integer in
1746 // the range of an Int32.
1747 TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1748 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1749 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1751 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1752 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1754 #endif // !GTEST_OS_WINDOWS_MOBILE
1756 // Tests ParseFlag().
1758 // Tests that ParseInt32Flag() returns false and doesn't change the
1759 // output value when the flag has wrong format
1760 TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1761 int32_t value = 123;
1762 EXPECT_FALSE(ParseFlag("--a=100", "b", &value));
1763 EXPECT_EQ(123, value);
1765 EXPECT_FALSE(ParseFlag("a=100", "a", &value));
1766 EXPECT_EQ(123, value);
1769 // Tests that ParseFlag() returns false and doesn't change the
1770 // output value when the flag overflows as an Int32.
1771 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1772 printf("(expecting 2 warnings)\n");
1774 int32_t value = 123;
1775 EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value));
1776 EXPECT_EQ(123, value);
1778 EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value));
1779 EXPECT_EQ(123, value);
1782 // Tests that ParseInt32Flag() returns false and doesn't change the
1783 // output value when the flag does not represent a valid decimal
1785 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1786 printf("(expecting 2 warnings)\n");
1788 int32_t value = 123;
1789 EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value));
1790 EXPECT_EQ(123, value);
1792 EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value));
1793 EXPECT_EQ(123, value);
1796 // Tests that ParseInt32Flag() parses the value of the flag and
1797 // returns true when the flag represents a valid decimal integer in
1798 // the range of an Int32.
1799 TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1800 int32_t value = 123;
1801 EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1802 EXPECT_EQ(456, value);
1804 EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value));
1805 EXPECT_EQ(-789, value);
1808 // Tests that Int32FromEnvOrDie() parses the value of the var or
1809 // returns the correct default.
1810 // Environment variables are not supported on Windows CE.
1811 #if !GTEST_OS_WINDOWS_MOBILE
1812 TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1813 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1814 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1815 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1816 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1817 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1819 #endif // !GTEST_OS_WINDOWS_MOBILE
1821 // Tests that Int32FromEnvOrDie() aborts with an error message
1822 // if the variable is not an int32_t.
1823 TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1824 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1825 EXPECT_DEATH_IF_SUPPORTED(
1826 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*");
1829 // Tests that Int32FromEnvOrDie() aborts with an error message
1830 // if the variable cannot be represented by an int32_t.
1831 TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1832 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1833 EXPECT_DEATH_IF_SUPPORTED(
1834 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*");
1837 // Tests that ShouldRunTestOnShard() selects all tests
1838 // where there is 1 shard.
1839 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1840 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1841 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1842 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1843 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1844 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1847 class ShouldShardTest : public testing::Test {
1849 void SetUp() override {
1850 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1851 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1854 void TearDown() override {
1855 SetEnv(index_var_, "");
1856 SetEnv(total_var_, "");
1859 const char* index_var_;
1860 const char* total_var_;
1863 // Tests that sharding is disabled if neither of the environment variables
1865 TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1866 SetEnv(index_var_, "");
1867 SetEnv(total_var_, "");
1869 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1870 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1873 // Tests that sharding is not enabled if total_shards == 1.
1874 TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1875 SetEnv(index_var_, "0");
1876 SetEnv(total_var_, "1");
1877 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1878 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1881 // Tests that sharding is enabled if total_shards > 1 and
1882 // we are not in a death test subprocess.
1883 // Environment variables are not supported on Windows CE.
1884 #if !GTEST_OS_WINDOWS_MOBILE
1885 TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1886 SetEnv(index_var_, "4");
1887 SetEnv(total_var_, "22");
1888 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1889 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1891 SetEnv(index_var_, "8");
1892 SetEnv(total_var_, "9");
1893 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1894 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1896 SetEnv(index_var_, "0");
1897 SetEnv(total_var_, "9");
1898 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1899 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1901 #endif // !GTEST_OS_WINDOWS_MOBILE
1903 // Tests that we exit in error if the sharding values are not valid.
1905 typedef ShouldShardTest ShouldShardDeathTest;
1907 TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
1908 SetEnv(index_var_, "4");
1909 SetEnv(total_var_, "4");
1910 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1912 SetEnv(index_var_, "4");
1913 SetEnv(total_var_, "-2");
1914 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1916 SetEnv(index_var_, "5");
1917 SetEnv(total_var_, "");
1918 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1920 SetEnv(index_var_, "");
1921 SetEnv(total_var_, "5");
1922 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1925 // Tests that ShouldRunTestOnShard is a partition when 5
1927 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1928 // Choose an arbitrary number of tests and shards.
1929 const int num_tests = 17;
1930 const int num_shards = 5;
1932 // Check partitioning: each test should be on exactly 1 shard.
1933 for (int test_id = 0; test_id < num_tests; test_id++) {
1934 int prev_selected_shard_index = -1;
1935 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1936 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1937 if (prev_selected_shard_index < 0) {
1938 prev_selected_shard_index = shard_index;
1940 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1941 << shard_index << " are both selected to run test "
1948 // Check balance: This is not required by the sharding protocol, but is a
1949 // desirable property for performance.
1950 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1951 int num_tests_on_shard = 0;
1952 for (int test_id = 0; test_id < num_tests; test_id++) {
1953 num_tests_on_shard +=
1954 ShouldRunTestOnShard(num_shards, shard_index, test_id);
1956 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1960 // For the same reason we are not explicitly testing everything in the
1961 // Test class, there are no separate tests for the following classes
1962 // (except for some trivial cases):
1964 // TestSuite, UnitTest, UnitTestResultPrinter.
1966 // Similarly, there are no separate tests for the following macros:
1968 // TEST, TEST_F, RUN_ALL_TESTS
1970 TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1971 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr);
1972 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1975 TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
1976 EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
1977 EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
1980 // When a property using a reserved key is supplied to this function, it
1981 // tests that a non-fatal failure is added, a fatal failure is not added,
1982 // and that the property is not recorded.
1983 void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
1984 const TestResult& test_result, const char* key) {
1985 EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
1986 ASSERT_EQ(0, test_result.test_property_count())
1987 << "Property for key '" << key << "' recorded unexpectedly.";
1990 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
1992 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
1993 ASSERT_TRUE(test_info != nullptr);
1994 ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
1998 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2000 const testing::TestSuite* test_suite =
2001 UnitTest::GetInstance()->current_test_suite();
2002 ASSERT_TRUE(test_suite != nullptr);
2003 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2004 test_suite->ad_hoc_test_result(), key);
2007 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2009 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2010 UnitTest::GetInstance()->ad_hoc_test_result(), key);
2013 // Tests that property recording functions in UnitTest outside of tests
2014 // functions correctly. Creating a separate instance of UnitTest ensures it
2015 // is in a state similar to the UnitTest's singleton's between tests.
2016 class UnitTestRecordPropertyTest
2017 : public testing::internal::UnitTestRecordPropertyTestHelper {
2019 static void SetUpTestSuite() {
2020 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2022 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2024 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2026 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2028 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2030 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2033 Test::RecordProperty("test_case_key_1", "1");
2035 const testing::TestSuite* test_suite =
2036 UnitTest::GetInstance()->current_test_suite();
2038 ASSERT_TRUE(test_suite != nullptr);
2040 ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count());
2041 EXPECT_STREQ("test_case_key_1",
2042 test_suite->ad_hoc_test_result().GetTestProperty(0).key());
2044 test_suite->ad_hoc_test_result().GetTestProperty(0).value());
2048 // Tests TestResult has the expected property when added.
2049 TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
2050 UnitTestRecordProperty("key_1", "1");
2052 ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
2054 EXPECT_STREQ("key_1",
2055 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2056 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2059 // Tests TestResult has multiple properties when added.
2060 TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
2061 UnitTestRecordProperty("key_1", "1");
2062 UnitTestRecordProperty("key_2", "2");
2064 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2066 EXPECT_STREQ("key_1",
2067 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2068 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2070 EXPECT_STREQ("key_2",
2071 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2072 EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2075 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
2076 TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
2077 UnitTestRecordProperty("key_1", "1");
2078 UnitTestRecordProperty("key_2", "2");
2079 UnitTestRecordProperty("key_1", "12");
2080 UnitTestRecordProperty("key_2", "22");
2082 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2084 EXPECT_STREQ("key_1",
2085 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2087 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2089 EXPECT_STREQ("key_2",
2090 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2092 unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2095 TEST_F(UnitTestRecordPropertyTest,
2096 AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
2097 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("name");
2098 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2100 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2102 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("status");
2103 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("time");
2104 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2108 TEST_F(UnitTestRecordPropertyTest,
2109 AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
2110 EXPECT_NONFATAL_FAILURE(
2111 Test::RecordProperty("name", "1"),
2112 "'classname', 'name', 'status', 'time', 'type_param', 'value_param',"
2113 " 'file', and 'line' are reserved");
2116 class UnitTestRecordPropertyTestEnvironment : public Environment {
2118 void TearDown() override {
2119 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2121 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2123 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2125 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2127 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2129 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2131 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2133 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2138 // This will test property recording outside of any test or test case.
2139 static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ =
2140 AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
2142 // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2143 // of various arities. They do not attempt to be exhaustive. Rather,
2144 // view them as smoke tests that can be easily reviewed and verified.
2145 // A more complete set of tests for predicate assertions can be found
2146 // in gtest_pred_impl_unittest.cc.
2148 // First, some predicates and predicate-formatters needed by the tests.
2150 // Returns true if and only if the argument is an even number.
2151 bool IsEven(int n) { return (n % 2) == 0; }
2153 // A functor that returns true if and only if the argument is an even number.
2154 struct IsEvenFunctor {
2155 bool operator()(int n) { return IsEven(n); }
2158 // A predicate-formatter function that asserts the argument is an even
2160 AssertionResult AssertIsEven(const char* expr, int n) {
2162 return AssertionSuccess();
2166 msg << expr << " evaluates to " << n << ", which is not even.";
2167 return AssertionFailure(msg);
2170 // A predicate function that returns AssertionResult for use in
2171 // EXPECT/ASSERT_TRUE/FALSE.
2172 AssertionResult ResultIsEven(int n) {
2174 return AssertionSuccess() << n << " is even";
2176 return AssertionFailure() << n << " is odd";
2179 // A predicate function that returns AssertionResult but gives no
2180 // explanation why it succeeds. Needed for testing that
2181 // EXPECT/ASSERT_FALSE handles such functions correctly.
2182 AssertionResult ResultIsEvenNoExplanation(int n) {
2184 return AssertionSuccess();
2186 return AssertionFailure() << n << " is odd";
2189 // A predicate-formatter functor that asserts the argument is an even
2191 struct AssertIsEvenFunctor {
2192 AssertionResult operator()(const char* expr, int n) {
2193 return AssertIsEven(expr, n);
2197 // Returns true if and only if the sum of the arguments is an even number.
2198 bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); }
2200 // A functor that returns true if and only if the sum of the arguments is an
2202 struct SumIsEven3Functor {
2203 bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); }
2206 // A predicate-formatter function that asserts the sum of the
2207 // arguments is an even number.
2208 AssertionResult AssertSumIsEven4(const char* e1, const char* e2, const char* e3,
2209 const char* e4, int n1, int n2, int n3,
2211 const int sum = n1 + n2 + n3 + n4;
2213 return AssertionSuccess();
2217 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " (" << n1 << " + "
2218 << n2 << " + " << n3 << " + " << n4 << ") evaluates to " << sum
2219 << ", which is not even.";
2220 return AssertionFailure(msg);
2223 // A predicate-formatter functor that asserts the sum of the arguments
2224 // is an even number.
2225 struct AssertSumIsEven5Functor {
2226 AssertionResult operator()(const char* e1, const char* e2, const char* e3,
2227 const char* e4, const char* e5, int n1, int n2,
2228 int n3, int n4, int n5) {
2229 const int sum = n1 + n2 + n3 + n4 + n5;
2231 return AssertionSuccess();
2235 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2236 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + "
2237 << n5 << ") evaluates to " << sum << ", which is not even.";
2238 return AssertionFailure(msg);
2242 // Tests unary predicate assertions.
2244 // Tests unary predicate assertions that don't use a custom formatter.
2245 TEST(Pred1Test, WithoutFormat) {
2247 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2248 ASSERT_PRED1(IsEven, 4);
2251 EXPECT_NONFATAL_FAILURE(
2253 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2255 "This failure is expected.");
2256 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), "evaluates to false");
2259 // Tests unary predicate assertions that use a custom formatter.
2260 TEST(Pred1Test, WithFormat) {
2262 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2263 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2264 << "This failure is UNEXPECTED!";
2268 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2269 "n evaluates to 5, which is not even.");
2270 EXPECT_FATAL_FAILURE(
2272 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2274 "This failure is expected.");
2277 // Tests that unary predicate assertions evaluates their arguments
2279 TEST(Pred1Test, SingleEvaluationOnFailure) {
2282 EXPECT_PRED1(IsEven, n++);
2283 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2286 EXPECT_FATAL_FAILURE(
2288 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2289 << "This failure is expected.";
2291 "This failure is expected.");
2292 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2295 // Tests predicate assertions whose arity is >= 2.
2297 // Tests predicate assertions that don't use a custom formatter.
2298 TEST(PredTest, WithoutFormat) {
2300 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2301 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2306 EXPECT_NONFATAL_FAILURE(
2308 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2310 "This failure is expected.");
2311 EXPECT_FATAL_FAILURE(
2313 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2315 "evaluates to false");
2318 // Tests predicate assertions that use a custom formatter.
2319 TEST(PredTest, WithFormat) {
2321 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10)
2322 << "This failure is UNEXPECTED!";
2323 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2330 EXPECT_NONFATAL_FAILURE(
2332 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2334 "evaluates to 13, which is not even.");
2335 EXPECT_FATAL_FAILURE(
2337 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2338 << "This failure is expected.";
2340 "This failure is expected.");
2343 // Tests that predicate assertions evaluates their arguments
2345 TEST(PredTest, SingleEvaluationOnFailure) {
2349 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2350 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2351 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2353 // Another success case.
2358 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), n1++, n2++, n3++, n4++, n5++)
2359 << "This failure is UNEXPECTED!";
2360 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2361 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2362 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2363 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2364 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2368 EXPECT_NONFATAL_FAILURE(
2370 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2371 << "This failure is expected.";
2373 "This failure is expected.");
2374 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2375 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2376 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2378 // Another failure case.
2379 n1 = n2 = n3 = n4 = 0;
2380 EXPECT_NONFATAL_FAILURE(
2382 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2384 "evaluates to 1, which is not even.");
2385 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2386 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2387 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2388 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2391 // Test predicate assertions for sets
2392 TEST(PredTest, ExpectPredEvalFailure) {
2393 std::set<int> set_a = {2, 1, 3, 4, 5};
2394 std::set<int> set_b = {0, 4, 8};
2395 const auto compare_sets = [](std::set<int>, std::set<int>) { return false; };
2396 EXPECT_NONFATAL_FAILURE(
2397 EXPECT_PRED2(compare_sets, set_a, set_b),
2398 "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates "
2399 "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }");
2402 // Some helper functions for testing using overloaded/template
2403 // functions with ASSERT_PREDn and EXPECT_PREDn.
2405 bool IsPositive(double x) { return x > 0; }
2407 template <typename T>
2408 bool IsNegative(T x) {
2412 template <typename T1, typename T2>
2413 bool GreaterThan(T1 x1, T2 x2) {
2417 // Tests that overloaded functions can be used in *_PRED* as long as
2418 // their types are explicitly specified.
2419 TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2420 // C++Builder requires C-style casts rather than static_cast.
2421 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2422 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
2425 // Tests that template functions can be used in *_PRED* as long as
2426 // their types are explicitly specified.
2427 TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2428 EXPECT_PRED1(IsNegative<int>, -5);
2429 // Makes sure that we can handle templates with more than one
2431 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2434 // Some helper functions for testing using overloaded/template
2435 // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2437 AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2438 return n > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
2441 AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2442 return x > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
2445 template <typename T>
2446 AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2447 return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
2450 template <typename T1, typename T2>
2451 AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2452 const T1& x1, const T2& x2) {
2453 return x1 == x2 ? AssertionSuccess()
2454 : AssertionFailure(Message() << "Failure");
2457 // Tests that overloaded functions can be used in *_PRED_FORMAT*
2458 // without explicitly specifying their types.
2459 TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2460 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2461 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2464 // Tests that template functions can be used in *_PRED_FORMAT* without
2465 // explicitly specifying their types.
2466 TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2467 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2468 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2471 // Tests string assertions.
2473 // Tests ASSERT_STREQ with non-NULL arguments.
2474 TEST(StringAssertionTest, ASSERT_STREQ) {
2475 const char* const p1 = "good";
2476 ASSERT_STREQ(p1, p1);
2478 // Let p2 have the same content as p1, but be at a different address.
2479 const char p2[] = "good";
2480 ASSERT_STREQ(p1, p2);
2482 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), " \"bad\"\n \"good\"");
2485 // Tests ASSERT_STREQ with NULL arguments.
2486 TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2487 ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr);
2488 EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null");
2491 // Tests ASSERT_STREQ with NULL arguments.
2492 TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2493 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null");
2496 // Tests ASSERT_STRNE.
2497 TEST(StringAssertionTest, ASSERT_STRNE) {
2498 ASSERT_STRNE("hi", "Hi");
2499 ASSERT_STRNE("Hi", nullptr);
2500 ASSERT_STRNE(nullptr, "Hi");
2501 ASSERT_STRNE("", nullptr);
2502 ASSERT_STRNE(nullptr, "");
2503 ASSERT_STRNE("", "Hi");
2504 ASSERT_STRNE("Hi", "");
2505 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), "\"Hi\" vs \"Hi\"");
2508 // Tests ASSERT_STRCASEEQ.
2509 TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2510 ASSERT_STRCASEEQ("hi", "Hi");
2511 ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);
2513 ASSERT_STRCASEEQ("", "");
2514 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), "Ignoring case");
2517 // Tests ASSERT_STRCASENE.
2518 TEST(StringAssertionTest, ASSERT_STRCASENE) {
2519 ASSERT_STRCASENE("hi1", "Hi2");
2520 ASSERT_STRCASENE("Hi", nullptr);
2521 ASSERT_STRCASENE(nullptr, "Hi");
2522 ASSERT_STRCASENE("", nullptr);
2523 ASSERT_STRCASENE(nullptr, "");
2524 ASSERT_STRCASENE("", "Hi");
2525 ASSERT_STRCASENE("Hi", "");
2526 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), "(ignoring case)");
2529 // Tests *_STREQ on wide strings.
2530 TEST(StringAssertionTest, STREQ_Wide) {
2532 ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr);
2535 ASSERT_STREQ(L"", L"");
2537 // Non-null vs NULL.
2538 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null");
2541 EXPECT_STREQ(L"Hi", L"Hi");
2544 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), "Abc");
2546 // Strings containing wide characters.
2547 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), "abc");
2549 // The streaming variation.
2550 EXPECT_NONFATAL_FAILURE(
2552 EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
2554 "Expected failure");
2557 // Tests *_STRNE on wide strings.
2558 TEST(StringAssertionTest, STRNE_Wide) {
2560 EXPECT_NONFATAL_FAILURE(
2562 EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr);
2567 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), "L\"\"");
2569 // Non-null vs NULL.
2570 ASSERT_STRNE(L"non-null", nullptr);
2573 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), "L\"Hi\"");
2576 EXPECT_STRNE(L"abc", L"Abc");
2578 // Strings containing wide characters.
2579 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), "abc");
2581 // The streaming variation.
2582 ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
2585 // Tests for ::testing::IsSubstring().
2587 // Tests that IsSubstring() returns the correct result when the input
2588 // argument type is const char*.
2589 TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2590 EXPECT_FALSE(IsSubstring("", "", nullptr, "a"));
2591 EXPECT_FALSE(IsSubstring("", "", "b", nullptr));
2592 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2594 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr));
2595 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2598 // Tests that IsSubstring() returns the correct result when the input
2599 // argument type is const wchar_t*.
2600 TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2601 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2602 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
2603 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2606 IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr));
2607 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2610 // Tests that IsSubstring() generates the correct message when the input
2611 // argument type is const char*.
2612 TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2614 "Value of: needle_expr\n"
2615 " Actual: \"needle\"\n"
2616 "Expected: a substring of haystack_expr\n"
2617 "Which is: \"haystack\"",
2618 IsSubstring("needle_expr", "haystack_expr", "needle", "haystack")
2619 .failure_message());
2622 // Tests that IsSubstring returns the correct result when the input
2623 // argument type is ::std::string.
2624 TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2625 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2626 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2629 #if GTEST_HAS_STD_WSTRING
2630 // Tests that IsSubstring returns the correct result when the input
2631 // argument type is ::std::wstring.
2632 TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2633 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2634 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2637 // Tests that IsSubstring() generates the correct message when the input
2638 // argument type is ::std::wstring.
2639 TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2641 "Value of: needle_expr\n"
2642 " Actual: L\"needle\"\n"
2643 "Expected: a substring of haystack_expr\n"
2644 "Which is: L\"haystack\"",
2645 IsSubstring("needle_expr", "haystack_expr", ::std::wstring(L"needle"),
2647 .failure_message());
2650 #endif // GTEST_HAS_STD_WSTRING
2652 // Tests for ::testing::IsNotSubstring().
2654 // Tests that IsNotSubstring() returns the correct result when the input
2655 // argument type is const char*.
2656 TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2657 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2658 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2661 // Tests that IsNotSubstring() returns the correct result when the input
2662 // argument type is const wchar_t*.
2663 TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2664 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2665 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2668 // Tests that IsNotSubstring() generates the correct message when the input
2669 // argument type is const wchar_t*.
2670 TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2672 "Value of: needle_expr\n"
2673 " Actual: L\"needle\"\n"
2674 "Expected: not a substring of haystack_expr\n"
2675 "Which is: L\"two needles\"",
2676 IsNotSubstring("needle_expr", "haystack_expr", L"needle", L"two needles")
2677 .failure_message());
2680 // Tests that IsNotSubstring returns the correct result when the input
2681 // argument type is ::std::string.
2682 TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2683 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2684 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2687 // Tests that IsNotSubstring() generates the correct message when the input
2688 // argument type is ::std::string.
2689 TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2691 "Value of: needle_expr\n"
2692 " Actual: \"needle\"\n"
2693 "Expected: not a substring of haystack_expr\n"
2694 "Which is: \"two needles\"",
2695 IsNotSubstring("needle_expr", "haystack_expr", ::std::string("needle"),
2697 .failure_message());
2700 #if GTEST_HAS_STD_WSTRING
2702 // Tests that IsNotSubstring returns the correct result when the input
2703 // argument type is ::std::wstring.
2704 TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2706 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2707 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2710 #endif // GTEST_HAS_STD_WSTRING
2712 // Tests floating-point assertions.
2714 template <typename RawType>
2715 class FloatingPointTest : public Test {
2717 // Pre-calculated numbers to be used by the tests.
2719 RawType close_to_positive_zero;
2720 RawType close_to_negative_zero;
2721 RawType further_from_negative_zero;
2723 RawType close_to_one;
2724 RawType further_from_one;
2727 RawType close_to_infinity;
2728 RawType further_from_infinity;
2734 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2735 typedef typename Floating::Bits Bits;
2737 void SetUp() override {
2738 const uint32_t max_ulps = Floating::kMaxUlps;
2740 // The bits that represent 0.0.
2741 const Bits zero_bits = Floating(0).bits();
2743 // Makes some numbers close to 0.0.
2744 values_.close_to_positive_zero =
2745 Floating::ReinterpretBits(zero_bits + max_ulps / 2);
2746 values_.close_to_negative_zero =
2747 -Floating::ReinterpretBits(zero_bits + max_ulps - max_ulps / 2);
2748 values_.further_from_negative_zero =
2749 -Floating::ReinterpretBits(zero_bits + max_ulps + 1 - max_ulps / 2);
2751 // The bits that represent 1.0.
2752 const Bits one_bits = Floating(1).bits();
2754 // Makes some numbers close to 1.0.
2755 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2756 values_.further_from_one =
2757 Floating::ReinterpretBits(one_bits + max_ulps + 1);
2760 values_.infinity = Floating::Infinity();
2762 // The bits that represent +infinity.
2763 const Bits infinity_bits = Floating(values_.infinity).bits();
2765 // Makes some numbers close to infinity.
2766 values_.close_to_infinity =
2767 Floating::ReinterpretBits(infinity_bits - max_ulps);
2768 values_.further_from_infinity =
2769 Floating::ReinterpretBits(infinity_bits - max_ulps - 1);
2771 // Makes some NAN's. Sets the most significant bit of the fraction so that
2772 // our NaN's are quiet; trying to process a signaling NaN would raise an
2773 // exception if our environment enables floating point exceptions.
2774 values_.nan1 = Floating::ReinterpretBits(
2775 Floating::kExponentBitMask |
2776 (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2777 values_.nan2 = Floating::ReinterpretBits(
2778 Floating::kExponentBitMask |
2779 (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
2782 void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); }
2784 static TestValues values_;
2787 template <typename RawType>
2788 typename FloatingPointTest<RawType>::TestValues
2789 FloatingPointTest<RawType>::values_;
2791 // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2792 typedef FloatingPointTest<float> FloatTest;
2794 // Tests that the size of Float::Bits matches the size of float.
2795 TEST_F(FloatTest, Size) { TestSize(); }
2797 // Tests comparing with +0 and -0.
2798 TEST_F(FloatTest, Zeros) {
2799 EXPECT_FLOAT_EQ(0.0, -0.0);
2800 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), "1.0");
2801 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), "1.5");
2804 // Tests comparing numbers close to 0.
2806 // This ensures that *_FLOAT_EQ handles the sign correctly and no
2807 // overflow occurs when comparing numbers whose absolute value is very
2809 TEST_F(FloatTest, AlmostZeros) {
2810 // In C++Builder, names within local classes (such as used by
2811 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2812 // scoping class. Use a static local alias as a workaround.
2813 // We use the assignment syntax since some compilers, like Sun Studio,
2814 // don't allow initializing references using construction syntax
2816 static const FloatTest::TestValues& v = this->values_;
2818 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2819 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2820 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2822 EXPECT_FATAL_FAILURE(
2824 ASSERT_FLOAT_EQ(v.close_to_positive_zero, v.further_from_negative_zero);
2826 "v.further_from_negative_zero");
2829 // Tests comparing numbers close to each other.
2830 TEST_F(FloatTest, SmallDiff) {
2831 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2832 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2833 "values_.further_from_one");
2836 // Tests comparing numbers far apart.
2837 TEST_F(FloatTest, LargeDiff) {
2838 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), "3.0");
2841 // Tests comparing with infinity.
2843 // This ensures that no overflow occurs when comparing numbers whose
2844 // absolute value is very large.
2845 TEST_F(FloatTest, Infinity) {
2846 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2847 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
2848 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2849 "-values_.infinity");
2851 // This is interesting as the representations of infinity and nan1
2852 // are only 1 DLP apart.
2853 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2857 // Tests that comparing with NAN always returns false.
2858 TEST_F(FloatTest, NaN) {
2859 // In C++Builder, names within local classes (such as used by
2860 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2861 // scoping class. Use a static local alias as a workaround.
2862 // We use the assignment syntax since some compilers, like Sun Studio,
2863 // don't allow initializing references using construction syntax
2865 static const FloatTest::TestValues& v = this->values_;
2867 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), "v.nan1");
2868 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), "v.nan2");
2869 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), "v.nan1");
2871 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity");
2874 // Tests that *_FLOAT_EQ are reflexive.
2875 TEST_F(FloatTest, Reflexive) {
2876 EXPECT_FLOAT_EQ(0.0, 0.0);
2877 EXPECT_FLOAT_EQ(1.0, 1.0);
2878 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
2881 // Tests that *_FLOAT_EQ are commutative.
2882 TEST_F(FloatTest, Commutative) {
2883 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2884 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2886 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2887 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2891 // Tests EXPECT_NEAR.
2892 TEST_F(FloatTest, EXPECT_NEAR) {
2893 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2894 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2895 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
2896 "The difference between 1.0f and 1.5f is 0.5, "
2897 "which exceeds 0.25f");
2900 // Tests ASSERT_NEAR.
2901 TEST_F(FloatTest, ASSERT_NEAR) {
2902 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2903 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2904 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
2905 "The difference between 1.0f and 1.5f is 0.5, "
2906 "which exceeds 0.25f");
2909 // Tests the cases where FloatLE() should succeed.
2910 TEST_F(FloatTest, FloatLESucceeds) {
2911 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2912 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
2914 // or when val1 is greater than, but almost equals to, val2.
2915 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2918 // Tests the cases where FloatLE() should fail.
2919 TEST_F(FloatTest, FloatLEFails) {
2920 // When val1 is greater than val2 by a large margin,
2921 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2922 "(2.0f) <= (1.0f)");
2924 // or by a small yet non-negligible margin,
2925 EXPECT_NONFATAL_FAILURE(
2927 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2929 "(values_.further_from_one) <= (1.0f)");
2931 EXPECT_NONFATAL_FAILURE(
2933 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2935 "(values_.nan1) <= (values_.infinity)");
2936 EXPECT_NONFATAL_FAILURE(
2938 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2940 "(-values_.infinity) <= (values_.nan1)");
2941 EXPECT_FATAL_FAILURE(
2943 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2945 "(values_.nan1) <= (values_.nan1)");
2948 // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2949 typedef FloatingPointTest<double> DoubleTest;
2951 // Tests that the size of Double::Bits matches the size of double.
2952 TEST_F(DoubleTest, Size) { TestSize(); }
2954 // Tests comparing with +0 and -0.
2955 TEST_F(DoubleTest, Zeros) {
2956 EXPECT_DOUBLE_EQ(0.0, -0.0);
2957 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), "1.0");
2958 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), "1.0");
2961 // Tests comparing numbers close to 0.
2963 // This ensures that *_DOUBLE_EQ handles the sign correctly and no
2964 // overflow occurs when comparing numbers whose absolute value is very
2966 TEST_F(DoubleTest, AlmostZeros) {
2967 // In C++Builder, names within local classes (such as used by
2968 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2969 // scoping class. Use a static local alias as a workaround.
2970 // We use the assignment syntax since some compilers, like Sun Studio,
2971 // don't allow initializing references using construction syntax
2973 static const DoubleTest::TestValues& v = this->values_;
2975 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2976 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
2977 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2979 EXPECT_FATAL_FAILURE(
2981 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
2982 v.further_from_negative_zero);
2984 "v.further_from_negative_zero");
2987 // Tests comparing numbers close to each other.
2988 TEST_F(DoubleTest, SmallDiff) {
2989 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
2990 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
2991 "values_.further_from_one");
2994 // Tests comparing numbers far apart.
2995 TEST_F(DoubleTest, LargeDiff) {
2996 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), "3.0");
2999 // Tests comparing with infinity.
3001 // This ensures that no overflow occurs when comparing numbers whose
3002 // absolute value is very large.
3003 TEST_F(DoubleTest, Infinity) {
3004 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
3005 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
3006 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
3007 "-values_.infinity");
3009 // This is interesting as the representations of infinity_ and nan1_
3010 // are only 1 DLP apart.
3011 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
3015 // Tests that comparing with NAN always returns false.
3016 TEST_F(DoubleTest, NaN) {
3017 static const DoubleTest::TestValues& v = this->values_;
3019 // Nokia's STLport crashes if we try to output infinity or NaN.
3020 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), "v.nan1");
3021 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
3022 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3023 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity");
3026 // Tests that *_DOUBLE_EQ are reflexive.
3027 TEST_F(DoubleTest, Reflexive) {
3028 EXPECT_DOUBLE_EQ(0.0, 0.0);
3029 EXPECT_DOUBLE_EQ(1.0, 1.0);
3030 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
3033 // Tests that *_DOUBLE_EQ are commutative.
3034 TEST_F(DoubleTest, Commutative) {
3035 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3036 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
3038 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3039 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3043 // Tests EXPECT_NEAR.
3044 TEST_F(DoubleTest, EXPECT_NEAR) {
3045 EXPECT_NEAR(-1.0, -1.1, 0.2);
3046 EXPECT_NEAR(2.0, 3.0, 1.0);
3047 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3048 "The difference between 1.0 and 1.5 is 0.5, "
3049 "which exceeds 0.25");
3050 // At this magnitude adjacent doubles are 512.0 apart, so this triggers a
3051 // slightly different failure reporting path.
3052 EXPECT_NONFATAL_FAILURE(
3053 EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),
3054 "The abs_error parameter 1.0 evaluates to 1 which is smaller than the "
3055 "minimum distance between doubles for numbers of this magnitude which is "
3059 // Tests ASSERT_NEAR.
3060 TEST_F(DoubleTest, ASSERT_NEAR) {
3061 ASSERT_NEAR(-1.0, -1.1, 0.2);
3062 ASSERT_NEAR(2.0, 3.0, 1.0);
3063 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3064 "The difference between 1.0 and 1.5 is 0.5, "
3065 "which exceeds 0.25");
3068 // Tests the cases where DoubleLE() should succeed.
3069 TEST_F(DoubleTest, DoubleLESucceeds) {
3070 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3071 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
3073 // or when val1 is greater than, but almost equals to, val2.
3074 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3077 // Tests the cases where DoubleLE() should fail.
3078 TEST_F(DoubleTest, DoubleLEFails) {
3079 // When val1 is greater than val2 by a large margin,
3080 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
3083 // or by a small yet non-negligible margin,
3084 EXPECT_NONFATAL_FAILURE(
3086 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3088 "(values_.further_from_one) <= (1.0)");
3090 EXPECT_NONFATAL_FAILURE(
3092 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3094 "(values_.nan1) <= (values_.infinity)");
3095 EXPECT_NONFATAL_FAILURE(
3097 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3099 " (-values_.infinity) <= (values_.nan1)");
3100 EXPECT_FATAL_FAILURE(
3102 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3104 "(values_.nan1) <= (values_.nan1)");
3107 // Verifies that a test or test case whose name starts with DISABLED_ is
3110 // A test whose name starts with DISABLED_.
3112 TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3113 FAIL() << "Unexpected failure: Disabled test should not be run.";
3116 // A test whose name does not start with DISABLED_.
3118 TEST(DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); }
3120 // A test case whose name starts with DISABLED_.
3122 TEST(DISABLED_TestSuite, TestShouldNotRun) {
3123 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3126 // A test case and test whose names start with DISABLED_.
3128 TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {
3129 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3132 // Check that when all tests in a test case are disabled, SetUpTestSuite() and
3133 // TearDownTestSuite() are not called.
3134 class DisabledTestsTest : public Test {
3136 static void SetUpTestSuite() {
3137 FAIL() << "Unexpected failure: All tests disabled in test case. "
3138 "SetUpTestSuite() should not be called.";
3141 static void TearDownTestSuite() {
3142 FAIL() << "Unexpected failure: All tests disabled in test case. "
3143 "TearDownTestSuite() should not be called.";
3147 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3148 FAIL() << "Unexpected failure: Disabled test should not be run.";
3151 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3152 FAIL() << "Unexpected failure: Disabled test should not be run.";
3155 // Tests that disabled typed tests aren't run.
3157 template <typename T>
3158 class TypedTest : public Test {};
3160 typedef testing::Types<int, double> NumericTypes;
3161 TYPED_TEST_SUITE(TypedTest, NumericTypes);
3163 TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3164 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3167 template <typename T>
3168 class DISABLED_TypedTest : public Test {};
3170 TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
3172 TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3173 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3176 // Tests that disabled type-parameterized tests aren't run.
3178 template <typename T>
3179 class TypedTestP : public Test {};
3181 TYPED_TEST_SUITE_P(TypedTestP);
3183 TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3184 FAIL() << "Unexpected failure: "
3185 << "Disabled type-parameterized test should not run.";
3188 REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
3190 INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);
3192 template <typename T>
3193 class DISABLED_TypedTestP : public Test {};
3195 TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
3197 TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3198 FAIL() << "Unexpected failure: "
3199 << "Disabled type-parameterized test should not run.";
3202 REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
3204 INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
3206 // Tests that assertion macros evaluate their arguments exactly once.
3208 class SingleEvaluationTest : public Test {
3209 public: // Must be public and not protected due to a bug in g++ 3.4.2.
3210 // This helper function is needed by the FailedASSERT_STREQ test
3211 // below. It's public to work around C++Builder's bug with scoping local
3213 static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); }
3215 // This helper function is needed by the FailedASSERT_NE test below. It's
3216 // public to work around C++Builder's bug with scoping local classes.
3217 static void CompareAndIncrementInts() { ASSERT_NE(a_++, b_++); }
3220 SingleEvaluationTest() {
3227 static const char* const s1_;
3228 static const char* const s2_;
3229 static const char* p1_;
3230 static const char* p2_;
3236 const char* const SingleEvaluationTest::s1_ = "01234";
3237 const char* const SingleEvaluationTest::s2_ = "abcde";
3238 const char* SingleEvaluationTest::p1_;
3239 const char* SingleEvaluationTest::p2_;
3240 int SingleEvaluationTest::a_;
3241 int SingleEvaluationTest::b_;
3243 // Tests that when ASSERT_STREQ fails, it evaluates its arguments
3245 TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3246 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3248 EXPECT_EQ(s1_ + 1, p1_);
3249 EXPECT_EQ(s2_ + 1, p2_);
3252 // Tests that string assertion arguments are evaluated exactly once.
3253 TEST_F(SingleEvaluationTest, ASSERT_STR) {
3254 // successful EXPECT_STRNE
3255 EXPECT_STRNE(p1_++, p2_++);
3256 EXPECT_EQ(s1_ + 1, p1_);
3257 EXPECT_EQ(s2_ + 1, p2_);
3259 // failed EXPECT_STRCASEEQ
3260 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), "Ignoring case");
3261 EXPECT_EQ(s1_ + 2, p1_);
3262 EXPECT_EQ(s2_ + 2, p2_);
3265 // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3267 TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3268 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3269 "(a_++) != (b_++)");
3274 // Tests that assertion arguments are evaluated exactly once.
3275 TEST_F(SingleEvaluationTest, OtherCases) {
3276 // successful EXPECT_TRUE
3277 EXPECT_TRUE(0 == a_++); // NOLINT
3280 // failed EXPECT_TRUE
3281 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3284 // successful EXPECT_GT
3285 EXPECT_GT(a_++, b_++);
3290 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3294 // successful ASSERT_TRUE
3295 ASSERT_TRUE(0 < a_++); // NOLINT
3298 // successful ASSERT_GT
3299 ASSERT_GT(a_++, b_++);
3304 #if GTEST_HAS_EXCEPTIONS
3309 #define ERROR_DESC "class std::runtime_error"
3311 #define ERROR_DESC "std::runtime_error"
3314 #else // GTEST_HAS_RTTI
3316 #define ERROR_DESC "an std::exception-derived error"
3318 #endif // GTEST_HAS_RTTI
3320 void ThrowAnInteger() { throw 1; }
3321 void ThrowRuntimeError(const char* what) { throw std::runtime_error(what); }
3323 // Tests that assertion arguments are evaluated exactly once.
3324 TEST_F(SingleEvaluationTest, ExceptionTests) {
3325 // successful EXPECT_THROW
3334 // failed EXPECT_THROW, throws different
3335 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(
3341 "throws a different type");
3344 // failed EXPECT_THROW, throws runtime error
3345 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(
3348 ThrowRuntimeError("A description");
3351 "throws " ERROR_DESC
3352 " with description \"A description\"");
3355 // failed EXPECT_THROW, throws nothing
3356 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3359 // successful EXPECT_NO_THROW
3360 EXPECT_NO_THROW(a_++);
3363 // failed EXPECT_NO_THROW
3364 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3371 // successful EXPECT_ANY_THROW
3372 EXPECT_ANY_THROW({ // NOLINT
3378 // failed EXPECT_ANY_THROW
3379 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3383 #endif // GTEST_HAS_EXCEPTIONS
3385 // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3386 class NoFatalFailureTest : public Test {
3389 void FailsNonFatal() { ADD_FAILURE() << "some non-fatal failure"; }
3390 void Fails() { FAIL() << "some fatal failure"; }
3392 void DoAssertNoFatalFailureOnFails() {
3393 ASSERT_NO_FATAL_FAILURE(Fails());
3394 ADD_FAILURE() << "should not reach here.";
3397 void DoExpectNoFatalFailureOnFails() {
3398 EXPECT_NO_FATAL_FAILURE(Fails());
3399 ADD_FAILURE() << "other failure";
3403 TEST_F(NoFatalFailureTest, NoFailure) {
3404 EXPECT_NO_FATAL_FAILURE(Succeeds());
3405 ASSERT_NO_FATAL_FAILURE(Succeeds());
3408 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3409 EXPECT_NONFATAL_FAILURE(EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3410 "some non-fatal failure");
3411 EXPECT_NONFATAL_FAILURE(ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3412 "some non-fatal failure");
3415 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3416 TestPartResultArray gtest_failures;
3418 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3419 DoAssertNoFatalFailureOnFails();
3421 ASSERT_EQ(2, gtest_failures.size());
3422 EXPECT_EQ(TestPartResult::kFatalFailure,
3423 gtest_failures.GetTestPartResult(0).type());
3424 EXPECT_EQ(TestPartResult::kFatalFailure,
3425 gtest_failures.GetTestPartResult(1).type());
3426 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3427 gtest_failures.GetTestPartResult(0).message());
3428 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3429 gtest_failures.GetTestPartResult(1).message());
3432 TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3433 TestPartResultArray gtest_failures;
3435 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3436 DoExpectNoFatalFailureOnFails();
3438 ASSERT_EQ(3, gtest_failures.size());
3439 EXPECT_EQ(TestPartResult::kFatalFailure,
3440 gtest_failures.GetTestPartResult(0).type());
3441 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3442 gtest_failures.GetTestPartResult(1).type());
3443 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3444 gtest_failures.GetTestPartResult(2).type());
3445 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3446 gtest_failures.GetTestPartResult(0).message());
3447 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3448 gtest_failures.GetTestPartResult(1).message());
3449 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3450 gtest_failures.GetTestPartResult(2).message());
3453 TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3454 TestPartResultArray gtest_failures;
3456 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3457 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3459 ASSERT_EQ(2, gtest_failures.size());
3460 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3461 gtest_failures.GetTestPartResult(0).type());
3462 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3463 gtest_failures.GetTestPartResult(1).type());
3464 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3465 gtest_failures.GetTestPartResult(0).message());
3466 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3467 gtest_failures.GetTestPartResult(1).message());
3470 // Tests non-string assertions.
3472 std::string EditsToString(const std::vector<EditType>& edits) {
3474 for (size_t i = 0; i < edits.size(); ++i) {
3475 static const char kEdits[] = " +-/";
3476 out.append(1, kEdits[edits[i]]);
3481 std::vector<size_t> CharsToIndices(const std::string& str) {
3482 std::vector<size_t> out;
3483 for (size_t i = 0; i < str.size(); ++i) {
3484 out.push_back(static_cast<size_t>(str[i]));
3489 std::vector<std::string> CharsToLines(const std::string& str) {
3490 std::vector<std::string> out;
3491 for (size_t i = 0; i < str.size(); ++i) {
3492 out.push_back(str.substr(i, 1));
3497 TEST(EditDistance, TestSuites) {
3502 const char* expected_edits;
3503 const char* expected_diff;
3505 static const Case kCases[] = {
3507 {__LINE__, "A", "A", " ", ""},
3508 {__LINE__, "ABCDE", "ABCDE", " ", ""},
3510 {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
3511 {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
3513 {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
3514 {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
3516 {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
3517 {__LINE__, "ABCD", "abcd", "////",
3518 "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
3520 {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
3521 "@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"},
3522 {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
3523 "@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"},
3524 {__LINE__, "ABCDE", "BCDCD", "- +/",
3525 "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
3526 {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
3527 "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
3528 "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
3530 for (const Case* c = kCases; c->left; ++c) {
3531 EXPECT_TRUE(c->expected_edits ==
3532 EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3533 CharsToIndices(c->right))))
3534 << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
3535 << EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3536 CharsToIndices(c->right)))
3538 EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
3539 CharsToLines(c->right)))
3540 << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
3541 << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
3546 // Tests EqFailure(), used for implementing *EQ* assertions.
3547 TEST(AssertionTest, EqFailure) {
3548 const std::string foo_val("5"), bar_val("6");
3549 const std::string msg1(
3550 EqFailure("foo", "bar", foo_val, bar_val, false).failure_message());
3552 "Expected equality of these values:\n"
3559 const std::string msg2(
3560 EqFailure("foo", "6", foo_val, bar_val, false).failure_message());
3562 "Expected equality of these values:\n"
3568 const std::string msg3(
3569 EqFailure("5", "bar", foo_val, bar_val, false).failure_message());
3571 "Expected equality of these values:\n"
3577 const std::string msg4(
3578 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3580 "Expected equality of these values:\n"
3585 const std::string msg5(
3586 EqFailure("foo", "bar", std::string("\"x\""), std::string("\"y\""), true)
3587 .failure_message());
3589 "Expected equality of these values:\n"
3591 " Which is: \"x\"\n"
3593 " Which is: \"y\"\n"
3598 TEST(AssertionTest, EqFailureWithDiff) {
3599 const std::string left(
3600 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
3601 const std::string right(
3602 "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
3603 const std::string msg1(
3604 EqFailure("left", "right", left, right, false).failure_message());
3606 "Expected equality of these values:\n"
3609 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3611 " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3612 "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
3613 "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
3617 // Tests AppendUserMessage(), used for implementing the *EQ* macros.
3618 TEST(AssertionTest, AppendUserMessage) {
3619 const std::string foo("foo");
3622 EXPECT_STREQ("foo", AppendUserMessage(foo, msg).c_str());
3625 EXPECT_STREQ("foo\nbar", AppendUserMessage(foo, msg).c_str());
3629 // Silences warnings: "Condition is always true", "Unreachable code"
3630 #pragma option push -w-ccc -w-rch
3633 // Tests ASSERT_TRUE.
3634 TEST(AssertionTest, ASSERT_TRUE) {
3635 ASSERT_TRUE(2 > 1); // NOLINT
3636 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), "2 < 1");
3639 // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3640 TEST(AssertionTest, AssertTrueWithAssertionResult) {
3641 ASSERT_TRUE(ResultIsEven(2));
3642 #ifndef __BORLANDC__
3643 // ICE's in C++Builder.
3644 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3645 "Value of: ResultIsEven(3)\n"
3646 " Actual: false (3 is odd)\n"
3649 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3650 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3651 "Value of: ResultIsEvenNoExplanation(3)\n"
3652 " Actual: false (3 is odd)\n"
3656 // Tests ASSERT_FALSE.
3657 TEST(AssertionTest, ASSERT_FALSE) {
3658 ASSERT_FALSE(2 < 1); // NOLINT
3659 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3665 // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3666 TEST(AssertionTest, AssertFalseWithAssertionResult) {
3667 ASSERT_FALSE(ResultIsEven(3));
3668 #ifndef __BORLANDC__
3669 // ICE's in C++Builder.
3670 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3671 "Value of: ResultIsEven(2)\n"
3672 " Actual: true (2 is even)\n"
3675 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3676 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3677 "Value of: ResultIsEvenNoExplanation(2)\n"
3683 // Restores warnings after previous "#pragma option push" suppressed them
3687 // Tests using ASSERT_EQ on double values. The purpose is to make
3688 // sure that the specialization we did for integer and anonymous enums
3689 // isn't used for double arguments.
3690 TEST(ExpectTest, ASSERT_EQ_Double) {
3692 ASSERT_EQ(5.6, 5.6);
3695 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), "5.1");
3699 TEST(AssertionTest, ASSERT_EQ) {
3700 ASSERT_EQ(5, 2 + 3);
3702 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3703 "Expected equality of these values:\n"
3710 // Tests ASSERT_EQ(NULL, pointer).
3711 TEST(AssertionTest, ASSERT_EQ_NULL) {
3713 const char* p = nullptr;
3714 ASSERT_EQ(nullptr, p);
3718 EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:");
3721 // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3722 // treated as a null pointer by the compiler, we need to make sure
3723 // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3724 // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3725 TEST(ExpectTest, ASSERT_EQ_0) {
3732 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), " 0\n 5.6");
3736 TEST(AssertionTest, ASSERT_NE) {
3738 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3739 "Expected: ('a') != ('a'), "
3740 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3744 TEST(AssertionTest, ASSERT_LE) {
3747 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0");
3751 TEST(AssertionTest, ASSERT_LT) {
3753 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2");
3757 TEST(AssertionTest, ASSERT_GE) {
3760 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3");
3764 TEST(AssertionTest, ASSERT_GT) {
3766 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2");
3769 #if GTEST_HAS_EXCEPTIONS
3771 void ThrowNothing() {}
3773 // Tests ASSERT_THROW.
3774 TEST(AssertionTest, ASSERT_THROW) {
3775 ASSERT_THROW(ThrowAnInteger(), int);
3777 #ifndef __BORLANDC__
3779 // ICE's in C++Builder 2007 and 2009.
3780 EXPECT_FATAL_FAILURE(
3781 ASSERT_THROW(ThrowAnInteger(), bool),
3782 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3783 " Actual: it throws a different type.");
3784 EXPECT_FATAL_FAILURE(
3785 ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
3786 "Expected: ThrowRuntimeError(\"A description\") "
3787 "throws an exception of type std::logic_error.\n "
3788 "Actual: it throws " ERROR_DESC
3790 "with description \"A description\".");
3793 EXPECT_FATAL_FAILURE(
3794 ASSERT_THROW(ThrowNothing(), bool),
3795 "Expected: ThrowNothing() throws an exception of type bool.\n"
3796 " Actual: it throws nothing.");
3799 // Tests ASSERT_NO_THROW.
3800 TEST(AssertionTest, ASSERT_NO_THROW) {
3801 ASSERT_NO_THROW(ThrowNothing());
3802 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3803 "Expected: ThrowAnInteger() doesn't throw an exception."
3804 "\n Actual: it throws.");
3805 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
3806 "Expected: ThrowRuntimeError(\"A description\") "
3807 "doesn't throw an exception.\n "
3808 "Actual: it throws " ERROR_DESC
3810 "with description \"A description\".");
3813 // Tests ASSERT_ANY_THROW.
3814 TEST(AssertionTest, ASSERT_ANY_THROW) {
3815 ASSERT_ANY_THROW(ThrowAnInteger());
3816 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()),
3817 "Expected: ThrowNothing() throws an exception.\n"
3818 " Actual: it doesn't.");
3821 #endif // GTEST_HAS_EXCEPTIONS
3823 // Makes sure we deal with the precedence of <<. This test should
3825 TEST(AssertionTest, AssertPrecedence) {
3826 ASSERT_EQ(1 < 2, true);
3827 bool false_value = false;
3828 ASSERT_EQ(true && false_value, false);
3831 // A subroutine used by the following test.
3832 void TestEq1(int x) { ASSERT_EQ(1, x); }
3834 // Tests calling a test subroutine that's not part of a fixture.
3835 TEST(AssertionTest, NonFixtureSubroutine) {
3836 EXPECT_FATAL_FAILURE(TestEq1(2), " x\n Which is: 2");
3839 // An uncopyable class.
3842 explicit Uncopyable(int a_value) : value_(a_value) {}
3844 int value() const { return value_; }
3845 bool operator==(const Uncopyable& rhs) const {
3846 return value() == rhs.value();
3850 // This constructor deliberately has no implementation, as we don't
3851 // want this class to be copyable.
3852 Uncopyable(const Uncopyable&); // NOLINT
3857 ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3858 return os << value.value();
3861 bool IsPositiveUncopyable(const Uncopyable& x) { return x.value() > 0; }
3863 // A subroutine used by the following test.
3864 void TestAssertNonPositive() {
3866 ASSERT_PRED1(IsPositiveUncopyable, y);
3868 // A subroutine used by the following test.
3869 void TestAssertEqualsUncopyable() {
3875 // Tests that uncopyable objects can be used in assertions.
3876 TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3878 ASSERT_PRED1(IsPositiveUncopyable, x);
3880 EXPECT_FATAL_FAILURE(
3881 TestAssertNonPositive(),
3882 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3883 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3884 "Expected equality of these values:\n"
3885 " x\n Which is: 5\n y\n Which is: -1");
3888 // Tests that uncopyable objects can be used in expects.
3889 TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3891 EXPECT_PRED1(IsPositiveUncopyable, x);
3893 EXPECT_NONFATAL_FAILURE(
3894 EXPECT_PRED1(IsPositiveUncopyable, y),
3895 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3897 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3898 "Expected equality of these values:\n"
3899 " x\n Which is: 5\n y\n Which is: -1");
3902 enum NamedEnum { kE1 = 0, kE2 = 1 };
3904 TEST(AssertionTest, NamedEnum) {
3905 EXPECT_EQ(kE1, kE1);
3906 EXPECT_LT(kE1, kE2);
3907 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3908 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
3911 // Sun Studio and HP aCC2reject this code.
3912 #if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3914 // Tests using assertions with anonymous enums.
3920 // We want to test the case where the size of the anonymous enum is
3921 // larger than sizeof(int), to make sure our implementation of the
3922 // assertions doesn't truncate the enums. However, MSVC
3923 // (incorrectly) doesn't allow an enum value to exceed the range of
3924 // an int, so this has to be conditionally compiled.
3926 // On Linux, kCaseB and kCaseA have the same value when truncated to
3927 // int size. We want to test whether this will confuse the
3929 kCaseB = testing::internal::kMaxBiggestInt,
3935 #endif // GTEST_OS_LINUX
3940 TEST(AssertionTest, AnonymousEnum) {
3943 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
3945 #endif // GTEST_OS_LINUX
3947 EXPECT_EQ(kCaseA, kCaseA);
3948 EXPECT_NE(kCaseA, kCaseB);
3949 EXPECT_LT(kCaseA, kCaseB);
3950 EXPECT_LE(kCaseA, kCaseB);
3951 EXPECT_GT(kCaseB, kCaseA);
3952 EXPECT_GE(kCaseA, kCaseA);
3953 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), "(kCaseA) >= (kCaseB)");
3954 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), "-1 vs 42");
3956 ASSERT_EQ(kCaseA, kCaseA);
3957 ASSERT_NE(kCaseA, kCaseB);
3958 ASSERT_LT(kCaseA, kCaseB);
3959 ASSERT_LE(kCaseA, kCaseB);
3960 ASSERT_GT(kCaseB, kCaseA);
3961 ASSERT_GE(kCaseA, kCaseA);
3963 #ifndef __BORLANDC__
3965 // ICE's in C++Builder.
3966 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), " kCaseB\n Which is: ");
3967 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: 42");
3970 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: -1");
3973 #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
3975 #if GTEST_OS_WINDOWS
3977 static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; }
3979 static HRESULT OkHRESULTSuccess() { return S_OK; }
3981 static HRESULT FalseHRESULTSuccess() { return S_FALSE; }
3983 // HRESULT assertion tests test both zero and non-zero
3984 // success codes as well as failure message for each.
3986 // Windows CE doesn't support message texts.
3987 TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
3988 EXPECT_HRESULT_SUCCEEDED(S_OK);
3989 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
3991 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
3992 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
3993 " Actual: 0x8000FFFF");
3996 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
3997 ASSERT_HRESULT_SUCCEEDED(S_OK);
3998 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
4000 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4001 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4002 " Actual: 0x8000FFFF");
4005 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
4006 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
4008 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
4009 "Expected: (OkHRESULTSuccess()) fails.\n"
4011 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
4012 "Expected: (FalseHRESULTSuccess()) fails.\n"
4016 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4017 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
4019 #ifndef __BORLANDC__
4021 // ICE's in C++Builder 2007 and 2009.
4022 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4023 "Expected: (OkHRESULTSuccess()) fails.\n"
4027 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4028 "Expected: (FalseHRESULTSuccess()) fails.\n"
4032 // Tests that streaming to the HRESULT macros works.
4033 TEST(HRESULTAssertionTest, Streaming) {
4034 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4035 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4036 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4037 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4039 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED)
4040 << "expected failure",
4041 "expected failure");
4043 #ifndef __BORLANDC__
4045 // ICE's in C++Builder 2007 and 2009.
4046 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED)
4047 << "expected failure",
4048 "expected failure");
4051 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4052 "expected failure");
4054 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4055 "expected failure");
4058 #endif // GTEST_OS_WINDOWS
4060 // The following code intentionally tests a suboptimal syntax.
4062 #pragma GCC diagnostic push
4063 #pragma GCC diagnostic ignored "-Wdangling-else"
4064 #pragma GCC diagnostic ignored "-Wempty-body"
4065 #pragma GCC diagnostic ignored "-Wpragmas"
4067 // Tests that the assertion macros behave like single statements.
4068 TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4070 ASSERT_TRUE(false) << "This should never be executed; "
4071 "It's a compilation test only.";
4074 EXPECT_FALSE(false);
4078 if (AlwaysFalse()) ASSERT_LT(1, 3);
4083 EXPECT_GT(3, 2) << "";
4086 #pragma GCC diagnostic pop
4089 #if GTEST_HAS_EXCEPTIONS
4090 // Tests that the compiler will not complain about unreachable code in the
4091 // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4092 TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4095 EXPECT_THROW(throw 1, int);
4096 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4097 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4098 EXPECT_NO_THROW(n++);
4099 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4100 EXPECT_ANY_THROW(throw 1);
4101 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4104 TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
4105 EXPECT_THROW(throw std::exception(), std::exception);
4108 // The following code intentionally tests a suboptimal syntax.
4110 #pragma GCC diagnostic push
4111 #pragma GCC diagnostic ignored "-Wdangling-else"
4112 #pragma GCC diagnostic ignored "-Wempty-body"
4113 #pragma GCC diagnostic ignored "-Wpragmas"
4115 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4116 if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool);
4119 EXPECT_THROW(ThrowAnInteger(), int);
4123 if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger());
4126 EXPECT_NO_THROW(ThrowNothing());
4130 if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing());
4133 EXPECT_ANY_THROW(ThrowAnInteger());
4138 #pragma GCC diagnostic pop
4141 #endif // GTEST_HAS_EXCEPTIONS
4143 // The following code intentionally tests a suboptimal syntax.
4145 #pragma GCC diagnostic push
4146 #pragma GCC diagnostic ignored "-Wdangling-else"
4147 #pragma GCC diagnostic ignored "-Wempty-body"
4148 #pragma GCC diagnostic ignored "-Wpragmas"
4150 TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4152 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4153 << "It's a compilation test only.";
4158 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4163 EXPECT_NO_FATAL_FAILURE(SUCCEED());
4170 ASSERT_NO_FATAL_FAILURE(SUCCEED());
4173 #pragma GCC diagnostic pop
4176 // Tests that the assertion macros work well with switch statements.
4177 TEST(AssertionSyntaxTest, WorksWithSwitch) {
4187 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4189 // Binary assertions are implemented using a different code path
4190 // than the Boolean assertions. Hence we test them separately.
4194 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4202 #if GTEST_HAS_EXCEPTIONS
4204 void ThrowAString() { throw "std::string"; }
4206 // Test that the exception assertion macros compile and work with const
4208 TEST(AssertionSyntaxTest, WorksWithConst) {
4209 ASSERT_THROW(ThrowAString(), const char*);
4211 EXPECT_THROW(ThrowAString(), const char*);
4214 #endif // GTEST_HAS_EXCEPTIONS
4220 // Tests that Google Test tracks SUCCEED*.
4221 TEST(SuccessfulAssertionTest, SUCCEED) {
4224 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4227 // Tests that Google Test doesn't track successful EXPECT_*.
4228 TEST(SuccessfulAssertionTest, EXPECT) {
4230 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4233 // Tests that Google Test doesn't track successful EXPECT_STR*.
4234 TEST(SuccessfulAssertionTest, EXPECT_STR) {
4235 EXPECT_STREQ("", "");
4236 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4239 // Tests that Google Test doesn't track successful ASSERT_*.
4240 TEST(SuccessfulAssertionTest, ASSERT) {
4242 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4245 // Tests that Google Test doesn't track successful ASSERT_STR*.
4246 TEST(SuccessfulAssertionTest, ASSERT_STR) {
4247 ASSERT_STREQ("", "");
4248 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4251 } // namespace testing
4255 // Tests the message streaming variation of assertions.
4257 TEST(AssertionWithMessageTest, EXPECT) {
4258 EXPECT_EQ(1, 1) << "This should succeed.";
4259 EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4260 "Expected failure #1");
4261 EXPECT_LE(1, 2) << "This should succeed.";
4262 EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4263 "Expected failure #2.");
4264 EXPECT_GE(1, 0) << "This should succeed.";
4265 EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4266 "Expected failure #3.");
4268 EXPECT_STREQ("1", "1") << "This should succeed.";
4269 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4270 "Expected failure #4.");
4271 EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4272 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4273 "Expected failure #5.");
4275 EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4276 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4277 "Expected failure #6.");
4278 EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4281 TEST(AssertionWithMessageTest, ASSERT) {
4282 ASSERT_EQ(1, 1) << "This should succeed.";
4283 ASSERT_NE(1, 2) << "This should succeed.";
4284 ASSERT_LE(1, 2) << "This should succeed.";
4285 ASSERT_LT(1, 2) << "This should succeed.";
4286 ASSERT_GE(1, 0) << "This should succeed.";
4287 EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4288 "Expected failure.");
4291 TEST(AssertionWithMessageTest, ASSERT_STR) {
4292 ASSERT_STREQ("1", "1") << "This should succeed.";
4293 ASSERT_STRNE("1", "2") << "This should succeed.";
4294 ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4295 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4296 "Expected failure.");
4299 TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4300 ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4301 ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4302 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT
4306 // Tests using ASSERT_FALSE with a streamed message.
4307 TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4308 ASSERT_FALSE(false) << "This shouldn't fail.";
4309 EXPECT_FATAL_FAILURE(
4311 ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4312 << " evaluates to " << true;
4314 "Expected failure");
4317 // Tests using FAIL with a streamed message.
4318 TEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0, "0"); }
4320 // Tests using SUCCEED with a streamed message.
4321 TEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() << "Success == " << 1; }
4323 // Tests using ASSERT_TRUE with a streamed message.
4324 TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4325 ASSERT_TRUE(true) << "This should succeed.";
4326 ASSERT_TRUE(true) << true;
4327 EXPECT_FATAL_FAILURE(
4329 ASSERT_TRUE(false) << static_cast<const char*>(nullptr)
4330 << static_cast<char*>(nullptr);
4335 #if GTEST_OS_WINDOWS
4336 // Tests using wide strings in assertion messages.
4337 TEST(AssertionWithMessageTest, WideStringMessage) {
4338 EXPECT_NONFATAL_FAILURE(
4340 EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4342 "This failure is expected.");
4343 EXPECT_FATAL_FAILURE(
4345 ASSERT_EQ(1, 2) << "This failure is " << L"expected too.\x8120";
4347 "This failure is expected too.");
4349 #endif // GTEST_OS_WINDOWS
4351 // Tests EXPECT_TRUE.
4352 TEST(ExpectTest, EXPECT_TRUE) {
4353 EXPECT_TRUE(true) << "Intentional success";
4354 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4355 "Intentional failure #1.");
4356 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4357 "Intentional failure #2.");
4358 EXPECT_TRUE(2 > 1); // NOLINT
4359 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4363 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), "2 > 3");
4366 // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4367 TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4368 EXPECT_TRUE(ResultIsEven(2));
4369 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4370 "Value of: ResultIsEven(3)\n"
4371 " Actual: false (3 is odd)\n"
4373 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4374 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4375 "Value of: ResultIsEvenNoExplanation(3)\n"
4376 " Actual: false (3 is odd)\n"
4380 // Tests EXPECT_FALSE with a streamed message.
4381 TEST(ExpectTest, EXPECT_FALSE) {
4382 EXPECT_FALSE(2 < 1); // NOLINT
4383 EXPECT_FALSE(false) << "Intentional success";
4384 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4385 "Intentional failure #1.");
4386 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4387 "Intentional failure #2.");
4388 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4392 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), "2 < 3");
4395 // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4396 TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4397 EXPECT_FALSE(ResultIsEven(3));
4398 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4399 "Value of: ResultIsEven(2)\n"
4400 " Actual: true (2 is even)\n"
4402 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4403 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4404 "Value of: ResultIsEvenNoExplanation(2)\n"
4410 // Restores warnings after previous "#pragma option push" suppressed them
4415 TEST(ExpectTest, EXPECT_EQ) {
4416 EXPECT_EQ(5, 2 + 3);
4418 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4419 "Expected equality of these values:\n"
4423 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), "2 - 3");
4427 // Tests using EXPECT_EQ on double values. The purpose is to make
4428 // sure that the specialization we did for integer and anonymous enums
4429 // isn't used for double arguments.
4430 TEST(ExpectTest, EXPECT_EQ_Double) {
4432 EXPECT_EQ(5.6, 5.6);
4435 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), "5.1");
4438 // Tests EXPECT_EQ(NULL, pointer).
4439 TEST(ExpectTest, EXPECT_EQ_NULL) {
4441 const char* p = nullptr;
4442 EXPECT_EQ(nullptr, p);
4446 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:");
4449 // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4450 // treated as a null pointer by the compiler, we need to make sure
4451 // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4452 // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4453 TEST(ExpectTest, EXPECT_EQ_0) {
4460 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), " 0\n 5.6");
4464 TEST(ExpectTest, EXPECT_NE) {
4467 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4468 "Expected: ('a') != ('a'), "
4469 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4470 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), "2");
4471 char* const p0 = nullptr;
4472 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), "p0");
4473 // Only way to get the Nokia compiler to compile the cast
4474 // is to have a separate void* variable first. Putting
4475 // the two casts on the same line doesn't work, neither does
4476 // a direct C-style to char*.
4477 void* pv1 = (void*)0x1234; // NOLINT
4478 char* const p1 = reinterpret_cast<char*>(pv1);
4479 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), "p1");
4483 TEST(ExpectTest, EXPECT_LE) {
4486 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4487 "Expected: (2) <= (0), actual: 2 vs 0");
4488 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), "(1.1) <= (0.9)");
4492 TEST(ExpectTest, EXPECT_LT) {
4494 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4495 "Expected: (2) < (2), actual: 2 vs 2");
4496 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), "(2) < (1)");
4500 TEST(ExpectTest, EXPECT_GE) {
4503 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4504 "Expected: (2) >= (3), actual: 2 vs 3");
4505 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), "(0.9) >= (1.1)");
4509 TEST(ExpectTest, EXPECT_GT) {
4511 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4512 "Expected: (2) > (2), actual: 2 vs 2");
4513 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), "(2) > (3)");
4516 #if GTEST_HAS_EXCEPTIONS
4518 // Tests EXPECT_THROW.
4519 TEST(ExpectTest, EXPECT_THROW) {
4520 EXPECT_THROW(ThrowAnInteger(), int);
4521 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4522 "Expected: ThrowAnInteger() throws an exception of "
4523 "type bool.\n Actual: it throws a different type.");
4524 EXPECT_NONFATAL_FAILURE(
4525 EXPECT_THROW(ThrowRuntimeError("A description"), std::logic_error),
4526 "Expected: ThrowRuntimeError(\"A description\") "
4527 "throws an exception of type std::logic_error.\n "
4528 "Actual: it throws " ERROR_DESC
4530 "with description \"A description\".");
4531 EXPECT_NONFATAL_FAILURE(
4532 EXPECT_THROW(ThrowNothing(), bool),
4533 "Expected: ThrowNothing() throws an exception of type bool.\n"
4534 " Actual: it throws nothing.");
4537 // Tests EXPECT_NO_THROW.
4538 TEST(ExpectTest, EXPECT_NO_THROW) {
4539 EXPECT_NO_THROW(ThrowNothing());
4540 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4541 "Expected: ThrowAnInteger() doesn't throw an "
4542 "exception.\n Actual: it throws.");
4543 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
4544 "Expected: ThrowRuntimeError(\"A description\") "
4545 "doesn't throw an exception.\n "
4546 "Actual: it throws " ERROR_DESC
4548 "with description \"A description\".");
4551 // Tests EXPECT_ANY_THROW.
4552 TEST(ExpectTest, EXPECT_ANY_THROW) {
4553 EXPECT_ANY_THROW(ThrowAnInteger());
4554 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()),
4555 "Expected: ThrowNothing() throws an exception.\n"
4556 " Actual: it doesn't.");
4559 #endif // GTEST_HAS_EXCEPTIONS
4561 // Make sure we deal with the precedence of <<.
4562 TEST(ExpectTest, ExpectPrecedence) {
4563 EXPECT_EQ(1 < 2, true);
4564 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4565 " true && false\n Which is: false");
4568 // Tests the StreamableToString() function.
4570 // Tests using StreamableToString() on a scalar.
4571 TEST(StreamableToStringTest, Scalar) {
4572 EXPECT_STREQ("5", StreamableToString(5).c_str());
4575 // Tests using StreamableToString() on a non-char pointer.
4576 TEST(StreamableToStringTest, Pointer) {
4579 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4582 // Tests using StreamableToString() on a NULL non-char pointer.
4583 TEST(StreamableToStringTest, NullPointer) {
4585 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4588 // Tests using StreamableToString() on a C string.
4589 TEST(StreamableToStringTest, CString) {
4590 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4593 // Tests using StreamableToString() on a NULL C string.
4594 TEST(StreamableToStringTest, NullCString) {
4596 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4599 // Tests using streamable values as assertion messages.
4601 // Tests using std::string as an assertion message.
4602 TEST(StreamableTest, string) {
4603 static const std::string str(
4604 "This failure message is a std::string, and is expected.");
4605 EXPECT_FATAL_FAILURE(FAIL() << str, str.c_str());
4608 // Tests that we can output strings containing embedded NULs.
4609 // Limited to Linux because we can only do this with std::string's.
4610 TEST(StreamableTest, stringWithEmbeddedNUL) {
4611 static const char char_array_with_nul[] =
4612 "Here's a NUL\0 and some more string";
4613 static const std::string string_with_nul(
4614 char_array_with_nul,
4615 sizeof(char_array_with_nul) - 1); // drops the trailing NUL
4616 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4617 "Here's a NUL\\0 and some more string");
4620 // Tests that we can output a NUL char.
4621 TEST(StreamableTest, NULChar) {
4622 EXPECT_FATAL_FAILURE(
4624 FAIL() << "A NUL" << '\0' << " and some more string";
4626 "A NUL\\0 and some more string");
4629 // Tests using int as an assertion message.
4630 TEST(StreamableTest, int) { EXPECT_FATAL_FAILURE(FAIL() << 900913, "900913"); }
4632 // Tests using NULL char pointer as an assertion message.
4634 // In MSVC, streaming a NULL char * causes access violation. Google Test
4635 // implemented a workaround (substituting "(null)" for NULL). This
4636 // tests whether the workaround works.
4637 TEST(StreamableTest, NullCharPtr) {
4638 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)");
4641 // Tests that basic IO manipulators (endl, ends, and flush) can be
4642 // streamed to testing::Message.
4643 TEST(StreamableTest, BasicIoManip) {
4644 EXPECT_FATAL_FAILURE(
4646 FAIL() << "Line 1." << std::endl
4647 << "A NUL char " << std::ends << std::flush << " in line 2.";
4649 "Line 1.\nA NUL char \\0 in line 2.");
4652 // Tests the macros that haven't been covered so far.
4654 void AddFailureHelper(bool* aborted) {
4656 ADD_FAILURE() << "Intentional failure.";
4660 // Tests ADD_FAILURE.
4661 TEST(MacroTest, ADD_FAILURE) {
4662 bool aborted = true;
4663 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), "Intentional failure.");
4664 EXPECT_FALSE(aborted);
4667 // Tests ADD_FAILURE_AT.
4668 TEST(MacroTest, ADD_FAILURE_AT) {
4669 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4670 // the failure message contains the user-streamed part.
4671 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4673 // Verifies that the user-streamed part is optional.
4674 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4676 // Unfortunately, we cannot verify that the failure message contains
4677 // the right file path and line number the same way, as
4678 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4679 // line number. Instead, we do that in googletest-output-test_.cc.
4683 TEST(MacroTest, FAIL) {
4684 EXPECT_FATAL_FAILURE(FAIL(), "Failed");
4685 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4686 "Intentional failure.");
4689 // Tests GTEST_FAIL_AT.
4690 TEST(MacroTest, GTEST_FAIL_AT) {
4691 // Verifies that GTEST_FAIL_AT does generate a fatal failure and
4692 // the failure message contains the user-streamed part.
4693 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4695 // Verifies that the user-streamed part is optional.
4696 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed");
4698 // See the ADD_FAIL_AT test above to see how we test that the failure message
4699 // contains the right filename and line number -- the same applies here.
4703 TEST(MacroTest, SUCCEED) {
4705 SUCCEED() << "Explicit success.";
4708 // Tests for EXPECT_EQ() and ASSERT_EQ().
4710 // These tests fail *intentionally*, s.t. the failure messages can be
4711 // generated and tested.
4713 // We have different tests for different argument types.
4715 // Tests using bool values in {EXPECT|ASSERT}_EQ.
4716 TEST(EqAssertionTest, Bool) {
4717 EXPECT_EQ(true, true);
4718 EXPECT_FATAL_FAILURE(
4720 bool false_value = false;
4721 ASSERT_EQ(false_value, true);
4723 " false_value\n Which is: false\n true");
4726 // Tests using int values in {EXPECT|ASSERT}_EQ.
4727 TEST(EqAssertionTest, Int) {
4729 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), " 32\n 33");
4732 // Tests using time_t values in {EXPECT|ASSERT}_EQ.
4733 TEST(EqAssertionTest, Time_T) {
4734 EXPECT_EQ(static_cast<time_t>(0), static_cast<time_t>(0));
4735 EXPECT_FATAL_FAILURE(
4736 ASSERT_EQ(static_cast<time_t>(0), static_cast<time_t>(1234)), "1234");
4739 // Tests using char values in {EXPECT|ASSERT}_EQ.
4740 TEST(EqAssertionTest, Char) {
4741 ASSERT_EQ('z', 'z');
4742 const char ch = 'b';
4743 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), " ch\n Which is: 'b'");
4744 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), " ch\n Which is: 'b'");
4747 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4748 TEST(EqAssertionTest, WideChar) {
4749 EXPECT_EQ(L'b', L'b');
4751 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4752 "Expected equality of these values:\n"
4754 " Which is: L'\0' (0, 0x0)\n"
4756 " Which is: L'x' (120, 0x78)");
4758 static wchar_t wchar;
4760 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), "wchar");
4762 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
4763 " wchar\n Which is: L'");
4766 // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4767 TEST(EqAssertionTest, StdString) {
4768 // Compares a const char* to an std::string that has identical
4770 ASSERT_EQ("Test", ::std::string("Test"));
4772 // Compares two identical std::strings.
4773 static const ::std::string str1("A * in the middle");
4774 static const ::std::string str2(str1);
4775 EXPECT_EQ(str1, str2);
4777 // Compares a const char* to an std::string that has different
4779 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), "\"test\"");
4781 // Compares an std::string to a char* that has different content.
4782 char* const p1 = const_cast<char*>("foo");
4783 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), "p1");
4785 // Compares two std::strings that have different contents, one of
4786 // which having a NUL character in the middle. This should fail.
4787 static ::std::string str3(str1);
4789 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4790 " str3\n Which is: \"A \\0 in the middle\"");
4793 #if GTEST_HAS_STD_WSTRING
4795 // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4796 TEST(EqAssertionTest, StdWideString) {
4797 // Compares two identical std::wstrings.
4798 const ::std::wstring wstr1(L"A * in the middle");
4799 const ::std::wstring wstr2(wstr1);
4800 ASSERT_EQ(wstr1, wstr2);
4802 // Compares an std::wstring to a const wchar_t* that has identical
4804 const wchar_t kTestX8119[] = {'T', 'e', 's', 't', 0x8119, '\0'};
4805 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4807 // Compares an std::wstring to a const wchar_t* that has different
4809 const wchar_t kTestX8120[] = {'T', 'e', 's', 't', 0x8120, '\0'};
4810 EXPECT_NONFATAL_FAILURE(
4812 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4816 // Compares two std::wstrings that have different contents, one of
4817 // which having a NUL character in the middle.
4818 ::std::wstring wstr3(wstr1);
4819 wstr3.at(2) = L'\0';
4820 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), "wstr3");
4822 // Compares a wchar_t* to an std::wstring that has different
4824 EXPECT_FATAL_FAILURE(
4826 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4831 #endif // GTEST_HAS_STD_WSTRING
4833 // Tests using char pointers in {EXPECT|ASSERT}_EQ.
4834 TEST(EqAssertionTest, CharPointer) {
4835 char* const p0 = nullptr;
4836 // Only way to get the Nokia compiler to compile the cast
4837 // is to have a separate void* variable first. Putting
4838 // the two casts on the same line doesn't work, neither does
4839 // a direct C-style to char*.
4840 void* pv1 = (void*)0x1234; // NOLINT
4841 void* pv2 = (void*)0xABC0; // NOLINT
4842 char* const p1 = reinterpret_cast<char*>(pv1);
4843 char* const p2 = reinterpret_cast<char*>(pv2);
4846 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:");
4847 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:");
4848 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4849 reinterpret_cast<char*>(0xABC0)),
4853 // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4854 TEST(EqAssertionTest, WideCharPointer) {
4855 wchar_t* const p0 = nullptr;
4856 // Only way to get the Nokia compiler to compile the cast
4857 // is to have a separate void* variable first. Putting
4858 // the two casts on the same line doesn't work, neither does
4859 // a direct C-style to char*.
4860 void* pv1 = (void*)0x1234; // NOLINT
4861 void* pv2 = (void*)0xABC0; // NOLINT
4862 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4863 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4866 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:");
4867 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:");
4868 void* pv3 = (void*)0x1234; // NOLINT
4869 void* pv4 = (void*)0xABC0; // NOLINT
4870 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4871 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4872 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), "p4");
4875 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4876 TEST(EqAssertionTest, OtherPointer) {
4877 ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));
4878 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),
4879 reinterpret_cast<const int*>(0x1234)),
4883 // A class that supports binary comparison operators but not streaming.
4884 class UnprintableChar {
4886 explicit UnprintableChar(char ch) : char_(ch) {}
4888 bool operator==(const UnprintableChar& rhs) const {
4889 return char_ == rhs.char_;
4891 bool operator!=(const UnprintableChar& rhs) const {
4892 return char_ != rhs.char_;
4894 bool operator<(const UnprintableChar& rhs) const { return char_ < rhs.char_; }
4895 bool operator<=(const UnprintableChar& rhs) const {
4896 return char_ <= rhs.char_;
4898 bool operator>(const UnprintableChar& rhs) const { return char_ > rhs.char_; }
4899 bool operator>=(const UnprintableChar& rhs) const {
4900 return char_ >= rhs.char_;
4907 // Tests that ASSERT_EQ() and friends don't require the arguments to
4909 TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4910 const UnprintableChar x('x'), y('y');
4918 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
4919 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
4920 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
4921 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
4922 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
4924 // Code tested by EXPECT_FATAL_FAILURE cannot reference local
4925 // variables, so we have to write UnprintableChar('x') instead of x.
4926 #ifndef __BORLANDC__
4927 // ICE's in C++Builder.
4928 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
4929 "1-byte object <78>");
4930 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4931 "1-byte object <78>");
4933 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4934 "1-byte object <79>");
4935 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4936 "1-byte object <78>");
4937 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4938 "1-byte object <79>");
4941 // Tests the FRIEND_TEST macro.
4943 // This class has a private member we want to test. We will test it
4944 // both in a TEST and in a TEST_F.
4950 int Bar() const { return 1; }
4952 // Declares the friend tests that can access the private member
4954 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4955 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4958 // Tests that the FRIEND_TEST declaration allows a TEST to access a
4959 // class's private members. This should compile.
4960 TEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); }
4962 // The fixture needed to test using FRIEND_TEST with TEST_F.
4963 class FRIEND_TEST_Test2 : public Test {
4968 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
4969 // class's private members. This should compile.
4970 TEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); }
4972 // Tests the life cycle of Test objects.
4974 // The test fixture for testing the life cycle of Test objects.
4976 // This class counts the number of live test objects that uses this
4978 class TestLifeCycleTest : public Test {
4980 // Constructor. Increments the number of test objects that uses
4982 TestLifeCycleTest() { count_++; }
4984 // Destructor. Decrements the number of test objects that uses this
4986 ~TestLifeCycleTest() override { count_--; }
4988 // Returns the number of live test objects that uses this fixture.
4989 int count() const { return count_; }
4995 int TestLifeCycleTest::count_ = 0;
4997 // Tests the life cycle of test objects.
4998 TEST_F(TestLifeCycleTest, Test1) {
4999 // There should be only one test object in this test case that's
5001 ASSERT_EQ(1, count());
5004 // Tests the life cycle of test objects.
5005 TEST_F(TestLifeCycleTest, Test2) {
5006 // After Test1 is done and Test2 is started, there should still be
5007 // only one live test object, as the object for Test1 should've been
5009 ASSERT_EQ(1, count());
5014 // Tests that the copy constructor works when it is NOT optimized away by
5016 TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5017 // Checks that the copy constructor doesn't try to dereference NULL pointers
5018 // in the source object.
5019 AssertionResult r1 = AssertionSuccess();
5020 AssertionResult r2 = r1;
5021 // The following line is added to prevent the compiler from optimizing
5022 // away the constructor call.
5025 AssertionResult r3 = r1;
5026 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
5027 EXPECT_STREQ("abc", r1.message());
5030 // Tests that AssertionSuccess and AssertionFailure construct
5031 // AssertionResult objects as expected.
5032 TEST(AssertionResultTest, ConstructionWorks) {
5033 AssertionResult r1 = AssertionSuccess();
5035 EXPECT_STREQ("", r1.message());
5037 AssertionResult r2 = AssertionSuccess() << "abc";
5039 EXPECT_STREQ("abc", r2.message());
5041 AssertionResult r3 = AssertionFailure();
5043 EXPECT_STREQ("", r3.message());
5045 AssertionResult r4 = AssertionFailure() << "def";
5047 EXPECT_STREQ("def", r4.message());
5049 AssertionResult r5 = AssertionFailure(Message() << "ghi");
5051 EXPECT_STREQ("ghi", r5.message());
5054 // Tests that the negation flips the predicate result but keeps the message.
5055 TEST(AssertionResultTest, NegationWorks) {
5056 AssertionResult r1 = AssertionSuccess() << "abc";
5058 EXPECT_STREQ("abc", (!r1).message());
5060 AssertionResult r2 = AssertionFailure() << "def";
5062 EXPECT_STREQ("def", (!r2).message());
5065 TEST(AssertionResultTest, StreamingWorks) {
5066 AssertionResult r = AssertionSuccess();
5067 r << "abc" << 'd' << 0 << true;
5068 EXPECT_STREQ("abcd0true", r.message());
5071 TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5072 AssertionResult r = AssertionSuccess();
5073 r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5074 EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5077 // The next test uses explicit conversion operators
5079 TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5080 struct ExplicitlyConvertibleToBool {
5081 explicit operator bool() const { return value; }
5084 ExplicitlyConvertibleToBool v1 = {false};
5085 ExplicitlyConvertibleToBool v2 = {true};
5090 struct ConvertibleToAssertionResult {
5091 operator AssertionResult() const { return AssertionResult(true); }
5094 TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5095 ConvertibleToAssertionResult obj;
5099 // Tests streaming a user type whose definition and operator << are
5100 // both in the global namespace.
5103 explicit Base(int an_x) : x_(an_x) {}
5104 int x() const { return x_; }
5109 std::ostream& operator<<(std::ostream& os, const Base& val) {
5110 return os << val.x();
5112 std::ostream& operator<<(std::ostream& os, const Base* pointer) {
5113 return os << "(" << pointer->x() << ")";
5116 TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5120 msg << a << &a; // Uses ::operator<<.
5121 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5124 // Tests streaming a user type whose definition and operator<< are
5125 // both in an unnamed namespace.
5127 class MyTypeInUnnamedNameSpace : public Base {
5129 explicit MyTypeInUnnamedNameSpace(int an_x) : Base(an_x) {}
5131 std::ostream& operator<<(std::ostream& os,
5132 const MyTypeInUnnamedNameSpace& val) {
5133 return os << val.x();
5135 std::ostream& operator<<(std::ostream& os,
5136 const MyTypeInUnnamedNameSpace* pointer) {
5137 return os << "(" << pointer->x() << ")";
5141 TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5143 MyTypeInUnnamedNameSpace a(1);
5145 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
5146 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5149 // Tests streaming a user type whose definition and operator<< are
5150 // both in a user namespace.
5151 namespace namespace1 {
5152 class MyTypeInNameSpace1 : public Base {
5154 explicit MyTypeInNameSpace1(int an_x) : Base(an_x) {}
5156 std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1& val) {
5157 return os << val.x();
5159 std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1* pointer) {
5160 return os << "(" << pointer->x() << ")";
5162 } // namespace namespace1
5164 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5166 namespace1::MyTypeInNameSpace1 a(1);
5168 msg << a << &a; // Uses namespace1::operator<<.
5169 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5172 // Tests streaming a user type whose definition is in a user namespace
5173 // but whose operator<< is in the global namespace.
5174 namespace namespace2 {
5175 class MyTypeInNameSpace2 : public ::Base {
5177 explicit MyTypeInNameSpace2(int an_x) : Base(an_x) {}
5179 } // namespace namespace2
5180 std::ostream& operator<<(std::ostream& os,
5181 const namespace2::MyTypeInNameSpace2& val) {
5182 return os << val.x();
5184 std::ostream& operator<<(std::ostream& os,
5185 const namespace2::MyTypeInNameSpace2* pointer) {
5186 return os << "(" << pointer->x() << ")";
5189 TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5191 namespace2::MyTypeInNameSpace2 a(1);
5193 msg << a << &a; // Uses ::operator<<.
5194 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5197 // Tests streaming NULL pointers to testing::Message.
5198 TEST(MessageTest, NullPointers) {
5200 char* const p1 = nullptr;
5201 unsigned char* const p2 = nullptr;
5203 double* p4 = nullptr;
5205 Message* p6 = nullptr;
5207 msg << p1 << p2 << p3 << p4 << p5 << p6;
5208 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", msg.GetString().c_str());
5211 // Tests streaming wide strings to testing::Message.
5212 TEST(MessageTest, WideStrings) {
5213 // Streams a NULL of type const wchar_t*.
5214 const wchar_t* const_wstr = nullptr;
5215 EXPECT_STREQ("(null)", (Message() << const_wstr).GetString().c_str());
5217 // Streams a NULL of type wchar_t*.
5218 wchar_t* wstr = nullptr;
5219 EXPECT_STREQ("(null)", (Message() << wstr).GetString().c_str());
5221 // Streams a non-NULL of type const wchar_t*.
5222 const_wstr = L"abc\x8119";
5223 EXPECT_STREQ("abc\xe8\x84\x99",
5224 (Message() << const_wstr).GetString().c_str());
5226 // Streams a non-NULL of type wchar_t*.
5227 wstr = const_cast<wchar_t*>(const_wstr);
5228 EXPECT_STREQ("abc\xe8\x84\x99", (Message() << wstr).GetString().c_str());
5231 // This line tests that we can define tests in the testing namespace.
5234 // Tests the TestInfo class.
5236 class TestInfoTest : public Test {
5238 static const TestInfo* GetTestInfo(const char* test_name) {
5239 const TestSuite* const test_suite =
5240 GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr);
5242 for (int i = 0; i < test_suite->total_test_count(); ++i) {
5243 const TestInfo* const test_info = test_suite->GetTestInfo(i);
5244 if (strcmp(test_name, test_info->name()) == 0) return test_info;
5249 static const TestResult* GetTestResult(const TestInfo* test_info) {
5250 return test_info->result();
5254 // Tests TestInfo::test_case_name() and TestInfo::name().
5255 TEST_F(TestInfoTest, Names) {
5256 const TestInfo* const test_info = GetTestInfo("Names");
5258 ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
5259 ASSERT_STREQ("Names", test_info->name());
5262 // Tests TestInfo::result().
5263 TEST_F(TestInfoTest, result) {
5264 const TestInfo* const test_info = GetTestInfo("result");
5266 // Initially, there is no TestPartResult for this test.
5267 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5269 // After the previous assertion, there is still none.
5270 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5273 #define VERIFY_CODE_LOCATION \
5274 const int expected_line = __LINE__ - 1; \
5275 const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
5276 ASSERT_TRUE(test_info); \
5277 EXPECT_STREQ(__FILE__, test_info->file()); \
5278 EXPECT_EQ(expected_line, test_info->line())
5281 TEST(CodeLocationForTEST, Verify) {
5282 VERIFY_CODE_LOCATION;
5285 class CodeLocationForTESTF : public Test {};
5287 TEST_F(CodeLocationForTESTF, Verify) {
5288 VERIFY_CODE_LOCATION;
5291 class CodeLocationForTESTP : public TestWithParam<int> {};
5293 TEST_P(CodeLocationForTESTP, Verify) {
5294 VERIFY_CODE_LOCATION;
5297 INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
5299 template <typename T>
5300 class CodeLocationForTYPEDTEST : public Test {};
5302 TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);
5304 TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
5305 VERIFY_CODE_LOCATION;
5308 template <typename T>
5309 class CodeLocationForTYPEDTESTP : public Test {};
5311 TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
5313 TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
5314 VERIFY_CODE_LOCATION;
5317 REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
5319 INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
5321 #undef VERIFY_CODE_LOCATION
5324 // Tests setting up and tearing down a test case.
5325 // Legacy API is deprecated but still available
5326 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5327 class SetUpTestCaseTest : public Test {
5329 // This will be called once before the first test in this test case
5331 static void SetUpTestCase() {
5332 printf("Setting up the test case . . .\n");
5334 // Initializes some shared resource. In this simple example, we
5335 // just create a C string. More complex stuff can be done if
5337 shared_resource_ = "123";
5339 // Increments the number of test cases that have been set up.
5342 // SetUpTestCase() should be called only once.
5343 EXPECT_EQ(1, counter_);
5346 // This will be called once after the last test in this test case is
5348 static void TearDownTestCase() {
5349 printf("Tearing down the test case . . .\n");
5351 // Decrements the number of test cases that have been set up.
5354 // TearDownTestCase() should be called only once.
5355 EXPECT_EQ(0, counter_);
5357 // Cleans up the shared resource.
5358 shared_resource_ = nullptr;
5361 // This will be called before each test in this test case.
5362 void SetUp() override {
5363 // SetUpTestCase() should be called only once, so counter_ should
5365 EXPECT_EQ(1, counter_);
5368 // Number of test cases that have been set up.
5369 static int counter_;
5371 // Some resource to be shared by all tests in this test case.
5372 static const char* shared_resource_;
5375 int SetUpTestCaseTest::counter_ = 0;
5376 const char* SetUpTestCaseTest::shared_resource_ = nullptr;
5378 // A test that uses the shared resource.
5379 TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
5381 // Another test that uses the shared resource.
5382 TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); }
5383 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5385 // Tests SetupTestSuite/TearDown TestSuite
5386 class SetUpTestSuiteTest : public Test {
5388 // This will be called once before the first test in this test case
5390 static void SetUpTestSuite() {
5391 printf("Setting up the test suite . . .\n");
5393 // Initializes some shared resource. In this simple example, we
5394 // just create a C string. More complex stuff can be done if
5396 shared_resource_ = "123";
5398 // Increments the number of test cases that have been set up.
5401 // SetUpTestSuite() should be called only once.
5402 EXPECT_EQ(1, counter_);
5405 // This will be called once after the last test in this test case is
5407 static void TearDownTestSuite() {
5408 printf("Tearing down the test suite . . .\n");
5410 // Decrements the number of test suites that have been set up.
5413 // TearDownTestSuite() should be called only once.
5414 EXPECT_EQ(0, counter_);
5416 // Cleans up the shared resource.
5417 shared_resource_ = nullptr;
5420 // This will be called before each test in this test case.
5421 void SetUp() override {
5422 // SetUpTestSuite() should be called only once, so counter_ should
5424 EXPECT_EQ(1, counter_);
5427 // Number of test suites that have been set up.
5428 static int counter_;
5430 // Some resource to be shared by all tests in this test case.
5431 static const char* shared_resource_;
5434 int SetUpTestSuiteTest::counter_ = 0;
5435 const char* SetUpTestSuiteTest::shared_resource_ = nullptr;
5437 // A test that uses the shared resource.
5438 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) {
5439 EXPECT_STRNE(nullptr, shared_resource_);
5442 // Another test that uses the shared resource.
5443 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
5444 EXPECT_STREQ("123", shared_resource_);
5447 // The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.
5449 // The Flags struct stores a copy of all Google Test flags.
5451 // Constructs a Flags struct where each flag has its default value.
5453 : also_run_disabled_tests(false),
5454 break_on_failure(false),
5455 catch_exceptions(false),
5456 death_test_use_fork(false),
5465 recreate_environments_when_repeating(true),
5467 stack_trace_depth(kMaxStackTraceDepth),
5468 stream_result_to(""),
5469 throw_on_failure(false) {}
5473 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5475 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5477 flags.also_run_disabled_tests = also_run_disabled_tests;
5481 // Creates a Flags struct where the gtest_break_on_failure flag has
5483 static Flags BreakOnFailure(bool break_on_failure) {
5485 flags.break_on_failure = break_on_failure;
5489 // Creates a Flags struct where the gtest_catch_exceptions flag has
5491 static Flags CatchExceptions(bool catch_exceptions) {
5493 flags.catch_exceptions = catch_exceptions;
5497 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5499 static Flags DeathTestUseFork(bool death_test_use_fork) {
5501 flags.death_test_use_fork = death_test_use_fork;
5505 // Creates a Flags struct where the gtest_fail_fast flag has
5507 static Flags FailFast(bool fail_fast) {
5509 flags.fail_fast = fail_fast;
5513 // Creates a Flags struct where the gtest_filter flag has the given
5515 static Flags Filter(const char* filter) {
5517 flags.filter = filter;
5521 // Creates a Flags struct where the gtest_list_tests flag has the
5523 static Flags ListTests(bool list_tests) {
5525 flags.list_tests = list_tests;
5529 // Creates a Flags struct where the gtest_output flag has the given
5531 static Flags Output(const char* output) {
5533 flags.output = output;
5537 // Creates a Flags struct where the gtest_brief flag has the given
5539 static Flags Brief(bool brief) {
5541 flags.brief = brief;
5545 // Creates a Flags struct where the gtest_print_time flag has the given
5547 static Flags PrintTime(bool print_time) {
5549 flags.print_time = print_time;
5553 // Creates a Flags struct where the gtest_random_seed flag has the given
5555 static Flags RandomSeed(int32_t random_seed) {
5557 flags.random_seed = random_seed;
5561 // Creates a Flags struct where the gtest_repeat flag has the given
5563 static Flags Repeat(int32_t repeat) {
5565 flags.repeat = repeat;
5569 // Creates a Flags struct where the gtest_recreate_environments_when_repeating
5570 // flag has the given value.
5571 static Flags RecreateEnvironmentsWhenRepeating(
5572 bool recreate_environments_when_repeating) {
5574 flags.recreate_environments_when_repeating =
5575 recreate_environments_when_repeating;
5579 // Creates a Flags struct where the gtest_shuffle flag has the given
5581 static Flags Shuffle(bool shuffle) {
5583 flags.shuffle = shuffle;
5587 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5589 static Flags StackTraceDepth(int32_t stack_trace_depth) {
5591 flags.stack_trace_depth = stack_trace_depth;
5595 // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5597 static Flags StreamResultTo(const char* stream_result_to) {
5599 flags.stream_result_to = stream_result_to;
5603 // Creates a Flags struct where the gtest_throw_on_failure flag has
5605 static Flags ThrowOnFailure(bool throw_on_failure) {
5607 flags.throw_on_failure = throw_on_failure;
5611 // These fields store the flag values.
5612 bool also_run_disabled_tests;
5613 bool break_on_failure;
5614 bool catch_exceptions;
5615 bool death_test_use_fork;
5622 int32_t random_seed;
5624 bool recreate_environments_when_repeating;
5626 int32_t stack_trace_depth;
5627 const char* stream_result_to;
5628 bool throw_on_failure;
5631 // Fixture for testing ParseGoogleTestFlagsOnly().
5632 class ParseFlagsTest : public Test {
5634 // Clears the flags before each test.
5635 void SetUp() override {
5636 GTEST_FLAG_SET(also_run_disabled_tests, false);
5637 GTEST_FLAG_SET(break_on_failure, false);
5638 GTEST_FLAG_SET(catch_exceptions, false);
5639 GTEST_FLAG_SET(death_test_use_fork, false);
5640 GTEST_FLAG_SET(fail_fast, false);
5641 GTEST_FLAG_SET(filter, "");
5642 GTEST_FLAG_SET(list_tests, false);
5643 GTEST_FLAG_SET(output, "");
5644 GTEST_FLAG_SET(brief, false);
5645 GTEST_FLAG_SET(print_time, true);
5646 GTEST_FLAG_SET(random_seed, 0);
5647 GTEST_FLAG_SET(repeat, 1);
5648 GTEST_FLAG_SET(recreate_environments_when_repeating, true);
5649 GTEST_FLAG_SET(shuffle, false);
5650 GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
5651 GTEST_FLAG_SET(stream_result_to, "");
5652 GTEST_FLAG_SET(throw_on_failure, false);
5655 // Asserts that two narrow or wide string arrays are equal.
5656 template <typename CharType>
5657 static void AssertStringArrayEq(int size1, CharType** array1, int size2,
5658 CharType** array2) {
5659 ASSERT_EQ(size1, size2) << " Array sizes different.";
5661 for (int i = 0; i != size1; i++) {
5662 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5666 // Verifies that the flag values match the expected values.
5667 static void CheckFlags(const Flags& expected) {
5668 EXPECT_EQ(expected.also_run_disabled_tests,
5669 GTEST_FLAG_GET(also_run_disabled_tests));
5670 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure));
5671 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions));
5672 EXPECT_EQ(expected.death_test_use_fork,
5673 GTEST_FLAG_GET(death_test_use_fork));
5674 EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast));
5675 EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str());
5676 EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests));
5677 EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str());
5678 EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief));
5679 EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time));
5680 EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed));
5681 EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat));
5682 EXPECT_EQ(expected.recreate_environments_when_repeating,
5683 GTEST_FLAG_GET(recreate_environments_when_repeating));
5684 EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle));
5685 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth));
5686 EXPECT_STREQ(expected.stream_result_to,
5687 GTEST_FLAG_GET(stream_result_to).c_str());
5688 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure));
5691 // Parses a command line (specified by argc1 and argv1), then
5692 // verifies that the flag values are expected and that the
5693 // recognized flags are removed from the command line.
5694 template <typename CharType>
5695 static void TestParsingFlags(int argc1, const CharType** argv1, int argc2,
5696 const CharType** argv2, const Flags& expected,
5697 bool should_print_help) {
5698 const bool saved_help_flag = ::testing::internal::g_help_flag;
5699 ::testing::internal::g_help_flag = false;
5701 #if GTEST_HAS_STREAM_REDIRECTION
5705 // Parses the command line.
5706 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5708 #if GTEST_HAS_STREAM_REDIRECTION
5709 const std::string captured_stdout = GetCapturedStdout();
5712 // Verifies the flag values.
5713 CheckFlags(expected);
5715 // Verifies that the recognized flags are removed from the command
5717 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5719 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5720 // help message for the flags it recognizes.
5721 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5723 #if GTEST_HAS_STREAM_REDIRECTION
5724 const char* const expected_help_fragment =
5725 "This program contains tests written using";
5726 if (should_print_help) {
5727 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5729 EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment,
5732 #endif // GTEST_HAS_STREAM_REDIRECTION
5734 ::testing::internal::g_help_flag = saved_help_flag;
5737 // This macro wraps TestParsingFlags s.t. the user doesn't need
5738 // to specify the array sizes.
5740 #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5741 TestParsingFlags(sizeof(argv1) / sizeof(*argv1) - 1, argv1, \
5742 sizeof(argv2) / sizeof(*argv2) - 1, argv2, expected, \
5746 // Tests parsing an empty command line.
5747 TEST_F(ParseFlagsTest, Empty) {
5748 const char* argv[] = {nullptr};
5750 const char* argv2[] = {nullptr};
5752 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5755 // Tests parsing a command line that has no flag.
5756 TEST_F(ParseFlagsTest, NoFlag) {
5757 const char* argv[] = {"foo.exe", nullptr};
5759 const char* argv2[] = {"foo.exe", nullptr};
5761 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5764 // Tests parsing --gtest_fail_fast.
5765 TEST_F(ParseFlagsTest, FailFast) {
5766 const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
5768 const char* argv2[] = {"foo.exe", nullptr};
5770 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
5773 // Tests parsing an empty --gtest_filter flag.
5774 TEST_F(ParseFlagsTest, FilterEmpty) {
5775 const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
5777 const char* argv2[] = {"foo.exe", nullptr};
5779 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5782 // Tests parsing a non-empty --gtest_filter flag.
5783 TEST_F(ParseFlagsTest, FilterNonEmpty) {
5784 const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr};
5786 const char* argv2[] = {"foo.exe", nullptr};
5788 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5791 // Tests parsing --gtest_break_on_failure.
5792 TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {
5793 const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr};
5795 const char* argv2[] = {"foo.exe", nullptr};
5797 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5800 // Tests parsing --gtest_break_on_failure=0.
5801 TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {
5802 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr};
5804 const char* argv2[] = {"foo.exe", nullptr};
5806 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5809 // Tests parsing --gtest_break_on_failure=f.
5810 TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {
5811 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr};
5813 const char* argv2[] = {"foo.exe", nullptr};
5815 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5818 // Tests parsing --gtest_break_on_failure=F.
5819 TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {
5820 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr};
5822 const char* argv2[] = {"foo.exe", nullptr};
5824 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5827 // Tests parsing a --gtest_break_on_failure flag that has a "true"
5829 TEST_F(ParseFlagsTest, BreakOnFailureTrue) {
5830 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr};
5832 const char* argv2[] = {"foo.exe", nullptr};
5834 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5837 // Tests parsing --gtest_catch_exceptions.
5838 TEST_F(ParseFlagsTest, CatchExceptions) {
5839 const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr};
5841 const char* argv2[] = {"foo.exe", nullptr};
5843 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5846 // Tests parsing --gtest_death_test_use_fork.
5847 TEST_F(ParseFlagsTest, DeathTestUseFork) {
5848 const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr};
5850 const char* argv2[] = {"foo.exe", nullptr};
5852 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5855 // Tests having the same flag twice with different values. The
5856 // expected behavior is that the one coming last takes precedence.
5857 TEST_F(ParseFlagsTest, DuplicatedFlags) {
5858 const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b",
5861 const char* argv2[] = {"foo.exe", nullptr};
5863 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5866 // Tests having an unrecognized flag on the command line.
5867 TEST_F(ParseFlagsTest, UnrecognizedFlag) {
5868 const char* argv[] = {"foo.exe", "--gtest_break_on_failure",
5869 "bar", // Unrecognized by Google Test.
5870 "--gtest_filter=b", nullptr};
5872 const char* argv2[] = {"foo.exe", "bar", nullptr};
5875 flags.break_on_failure = true;
5877 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5880 // Tests having a --gtest_list_tests flag
5881 TEST_F(ParseFlagsTest, ListTestsFlag) {
5882 const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr};
5884 const char* argv2[] = {"foo.exe", nullptr};
5886 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5889 // Tests having a --gtest_list_tests flag with a "true" value
5890 TEST_F(ParseFlagsTest, ListTestsTrue) {
5891 const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr};
5893 const char* argv2[] = {"foo.exe", nullptr};
5895 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5898 // Tests having a --gtest_list_tests flag with a "false" value
5899 TEST_F(ParseFlagsTest, ListTestsFalse) {
5900 const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr};
5902 const char* argv2[] = {"foo.exe", nullptr};
5904 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5907 // Tests parsing --gtest_list_tests=f.
5908 TEST_F(ParseFlagsTest, ListTestsFalse_f) {
5909 const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr};
5911 const char* argv2[] = {"foo.exe", nullptr};
5913 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5916 // Tests parsing --gtest_list_tests=F.
5917 TEST_F(ParseFlagsTest, ListTestsFalse_F) {
5918 const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr};
5920 const char* argv2[] = {"foo.exe", nullptr};
5922 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5925 // Tests parsing --gtest_output=xml
5926 TEST_F(ParseFlagsTest, OutputXml) {
5927 const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
5929 const char* argv2[] = {"foo.exe", nullptr};
5931 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
5934 // Tests parsing --gtest_output=xml:file
5935 TEST_F(ParseFlagsTest, OutputXmlFile) {
5936 const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr};
5938 const char* argv2[] = {"foo.exe", nullptr};
5940 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
5943 // Tests parsing --gtest_output=xml:directory/path/
5944 TEST_F(ParseFlagsTest, OutputXmlDirectory) {
5945 const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/",
5948 const char* argv2[] = {"foo.exe", nullptr};
5950 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"),
5954 // Tests having a --gtest_brief flag
5955 TEST_F(ParseFlagsTest, BriefFlag) {
5956 const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
5958 const char* argv2[] = {"foo.exe", nullptr};
5960 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
5963 // Tests having a --gtest_brief flag with a "true" value
5964 TEST_F(ParseFlagsTest, BriefFlagTrue) {
5965 const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
5967 const char* argv2[] = {"foo.exe", nullptr};
5969 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
5972 // Tests having a --gtest_brief flag with a "false" value
5973 TEST_F(ParseFlagsTest, BriefFlagFalse) {
5974 const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
5976 const char* argv2[] = {"foo.exe", nullptr};
5978 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
5981 // Tests having a --gtest_print_time flag
5982 TEST_F(ParseFlagsTest, PrintTimeFlag) {
5983 const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
5985 const char* argv2[] = {"foo.exe", nullptr};
5987 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
5990 // Tests having a --gtest_print_time flag with a "true" value
5991 TEST_F(ParseFlagsTest, PrintTimeTrue) {
5992 const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr};
5994 const char* argv2[] = {"foo.exe", nullptr};
5996 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
5999 // Tests having a --gtest_print_time flag with a "false" value
6000 TEST_F(ParseFlagsTest, PrintTimeFalse) {
6001 const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr};
6003 const char* argv2[] = {"foo.exe", nullptr};
6005 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6008 // Tests parsing --gtest_print_time=f.
6009 TEST_F(ParseFlagsTest, PrintTimeFalse_f) {
6010 const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr};
6012 const char* argv2[] = {"foo.exe", nullptr};
6014 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6017 // Tests parsing --gtest_print_time=F.
6018 TEST_F(ParseFlagsTest, PrintTimeFalse_F) {
6019 const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr};
6021 const char* argv2[] = {"foo.exe", nullptr};
6023 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6026 // Tests parsing --gtest_random_seed=number
6027 TEST_F(ParseFlagsTest, RandomSeed) {
6028 const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr};
6030 const char* argv2[] = {"foo.exe", nullptr};
6032 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6035 // Tests parsing --gtest_repeat=number
6036 TEST_F(ParseFlagsTest, Repeat) {
6037 const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr};
6039 const char* argv2[] = {"foo.exe", nullptr};
6041 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
6044 // Tests parsing --gtest_recreate_environments_when_repeating
6045 TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) {
6046 const char* argv[] = {
6048 "--gtest_recreate_environments_when_repeating=0",
6052 const char* argv2[] = {"foo.exe", nullptr};
6054 GTEST_TEST_PARSING_FLAGS_(
6055 argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false);
6058 // Tests having a --gtest_also_run_disabled_tests flag
6059 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
6060 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
6062 const char* argv2[] = {"foo.exe", nullptr};
6064 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
6068 // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6069 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {
6070 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1",
6073 const char* argv2[] = {"foo.exe", nullptr};
6075 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
6079 // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6080 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {
6081 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0",
6084 const char* argv2[] = {"foo.exe", nullptr};
6086 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false),
6090 // Tests parsing --gtest_shuffle.
6091 TEST_F(ParseFlagsTest, ShuffleWithoutValue) {
6092 const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr};
6094 const char* argv2[] = {"foo.exe", nullptr};
6096 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6099 // Tests parsing --gtest_shuffle=0.
6100 TEST_F(ParseFlagsTest, ShuffleFalse_0) {
6101 const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr};
6103 const char* argv2[] = {"foo.exe", nullptr};
6105 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6108 // Tests parsing a --gtest_shuffle flag that has a "true" definition.
6109 TEST_F(ParseFlagsTest, ShuffleTrue) {
6110 const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr};
6112 const char* argv2[] = {"foo.exe", nullptr};
6114 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6117 // Tests parsing --gtest_stack_trace_depth=number.
6118 TEST_F(ParseFlagsTest, StackTraceDepth) {
6119 const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr};
6121 const char* argv2[] = {"foo.exe", nullptr};
6123 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6126 TEST_F(ParseFlagsTest, StreamResultTo) {
6127 const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234",
6130 const char* argv2[] = {"foo.exe", nullptr};
6132 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6133 Flags::StreamResultTo("localhost:1234"), false);
6136 // Tests parsing --gtest_throw_on_failure.
6137 TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
6138 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr};
6140 const char* argv2[] = {"foo.exe", nullptr};
6142 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6145 // Tests parsing --gtest_throw_on_failure=0.
6146 TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {
6147 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr};
6149 const char* argv2[] = {"foo.exe", nullptr};
6151 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
6154 // Tests parsing a --gtest_throw_on_failure flag that has a "true"
6156 TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
6157 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr};
6159 const char* argv2[] = {"foo.exe", nullptr};
6161 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6164 // Tests parsing a bad --gtest_filter flag.
6165 TEST_F(ParseFlagsTest, FilterBad) {
6166 const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
6168 const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
6170 #if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST
6171 // Invalid flag arguments are a fatal error when using the Abseil Flags.
6172 EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true),
6173 testing::ExitedWithCode(1),
6174 "ERROR: Missing the value for the flag 'gtest_filter'");
6175 #elif !GTEST_HAS_ABSL
6176 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
6178 static_cast<void>(argv);
6179 static_cast<void>(argv2);
6183 // Tests parsing --gtest_output (invalid).
6184 TEST_F(ParseFlagsTest, OutputEmpty) {
6185 const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
6187 const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
6189 #if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST
6190 // Invalid flag arguments are a fatal error when using the Abseil Flags.
6191 EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true),
6192 testing::ExitedWithCode(1),
6193 "ERROR: Missing the value for the flag 'gtest_output'");
6194 #elif !GTEST_HAS_ABSL
6195 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
6197 static_cast<void>(argv);
6198 static_cast<void>(argv2);
6203 TEST_F(ParseFlagsTest, AbseilPositionalFlags) {
6204 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", "--",
6205 "--other_flag", nullptr};
6207 // When using Abseil flags, it should be possible to pass flags not recognized
6208 // using "--" to delimit positional arguments. These flags should be returned
6210 const char* argv2[] = {"foo.exe", "--other_flag", nullptr};
6212 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6216 #if GTEST_OS_WINDOWS
6217 // Tests parsing wide strings.
6218 TEST_F(ParseFlagsTest, WideStrings) {
6219 const wchar_t* argv[] = {L"foo.exe",
6220 L"--gtest_filter=Foo*",
6221 L"--gtest_list_tests=1",
6222 L"--gtest_break_on_failure",
6223 L"--non_gtest_flag",
6226 const wchar_t* argv2[] = {L"foo.exe", L"--non_gtest_flag", NULL};
6228 Flags expected_flags;
6229 expected_flags.break_on_failure = true;
6230 expected_flags.filter = "Foo*";
6231 expected_flags.list_tests = true;
6233 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6235 #endif // GTEST_OS_WINDOWS
6237 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6238 class FlagfileTest : public ParseFlagsTest {
6240 void SetUp() override {
6241 ParseFlagsTest::SetUp();
6243 testdata_path_.Set(internal::FilePath(
6244 testing::TempDir() + internal::GetCurrentExecutableName().string() +
6246 testing::internal::posix::RmDir(testdata_path_.c_str());
6247 EXPECT_TRUE(testdata_path_.CreateFolder());
6250 void TearDown() override {
6251 testing::internal::posix::RmDir(testdata_path_.c_str());
6252 ParseFlagsTest::TearDown();
6255 internal::FilePath CreateFlagfile(const char* contents) {
6256 internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
6257 testdata_path_, internal::FilePath("unique"), "txt"));
6258 FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
6259 fprintf(f, "%s", contents);
6265 internal::FilePath testdata_path_;
6268 // Tests an empty flagfile.
6269 TEST_F(FlagfileTest, Empty) {
6270 internal::FilePath flagfile_path(CreateFlagfile(""));
6271 std::string flagfile_flag =
6272 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6274 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6276 const char* argv2[] = {"foo.exe", nullptr};
6278 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
6281 // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
6282 TEST_F(FlagfileTest, FilterNonEmpty) {
6283 internal::FilePath flagfile_path(
6284 CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc"));
6285 std::string flagfile_flag =
6286 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6288 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6290 const char* argv2[] = {"foo.exe", nullptr};
6292 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
6295 // Tests passing several flags via --gtest_flagfile.
6296 TEST_F(FlagfileTest, SeveralFlags) {
6297 internal::FilePath flagfile_path(
6298 CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc\n"
6299 "--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
6300 "--" GTEST_FLAG_PREFIX_ "list_tests"));
6301 std::string flagfile_flag =
6302 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6304 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6306 const char* argv2[] = {"foo.exe", nullptr};
6308 Flags expected_flags;
6309 expected_flags.break_on_failure = true;
6310 expected_flags.filter = "abc";
6311 expected_flags.list_tests = true;
6313 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6315 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6317 // Tests current_test_info() in UnitTest.
6318 class CurrentTestInfoTest : public Test {
6320 // Tests that current_test_info() returns NULL before the first test in
6321 // the test case is run.
6322 static void SetUpTestSuite() {
6323 // There should be no tests running at this point.
6324 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
6325 EXPECT_TRUE(test_info == nullptr)
6326 << "There should be no tests running at this point.";
6329 // Tests that current_test_info() returns NULL after the last test in
6330 // the test case has run.
6331 static void TearDownTestSuite() {
6332 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
6333 EXPECT_TRUE(test_info == nullptr)
6334 << "There should be no tests running at this point.";
6338 // Tests that current_test_info() returns TestInfo for currently running
6339 // test by checking the expected test name against the actual one.
6340 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
6341 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
6342 ASSERT_TRUE(nullptr != test_info)
6343 << "There is a test running so we should have a valid TestInfo.";
6344 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6345 << "Expected the name of the currently running test suite.";
6346 EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
6347 << "Expected the name of the currently running test.";
6350 // Tests that current_test_info() returns TestInfo for currently running
6351 // test by checking the expected test name against the actual one. We
6352 // use this test to see that the TestInfo object actually changed from
6353 // the previous invocation.
6354 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
6355 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
6356 ASSERT_TRUE(nullptr != test_info)
6357 << "There is a test running so we should have a valid TestInfo.";
6358 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6359 << "Expected the name of the currently running test suite.";
6360 EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
6361 << "Expected the name of the currently running test.";
6364 } // namespace testing
6366 // These two lines test that we can define tests in a namespace that
6367 // has the name "testing" and is nested in another namespace.
6368 namespace my_namespace {
6371 // Makes sure that TEST knows to use ::testing::Test instead of
6372 // ::my_namespace::testing::Test.
6375 // Makes sure that an assertion knows to use ::testing::Message instead of
6376 // ::my_namespace::testing::Message.
6379 // Makes sure that an assertion knows to use
6380 // ::testing::AssertionResult instead of
6381 // ::my_namespace::testing::AssertionResult.
6382 class AssertionResult {};
6384 // Tests that an assertion that should succeed works as expected.
6385 TEST(NestedTestingNamespaceTest, Success) {
6386 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6389 // Tests that an assertion that should fail works as expected.
6390 TEST(NestedTestingNamespaceTest, Failure) {
6391 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6392 "This failure is expected.");
6395 } // namespace testing
6396 } // namespace my_namespace
6398 // Tests that one can call superclass SetUp and TearDown methods--
6399 // that is, that they are not private.
6400 // No tests are based on this fixture; the test "passes" if it compiles
6402 class ProtectedFixtureMethodsTest : public Test {
6404 void SetUp() override { Test::SetUp(); }
6405 void TearDown() override { Test::TearDown(); }
6408 // StreamingAssertionsTest tests the streaming versions of a representative
6409 // sample of assertions.
6410 TEST(StreamingAssertionsTest, Unconditional) {
6411 SUCCEED() << "expected success";
6412 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6413 "expected failure");
6414 EXPECT_FATAL_FAILURE(FAIL() << "expected failure", "expected failure");
6418 // Silences warnings: "Condition is always true", "Unreachable code"
6419 #pragma option push -w-ccc -w-rch
6422 TEST(StreamingAssertionsTest, Truth) {
6423 EXPECT_TRUE(true) << "unexpected failure";
6424 ASSERT_TRUE(true) << "unexpected failure";
6425 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6426 "expected failure");
6427 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6428 "expected failure");
6431 TEST(StreamingAssertionsTest, Truth2) {
6432 EXPECT_FALSE(false) << "unexpected failure";
6433 ASSERT_FALSE(false) << "unexpected failure";
6434 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6435 "expected failure");
6436 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6437 "expected failure");
6441 // Restores warnings after previous "#pragma option push" suppressed them
6445 TEST(StreamingAssertionsTest, IntegerEquals) {
6446 EXPECT_EQ(1, 1) << "unexpected failure";
6447 ASSERT_EQ(1, 1) << "unexpected failure";
6448 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6449 "expected failure");
6450 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6451 "expected failure");
6454 TEST(StreamingAssertionsTest, IntegerLessThan) {
6455 EXPECT_LT(1, 2) << "unexpected failure";
6456 ASSERT_LT(1, 2) << "unexpected failure";
6457 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6458 "expected failure");
6459 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6460 "expected failure");
6463 TEST(StreamingAssertionsTest, StringsEqual) {
6464 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6465 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6466 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6467 "expected failure");
6468 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6469 "expected failure");
6472 TEST(StreamingAssertionsTest, StringsNotEqual) {
6473 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6474 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6475 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6476 "expected failure");
6477 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6478 "expected failure");
6481 TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6482 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6483 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6484 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6485 "expected failure");
6486 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6487 "expected failure");
6490 TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6491 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6492 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6493 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6494 "expected failure");
6495 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6496 "expected failure");
6499 TEST(StreamingAssertionsTest, FloatingPointEquals) {
6500 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6501 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6502 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6503 "expected failure");
6504 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6505 "expected failure");
6508 #if GTEST_HAS_EXCEPTIONS
6510 TEST(StreamingAssertionsTest, Throw) {
6511 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6512 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6513 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool)
6514 << "expected failure",
6515 "expected failure");
6516 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool)
6517 << "expected failure",
6518 "expected failure");
6521 TEST(StreamingAssertionsTest, NoThrow) {
6522 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6523 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6524 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger())
6525 << "expected failure",
6526 "expected failure");
6527 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << "expected failure",
6528 "expected failure");
6531 TEST(StreamingAssertionsTest, AnyThrow) {
6532 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6533 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6534 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing())
6535 << "expected failure",
6536 "expected failure");
6537 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << "expected failure",
6538 "expected failure");
6541 #endif // GTEST_HAS_EXCEPTIONS
6543 // Tests that Google Test correctly decides whether to use colors in the output.
6545 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6546 GTEST_FLAG_SET(color, "yes");
6548 SetEnv("TERM", "xterm"); // TERM supports colors.
6549 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6550 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6552 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6553 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6554 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6557 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6558 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6560 GTEST_FLAG_SET(color, "True");
6561 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6563 GTEST_FLAG_SET(color, "t");
6564 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6566 GTEST_FLAG_SET(color, "1");
6567 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6570 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6571 GTEST_FLAG_SET(color, "no");
6573 SetEnv("TERM", "xterm"); // TERM supports colors.
6574 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6575 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6577 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6578 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6579 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6582 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6583 SetEnv("TERM", "xterm"); // TERM supports colors.
6585 GTEST_FLAG_SET(color, "F");
6586 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6588 GTEST_FLAG_SET(color, "0");
6589 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6591 GTEST_FLAG_SET(color, "unknown");
6592 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6595 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6596 GTEST_FLAG_SET(color, "auto");
6598 SetEnv("TERM", "xterm"); // TERM supports colors.
6599 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6600 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6603 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6604 GTEST_FLAG_SET(color, "auto");
6606 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
6607 // On Windows, we ignore the TERM variable as it's usually not set.
6609 SetEnv("TERM", "dumb");
6610 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6613 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6615 SetEnv("TERM", "xterm");
6616 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6618 // On non-Windows platforms, we rely on TERM to determine if the
6619 // terminal supports colors.
6621 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6622 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6624 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6625 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6627 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6628 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6630 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6631 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6633 SetEnv("TERM", "xterm"); // TERM supports colors.
6634 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6636 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6637 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6639 SetEnv("TERM", "xterm-256color"); // TERM supports colors.
6640 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6642 SetEnv("TERM", "screen"); // TERM supports colors.
6643 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6645 SetEnv("TERM", "screen-256color"); // TERM supports colors.
6646 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6648 SetEnv("TERM", "tmux"); // TERM supports colors.
6649 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6651 SetEnv("TERM", "tmux-256color"); // TERM supports colors.
6652 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6654 SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
6655 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6657 SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
6658 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6660 SetEnv("TERM", "linux"); // TERM supports colors.
6661 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6663 SetEnv("TERM", "cygwin"); // TERM supports colors.
6664 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6665 #endif // GTEST_OS_WINDOWS
6668 // Verifies that StaticAssertTypeEq works in a namespace scope.
6670 static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6671 static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6672 StaticAssertTypeEq<const int, const int>();
6674 // Verifies that StaticAssertTypeEq works in a class.
6676 template <typename T>
6677 class StaticAssertTypeEqTestHelper {
6679 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6682 TEST(StaticAssertTypeEqTest, WorksInClass) {
6683 StaticAssertTypeEqTestHelper<bool>();
6686 // Verifies that StaticAssertTypeEq works inside a function.
6688 typedef int IntAlias;
6690 TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6691 StaticAssertTypeEq<int, IntAlias>();
6692 StaticAssertTypeEq<int*, IntAlias*>();
6695 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6696 EXPECT_FALSE(HasNonfatalFailure());
6699 static void FailFatally() { FAIL(); }
6701 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6703 const bool has_nonfatal_failure = HasNonfatalFailure();
6704 ClearCurrentTestPartResults();
6705 EXPECT_FALSE(has_nonfatal_failure);
6708 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6710 const bool has_nonfatal_failure = HasNonfatalFailure();
6711 ClearCurrentTestPartResults();
6712 EXPECT_TRUE(has_nonfatal_failure);
6715 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6718 const bool has_nonfatal_failure = HasNonfatalFailure();
6719 ClearCurrentTestPartResults();
6720 EXPECT_TRUE(has_nonfatal_failure);
6723 // A wrapper for calling HasNonfatalFailure outside of a test body.
6724 static bool HasNonfatalFailureHelper() {
6725 return testing::Test::HasNonfatalFailure();
6728 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6729 EXPECT_FALSE(HasNonfatalFailureHelper());
6732 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6734 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6735 ClearCurrentTestPartResults();
6736 EXPECT_TRUE(has_nonfatal_failure);
6739 TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6740 EXPECT_FALSE(HasFailure());
6743 TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6745 const bool has_failure = HasFailure();
6746 ClearCurrentTestPartResults();
6747 EXPECT_TRUE(has_failure);
6750 TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6752 const bool has_failure = HasFailure();
6753 ClearCurrentTestPartResults();
6754 EXPECT_TRUE(has_failure);
6757 TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6760 const bool has_failure = HasFailure();
6761 ClearCurrentTestPartResults();
6762 EXPECT_TRUE(has_failure);
6765 // A wrapper for calling HasFailure outside of a test body.
6766 static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6768 TEST(HasFailureTest, WorksOutsideOfTestBody) {
6769 EXPECT_FALSE(HasFailureHelper());
6772 TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6774 const bool has_failure = HasFailureHelper();
6775 ClearCurrentTestPartResults();
6776 EXPECT_TRUE(has_failure);
6779 class TestListener : public EmptyTestEventListener {
6781 TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
6782 TestListener(int* on_start_counter, bool* is_destroyed)
6783 : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {}
6785 ~TestListener() override {
6786 if (is_destroyed_) *is_destroyed_ = true;
6790 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6791 if (on_start_counter_ != nullptr) (*on_start_counter_)++;
6795 int* on_start_counter_;
6796 bool* is_destroyed_;
6799 // Tests the constructor.
6800 TEST(TestEventListenersTest, ConstructionWorks) {
6801 TestEventListeners listeners;
6803 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr);
6804 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
6805 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
6808 // Tests that the TestEventListeners destructor deletes all the listeners it
6810 TEST(TestEventListenersTest, DestructionWorks) {
6811 bool default_result_printer_is_destroyed = false;
6812 bool default_xml_printer_is_destroyed = false;
6813 bool extra_listener_is_destroyed = false;
6814 TestListener* default_result_printer =
6815 new TestListener(nullptr, &default_result_printer_is_destroyed);
6816 TestListener* default_xml_printer =
6817 new TestListener(nullptr, &default_xml_printer_is_destroyed);
6818 TestListener* extra_listener =
6819 new TestListener(nullptr, &extra_listener_is_destroyed);
6822 TestEventListeners listeners;
6823 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
6824 default_result_printer);
6825 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
6826 default_xml_printer);
6827 listeners.Append(extra_listener);
6829 EXPECT_TRUE(default_result_printer_is_destroyed);
6830 EXPECT_TRUE(default_xml_printer_is_destroyed);
6831 EXPECT_TRUE(extra_listener_is_destroyed);
6834 // Tests that a listener Append'ed to a TestEventListeners list starts
6835 // receiving events.
6836 TEST(TestEventListenersTest, Append) {
6837 int on_start_counter = 0;
6838 bool is_destroyed = false;
6839 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6841 TestEventListeners listeners;
6842 listeners.Append(listener);
6843 TestEventListenersAccessor::GetRepeater(&listeners)
6844 ->OnTestProgramStart(*UnitTest::GetInstance());
6845 EXPECT_EQ(1, on_start_counter);
6847 EXPECT_TRUE(is_destroyed);
6850 // Tests that listeners receive events in the order they were appended to
6851 // the list, except for *End requests, which must be received in the reverse
6853 class SequenceTestingListener : public EmptyTestEventListener {
6855 SequenceTestingListener(std::vector<std::string>* vector, const char* id)
6856 : vector_(vector), id_(id) {}
6859 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6860 vector_->push_back(GetEventDescription("OnTestProgramStart"));
6863 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {
6864 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
6867 void OnTestIterationStart(const UnitTest& /*unit_test*/,
6868 int /*iteration*/) override {
6869 vector_->push_back(GetEventDescription("OnTestIterationStart"));
6872 void OnTestIterationEnd(const UnitTest& /*unit_test*/,
6873 int /*iteration*/) override {
6874 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
6878 std::string GetEventDescription(const char* method) {
6880 message << id_ << "." << method;
6881 return message.GetString();
6884 std::vector<std::string>* vector_;
6885 const char* const id_;
6887 SequenceTestingListener(const SequenceTestingListener&) = delete;
6888 SequenceTestingListener& operator=(const SequenceTestingListener&) = delete;
6891 TEST(EventListenerTest, AppendKeepsOrder) {
6892 std::vector<std::string> vec;
6893 TestEventListeners listeners;
6894 listeners.Append(new SequenceTestingListener(&vec, "1st"));
6895 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
6896 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
6898 TestEventListenersAccessor::GetRepeater(&listeners)
6899 ->OnTestProgramStart(*UnitTest::GetInstance());
6900 ASSERT_EQ(3U, vec.size());
6901 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
6902 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
6903 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
6906 TestEventListenersAccessor::GetRepeater(&listeners)
6907 ->OnTestProgramEnd(*UnitTest::GetInstance());
6908 ASSERT_EQ(3U, vec.size());
6909 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
6910 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
6911 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
6914 TestEventListenersAccessor::GetRepeater(&listeners)
6915 ->OnTestIterationStart(*UnitTest::GetInstance(), 0);
6916 ASSERT_EQ(3U, vec.size());
6917 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
6918 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
6919 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
6922 TestEventListenersAccessor::GetRepeater(&listeners)
6923 ->OnTestIterationEnd(*UnitTest::GetInstance(), 0);
6924 ASSERT_EQ(3U, vec.size());
6925 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
6926 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
6927 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
6930 // Tests that a listener removed from a TestEventListeners list stops receiving
6931 // events and is not deleted when the list is destroyed.
6932 TEST(TestEventListenersTest, Release) {
6933 int on_start_counter = 0;
6934 bool is_destroyed = false;
6935 // Although Append passes the ownership of this object to the list,
6936 // the following calls release it, and we need to delete it before the
6938 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6940 TestEventListeners listeners;
6941 listeners.Append(listener);
6942 EXPECT_EQ(listener, listeners.Release(listener));
6943 TestEventListenersAccessor::GetRepeater(&listeners)
6944 ->OnTestProgramStart(*UnitTest::GetInstance());
6945 EXPECT_TRUE(listeners.Release(listener) == nullptr);
6947 EXPECT_EQ(0, on_start_counter);
6948 EXPECT_FALSE(is_destroyed);
6952 // Tests that no events are forwarded when event forwarding is disabled.
6953 TEST(EventListenerTest, SuppressEventForwarding) {
6954 int on_start_counter = 0;
6955 TestListener* listener = new TestListener(&on_start_counter, nullptr);
6957 TestEventListeners listeners;
6958 listeners.Append(listener);
6959 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6960 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
6961 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
6962 TestEventListenersAccessor::GetRepeater(&listeners)
6963 ->OnTestProgramStart(*UnitTest::GetInstance());
6964 EXPECT_EQ(0, on_start_counter);
6967 // Tests that events generated by Google Test are not forwarded in
6968 // death test subprocesses.
6969 TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
6970 EXPECT_DEATH_IF_SUPPORTED(
6972 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
6973 *GetUnitTestImpl()->listeners()))
6974 << "expected failure";
6976 "expected failure");
6979 // Tests that a listener installed via SetDefaultResultPrinter() starts
6980 // receiving events and is returned via default_result_printer() and that
6981 // the previous default_result_printer is removed from the list and deleted.
6982 TEST(EventListenerTest, default_result_printer) {
6983 int on_start_counter = 0;
6984 bool is_destroyed = false;
6985 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6987 TestEventListeners listeners;
6988 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
6990 EXPECT_EQ(listener, listeners.default_result_printer());
6992 TestEventListenersAccessor::GetRepeater(&listeners)
6993 ->OnTestProgramStart(*UnitTest::GetInstance());
6995 EXPECT_EQ(1, on_start_counter);
6997 // Replacing default_result_printer with something else should remove it
6998 // from the list and destroy it.
6999 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr);
7001 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7002 EXPECT_TRUE(is_destroyed);
7004 // After broadcasting an event the counter is still the same, indicating
7005 // the listener is not in the list anymore.
7006 TestEventListenersAccessor::GetRepeater(&listeners)
7007 ->OnTestProgramStart(*UnitTest::GetInstance());
7008 EXPECT_EQ(1, on_start_counter);
7011 // Tests that the default_result_printer listener stops receiving events
7012 // when removed via Release and that is not owned by the list anymore.
7013 TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
7014 int on_start_counter = 0;
7015 bool is_destroyed = false;
7016 // Although Append passes the ownership of this object to the list,
7017 // the following calls release it, and we need to delete it before the
7019 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7021 TestEventListeners listeners;
7022 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7024 EXPECT_EQ(listener, listeners.Release(listener));
7025 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7026 EXPECT_FALSE(is_destroyed);
7028 // Broadcasting events now should not affect default_result_printer.
7029 TestEventListenersAccessor::GetRepeater(&listeners)
7030 ->OnTestProgramStart(*UnitTest::GetInstance());
7031 EXPECT_EQ(0, on_start_counter);
7033 // Destroying the list should not affect the listener now, too.
7034 EXPECT_FALSE(is_destroyed);
7038 // Tests that a listener installed via SetDefaultXmlGenerator() starts
7039 // receiving events and is returned via default_xml_generator() and that
7040 // the previous default_xml_generator is removed from the list and deleted.
7041 TEST(EventListenerTest, default_xml_generator) {
7042 int on_start_counter = 0;
7043 bool is_destroyed = false;
7044 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7046 TestEventListeners listeners;
7047 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7049 EXPECT_EQ(listener, listeners.default_xml_generator());
7051 TestEventListenersAccessor::GetRepeater(&listeners)
7052 ->OnTestProgramStart(*UnitTest::GetInstance());
7054 EXPECT_EQ(1, on_start_counter);
7056 // Replacing default_xml_generator with something else should remove it
7057 // from the list and destroy it.
7058 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr);
7060 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7061 EXPECT_TRUE(is_destroyed);
7063 // After broadcasting an event the counter is still the same, indicating
7064 // the listener is not in the list anymore.
7065 TestEventListenersAccessor::GetRepeater(&listeners)
7066 ->OnTestProgramStart(*UnitTest::GetInstance());
7067 EXPECT_EQ(1, on_start_counter);
7070 // Tests that the default_xml_generator listener stops receiving events
7071 // when removed via Release and that is not owned by the list anymore.
7072 TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
7073 int on_start_counter = 0;
7074 bool is_destroyed = false;
7075 // Although Append passes the ownership of this object to the list,
7076 // the following calls release it, and we need to delete it before the
7078 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7080 TestEventListeners listeners;
7081 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7083 EXPECT_EQ(listener, listeners.Release(listener));
7084 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7085 EXPECT_FALSE(is_destroyed);
7087 // Broadcasting events now should not affect default_xml_generator.
7088 TestEventListenersAccessor::GetRepeater(&listeners)
7089 ->OnTestProgramStart(*UnitTest::GetInstance());
7090 EXPECT_EQ(0, on_start_counter);
7092 // Destroying the list should not affect the listener now, too.
7093 EXPECT_FALSE(is_destroyed);
7097 // Tests to ensure that the alternative, verbose spellings of
7098 // some of the macros work. We don't test them thoroughly as that
7099 // would be quite involved. Since their implementations are
7100 // straightforward, and they are rarely used, we'll just rely on the
7101 // users to tell us when they are broken.
7102 GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
7103 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
7105 // GTEST_FAIL is the same as FAIL.
7106 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
7107 "An expected failure");
7109 // GTEST_ASSERT_XY is the same as ASSERT_XY.
7111 GTEST_ASSERT_EQ(0, 0);
7112 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
7113 "An expected failure");
7114 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
7115 "An expected failure");
7117 GTEST_ASSERT_NE(0, 1);
7118 GTEST_ASSERT_NE(1, 0);
7119 EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
7120 "An expected failure");
7122 GTEST_ASSERT_LE(0, 0);
7123 GTEST_ASSERT_LE(0, 1);
7124 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
7125 "An expected failure");
7127 GTEST_ASSERT_LT(0, 1);
7128 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
7129 "An expected failure");
7130 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
7131 "An expected failure");
7133 GTEST_ASSERT_GE(0, 0);
7134 GTEST_ASSERT_GE(1, 0);
7135 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
7136 "An expected failure");
7138 GTEST_ASSERT_GT(1, 0);
7139 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
7140 "An expected failure");
7141 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
7142 "An expected failure");
7145 // Tests for internal utilities necessary for implementation of the universal
7148 class ConversionHelperBase {};
7149 class ConversionHelperDerived : public ConversionHelperBase {};
7151 struct HasDebugStringMethods {
7152 std::string DebugString() const { return ""; }
7153 std::string ShortDebugString() const { return ""; }
7156 struct InheritsDebugStringMethods : public HasDebugStringMethods {};
7158 struct WrongTypeDebugStringMethod {
7159 std::string DebugString() const { return ""; }
7160 int ShortDebugString() const { return 1; }
7163 struct NotConstDebugStringMethod {
7164 std::string DebugString() { return ""; }
7165 std::string ShortDebugString() const { return ""; }
7168 struct MissingDebugStringMethod {
7169 std::string DebugString() { return ""; }
7172 struct IncompleteType;
7174 // Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
7176 TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
7177 static_assert(HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
7180 HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
7182 static_assert(HasDebugStringAndShortDebugString<
7183 const InheritsDebugStringMethods>::value,
7186 !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
7189 !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
7192 !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
7194 static_assert(!HasDebugStringAndShortDebugString<IncompleteType>::value,
7196 static_assert(!HasDebugStringAndShortDebugString<int>::value, "const_false");
7199 // Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
7201 TEST(HasDebugStringAndShortDebugStringTest,
7202 ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
7204 HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
7207 // Tests that HasDebugStringAndShortDebugString<T>::value is false when T
7208 // doesn't have needed methods.
7209 TEST(HasDebugStringAndShortDebugStringTest,
7210 ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7211 EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);
7213 HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);
7216 // Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7218 template <typename T1, typename T2>
7219 void TestGTestRemoveReferenceAndConst() {
7220 static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value,
7221 "GTEST_REMOVE_REFERENCE_AND_CONST_ failed.");
7224 TEST(RemoveReferenceToConstTest, Works) {
7225 TestGTestRemoveReferenceAndConst<int, int>();
7226 TestGTestRemoveReferenceAndConst<double, double&>();
7227 TestGTestRemoveReferenceAndConst<char, const char>();
7228 TestGTestRemoveReferenceAndConst<char, const char&>();
7229 TestGTestRemoveReferenceAndConst<const char*, const char*>();
7232 // Tests GTEST_REFERENCE_TO_CONST_.
7234 template <typename T1, typename T2>
7235 void TestGTestReferenceToConst() {
7236 static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value,
7237 "GTEST_REFERENCE_TO_CONST_ failed.");
7240 TEST(GTestReferenceToConstTest, Works) {
7241 TestGTestReferenceToConst<const char&, char>();
7242 TestGTestReferenceToConst<const int&, const int>();
7243 TestGTestReferenceToConst<const double&, double>();
7244 TestGTestReferenceToConst<const std::string&, const std::string&>();
7247 // Tests IsContainerTest.
7249 class NonContainer {};
7251 TEST(IsContainerTestTest, WorksForNonContainer) {
7252 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7253 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7254 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7257 TEST(IsContainerTestTest, WorksForContainer) {
7258 EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::vector<bool>>(0)));
7259 EXPECT_EQ(sizeof(IsContainer),
7260 sizeof(IsContainerTest<std::map<int, double>>(0)));
7263 struct ConstOnlyContainerWithPointerIterator {
7264 using const_iterator = int*;
7265 const_iterator begin() const;
7266 const_iterator end() const;
7269 struct ConstOnlyContainerWithClassIterator {
7270 struct const_iterator {
7271 const int& operator*() const;
7272 const_iterator& operator++(/* pre-increment */);
7274 const_iterator begin() const;
7275 const_iterator end() const;
7278 TEST(IsContainerTestTest, ConstOnlyContainer) {
7279 EXPECT_EQ(sizeof(IsContainer),
7280 sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
7281 EXPECT_EQ(sizeof(IsContainer),
7282 sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
7285 // Tests IsHashTable.
7287 typedef void hasher;
7289 struct NotReallyAHashTable {
7290 typedef void hasher;
7291 typedef void reverse_iterator;
7293 TEST(IsHashTable, Basic) {
7294 EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value);
7295 EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value);
7296 EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value);
7297 EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value);
7302 TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7303 EXPECT_TRUE(ArrayEq(5, 5L));
7304 EXPECT_FALSE(ArrayEq('a', 0));
7307 TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7308 // Note that a and b are distinct but compatible types.
7309 const int a[] = {0, 1};
7311 EXPECT_TRUE(ArrayEq(a, b));
7312 EXPECT_TRUE(ArrayEq(a, 2, b));
7315 EXPECT_FALSE(ArrayEq(a, b));
7316 EXPECT_FALSE(ArrayEq(a, 1, b));
7319 TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7320 const char a[][3] = {"hi", "lo"};
7321 const char b[][3] = {"hi", "lo"};
7322 const char c[][3] = {"hi", "li"};
7324 EXPECT_TRUE(ArrayEq(a, b));
7325 EXPECT_TRUE(ArrayEq(a, 2, b));
7327 EXPECT_FALSE(ArrayEq(a, c));
7328 EXPECT_FALSE(ArrayEq(a, 2, c));
7331 // Tests ArrayAwareFind().
7333 TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7334 const char a[] = "hello";
7335 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7336 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7339 TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7340 int a[][2] = {{0, 1}, {2, 3}, {4, 5}};
7341 const int b[2] = {2, 3};
7342 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7344 const int c[2] = {6, 7};
7345 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7348 // Tests CopyArray().
7350 TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7356 TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7357 const char a[3] = "hi";
7359 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7361 EXPECT_TRUE(ArrayEq(a, b));
7366 EXPECT_TRUE(ArrayEq(a, c));
7369 TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7370 const int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
7372 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7374 EXPECT_TRUE(ArrayEq(a, b));
7379 EXPECT_TRUE(ArrayEq(a, c));
7382 // Tests NativeArray.
7384 TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7385 const int a[3] = {0, 1, 2};
7386 NativeArray<int> na(a, 3, RelationToSourceReference());
7387 EXPECT_EQ(3U, na.size());
7388 EXPECT_EQ(a, na.begin());
7391 TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7392 typedef int Array[2];
7393 Array* a = new Array[1];
7396 NativeArray<int> na(*a, 2, RelationToSourceCopy());
7397 EXPECT_NE(*a, na.begin());
7399 EXPECT_EQ(0, na.begin()[0]);
7400 EXPECT_EQ(1, na.begin()[1]);
7402 // We rely on the heap checker to verify that na deletes the copy of
7406 TEST(NativeArrayTest, TypeMembersAreCorrect) {
7407 StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7408 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7410 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7411 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7414 TEST(NativeArrayTest, MethodsWork) {
7415 const int a[3] = {0, 1, 2};
7416 NativeArray<int> na(a, 3, RelationToSourceCopy());
7417 ASSERT_EQ(3U, na.size());
7418 EXPECT_EQ(3, na.end() - na.begin());
7420 NativeArray<int>::const_iterator it = na.begin();
7427 EXPECT_EQ(na.end(), it);
7429 EXPECT_TRUE(na == na);
7431 NativeArray<int> na2(a, 3, RelationToSourceReference());
7432 EXPECT_TRUE(na == na2);
7434 const int b1[3] = {0, 1, 1};
7435 const int b2[4] = {0, 1, 2, 3};
7436 EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
7437 EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
7440 TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7441 const char a[2][3] = {"hi", "lo"};
7442 NativeArray<char[3]> na(a, 2, RelationToSourceReference());
7443 ASSERT_EQ(2U, na.size());
7444 EXPECT_EQ(a, na.begin());
7448 TEST(IndexSequence, MakeIndexSequence) {
7449 using testing::internal::IndexSequence;
7450 using testing::internal::MakeIndexSequence;
7452 (std::is_same<IndexSequence<>, MakeIndexSequence<0>::type>::value));
7454 (std::is_same<IndexSequence<0>, MakeIndexSequence<1>::type>::value));
7456 (std::is_same<IndexSequence<0, 1>, MakeIndexSequence<2>::type>::value));
7458 std::is_same<IndexSequence<0, 1, 2>, MakeIndexSequence<3>::type>::value));
7460 (std::is_base_of<IndexSequence<0, 1, 2>, MakeIndexSequence<3>>::value));
7464 TEST(ElemFromList, Basic) {
7465 using testing::internal::ElemFromList;
7467 (std::is_same<int, ElemFromList<0, int, double, char>::type>::value));
7469 (std::is_same<double, ElemFromList<1, int, double, char>::type>::value));
7471 (std::is_same<char, ElemFromList<2, int, double, char>::type>::value));
7473 std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int,
7474 char, int, int, int, int>::type>::value));
7478 TEST(FlatTuple, Basic) {
7479 using testing::internal::FlatTuple;
7481 FlatTuple<int, double, const char*> tuple = {};
7482 EXPECT_EQ(0, tuple.Get<0>());
7483 EXPECT_EQ(0.0, tuple.Get<1>());
7484 EXPECT_EQ(nullptr, tuple.Get<2>());
7486 tuple = FlatTuple<int, double, const char*>(
7487 testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo");
7488 EXPECT_EQ(7, tuple.Get<0>());
7489 EXPECT_EQ(3.2, tuple.Get<1>());
7490 EXPECT_EQ(std::string("Foo"), tuple.Get<2>());
7492 tuple.Get<1>() = 5.1;
7493 EXPECT_EQ(5.1, tuple.Get<1>());
7497 std::string AddIntToString(int i, const std::string& s) {
7498 return s + std::to_string(i);
7502 TEST(FlatTuple, Apply) {
7503 using testing::internal::FlatTuple;
7505 FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},
7509 EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
7510 return i == static_cast<int>(s.size());
7514 EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
7516 // Mutating operations.
7517 tuple.Apply([](int& i, std::string& s) {
7521 EXPECT_EQ(tuple.Get<0>(), 6);
7522 EXPECT_EQ(tuple.Get<1>(), "HelloHello");
7525 struct ConstructionCounting {
7526 ConstructionCounting() { ++default_ctor_calls; }
7527 ~ConstructionCounting() { ++dtor_calls; }
7528 ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }
7529 ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }
7530 ConstructionCounting& operator=(const ConstructionCounting&) {
7531 ++copy_assignment_calls;
7534 ConstructionCounting& operator=(ConstructionCounting&&) noexcept {
7535 ++move_assignment_calls;
7539 static void Reset() {
7540 default_ctor_calls = 0;
7542 copy_ctor_calls = 0;
7543 move_ctor_calls = 0;
7544 copy_assignment_calls = 0;
7545 move_assignment_calls = 0;
7548 static int default_ctor_calls;
7549 static int dtor_calls;
7550 static int copy_ctor_calls;
7551 static int move_ctor_calls;
7552 static int copy_assignment_calls;
7553 static int move_assignment_calls;
7556 int ConstructionCounting::default_ctor_calls = 0;
7557 int ConstructionCounting::dtor_calls = 0;
7558 int ConstructionCounting::copy_ctor_calls = 0;
7559 int ConstructionCounting::move_ctor_calls = 0;
7560 int ConstructionCounting::copy_assignment_calls = 0;
7561 int ConstructionCounting::move_assignment_calls = 0;
7563 TEST(FlatTuple, ConstructorCalls) {
7564 using testing::internal::FlatTuple;
7566 // Default construction.
7567 ConstructionCounting::Reset();
7568 { FlatTuple<ConstructionCounting> tuple; }
7569 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7570 EXPECT_EQ(ConstructionCounting::dtor_calls, 1);
7571 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7572 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7573 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7574 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7576 // Copy construction.
7577 ConstructionCounting::Reset();
7579 ConstructionCounting elem;
7580 FlatTuple<ConstructionCounting> tuple{
7581 testing::internal::FlatTupleConstructTag{}, elem};
7583 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7584 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7585 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);
7586 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7587 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7588 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7590 // Move construction.
7591 ConstructionCounting::Reset();
7593 FlatTuple<ConstructionCounting> tuple{
7594 testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}};
7596 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7597 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7598 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7599 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);
7600 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7601 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7604 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7606 ConstructionCounting::Reset();
7608 FlatTuple<ConstructionCounting> tuple;
7609 ConstructionCounting elem;
7610 tuple.Get<0>() = elem;
7612 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
7613 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7614 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7615 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7616 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);
7617 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7620 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7622 ConstructionCounting::Reset();
7624 FlatTuple<ConstructionCounting> tuple;
7625 tuple.Get<0>() = ConstructionCounting{};
7627 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
7628 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7629 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7630 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7631 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7632 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);
7634 ConstructionCounting::Reset();
7637 TEST(FlatTuple, ManyTypes) {
7638 using testing::internal::FlatTuple;
7640 // Instantiate FlatTuple with 257 ints.
7641 // Tests show that we can do it with thousands of elements, but very long
7642 // compile times makes it unusuitable for this test.
7643 #define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int,
7644 #define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8
7645 #define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16
7646 #define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32
7647 #define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64
7648 #define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128
7650 // Let's make sure that we can have a very long list of types without blowing
7651 // up the template instantiation depth.
7652 FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple;
7655 tuple.Get<99>() = 17;
7656 tuple.Get<256>() = 1000;
7657 EXPECT_EQ(7, tuple.Get<0>());
7658 EXPECT_EQ(17, tuple.Get<99>());
7659 EXPECT_EQ(1000, tuple.Get<256>());
7662 // Tests SkipPrefix().
7664 TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7665 const char* const str = "hello";
7667 const char* p = str;
7668 EXPECT_TRUE(SkipPrefix("", &p));
7672 EXPECT_TRUE(SkipPrefix("hell", &p));
7673 EXPECT_EQ(str + 4, p);
7676 TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7677 const char* const str = "world";
7679 const char* p = str;
7680 EXPECT_FALSE(SkipPrefix("W", &p));
7684 EXPECT_FALSE(SkipPrefix("world!", &p));
7688 // Tests ad_hoc_test_result().
7689 TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
7690 const testing::TestResult& test_result =
7691 testing::UnitTest::GetInstance()->ad_hoc_test_result();
7692 EXPECT_FALSE(test_result.Failed());
7695 class DynamicUnitTestFixture : public testing::Test {};
7697 class DynamicTest : public DynamicUnitTestFixture {
7698 void TestBody() override { EXPECT_TRUE(true); }
7701 auto* dynamic_test = testing::RegisterTest(
7702 "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__,
7703 __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });
7705 TEST(RegisterTest, WasRegistered) {
7706 auto* unittest = testing::UnitTest::GetInstance();
7707 for (int i = 0; i < unittest->total_test_suite_count(); ++i) {
7708 auto* tests = unittest->GetTestSuite(i);
7709 if (tests->name() != std::string("DynamicUnitTestFixture")) continue;
7710 for (int j = 0; j < tests->total_test_count(); ++j) {
7711 if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue;
7713 EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE");
7714 EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE");
7719 FAIL() << "Didn't find the test!";
7722 // Test that the pattern globbing algorithm is linear. If not, this test should
7724 TEST(PatternGlobbingTest, MatchesFilterLinearRuntime) {
7725 std::string name(100, 'a'); // Construct the string (a^100)b
7726 name.push_back('b');
7728 std::string pattern; // Construct the string ((a*)^100)b
7729 for (int i = 0; i < 100; ++i) {
7730 pattern.append("a*");
7732 pattern.push_back('b');
7735 testing::internal::UnitTestOptions::MatchesFilter(name, pattern.c_str()));
7738 TEST(PatternGlobbingTest, MatchesFilterWithMultiplePatterns) {
7739 const std::string name = "aaaa";
7740 EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*"));
7741 EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*:"));
7742 EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab"));
7743 EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:"));
7744 EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:a*"));
7747 TEST(PatternGlobbingTest, MatchesFilterEdgeCases) {
7748 EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("", "*a"));
7749 EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", "*"));
7750 EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("a", ""));
7751 EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", ""));