34#include "gtest/gtest.h"
39TEST(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);
66#include <unordered_set>
69#include "gtest/gtest-spi.h"
70#include "src/gtest-internal-inl.h"
75#if GTEST_CAN_STREAM_RESULTS_
77class StreamingListenerTest :
public Test {
79 class FakeSocketWriter :
public StreamingListener::AbstractSocketWriter {
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_;
102TEST_F(StreamingListenerTest, OnTestProgramEnd) {
104 streamer_.OnTestProgramEnd(unit_test_);
105 EXPECT_EQ(
"event=TestProgramEnd&passed=1\n", *output());
108TEST_F(StreamingListenerTest, OnTestIterationEnd) {
110 streamer_.OnTestIterationEnd(unit_test_, 42);
111 EXPECT_EQ(
"event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
114TEST_F(StreamingListenerTest, OnTestSuiteStart) {
116 streamer_.OnTestSuiteStart(
TestSuite(
"FooTest",
"Bar",
nullptr,
nullptr));
117 EXPECT_EQ(
"event=TestCaseStart&name=FooTest\n", *output());
120TEST_F(StreamingListenerTest, OnTestSuiteEnd) {
122 streamer_.OnTestSuiteEnd(
TestSuite(
"FooTest",
"Bar",
nullptr,
nullptr));
123 EXPECT_EQ(
"event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
126TEST_F(StreamingListenerTest, OnTestStart) {
128 streamer_.OnTestStart(test_info_obj_);
129 EXPECT_EQ(
"event=TestStart&name=Bar\n", *output());
132TEST_F(StreamingListenerTest, OnTestEnd) {
134 streamer_.OnTestEnd(test_info_obj_);
135 EXPECT_EQ(
"event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
138TEST_F(StreamingListenerTest, OnTestPartResult) {
140 streamer_.OnTestPartResult(TestPartResult(TestPartResult::kFatalFailure,
141 "foo.cc", 42,
"failed=\n&%"));
145 "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
156 return listeners->repeater();
161 listeners->SetDefaultResultPrinter(listener);
165 listeners->SetDefaultXmlGenerator(listener);
169 return listeners.EventForwardingEnabled();
173 listeners->SuppressEventForwarding();
182 void UnitTestRecordProperty(
const char* key,
const std::string& value) {
183 unit_test_.RecordProperty(key, value);
192using testing::AssertionFailure;
193using testing::AssertionResult;
194using testing::AssertionSuccess;
195using testing::DoubleLE;
198using testing::FloatLE;
199using testing::IsNotSubstring;
200using testing::IsSubstring;
201using testing::kMaxStackTraceDepth;
203using testing::ScopedFakeTestPartResultReporter;
204using testing::StaticAssertTypeEq;
208using testing::TestPartResult;
209using testing::TestPartResultArray;
213using testing::TimeInMillis;
215using testing::internal::AlwaysFalse;
216using testing::internal::AlwaysTrue;
217using testing::internal::AppendUserMessage;
218using testing::internal::ArrayAwareFind;
219using testing::internal::ArrayEq;
220using testing::internal::CodePointToUtf8;
221using testing::internal::CopyArray;
222using testing::internal::CountIf;
223using testing::internal::EqFailure;
225using testing::internal::ForEach;
226using testing::internal::FormatEpochTimeInMillisAsIso8601;
227using testing::internal::FormatTimeInMillisAsSeconds;
228using testing::internal::GetCurrentOsStackTraceExceptTop;
229using testing::internal::GetElementOr;
230using testing::internal::GetNextRandomSeed;
231using testing::internal::GetRandomSeedFromFlag;
232using testing::internal::GetTestTypeId;
233using testing::internal::GetTimeInMillis;
234using testing::internal::GetTypeId;
235using testing::internal::GetUnitTestImpl;
238using testing::internal::Int32FromEnvOrDie;
239using testing::internal::IsContainer;
240using testing::internal::IsContainerTest;
241using testing::internal::IsNotContainer;
242using testing::internal::kMaxRandomSeed;
243using testing::internal::kTestTypeIdInGoogleTest;
247using testing::internal::ParseFlag;
250using testing::internal::ShouldRunTestOnShard;
251using testing::internal::ShouldShard;
252using testing::internal::ShouldUseColor;
253using testing::internal::Shuffle;
254using testing::internal::ShuffleRange;
255using testing::internal::SkipPrefix;
256using testing::internal::StreamableToString;
261using testing::internal::WideStringToUtf8;
262using testing::internal::edit_distance::CalculateOptimalEdits;
263using testing::internal::edit_distance::CreateUnifiedDiff;
264using testing::internal::edit_distance::EditType;
266#if GTEST_HAS_STREAM_REDIRECTION
267using testing::internal::CaptureStdout;
268using testing::internal::GetCapturedStdout;
271#if GTEST_IS_THREADSAFE
272using testing::internal::ThreadWithParam;
277::std::ostream& operator<<(::std::ostream& os,
const TestingVector& vector) {
279 for (
size_t i = 0; i < vector.size(); i++) {
280 os << vector[i] <<
" ";
289TEST(GetRandomSeedFromFlagTest, HandlesZero) {
290 const int seed = GetRandomSeedFromFlag(0);
292 EXPECT_LE(seed,
static_cast<int>(kMaxRandomSeed));
295TEST(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));
303TEST(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));
313TEST(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));
326static void ClearCurrentTestPartResults() {
327 TestResultAccessor::ClearTestPartResults(
328 GetUnitTestImpl()->current_test_result());
333TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
334 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
335 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
338class SubClassOfTest :
public Test {};
339class AnotherSubClassOfTest :
public Test {};
341TEST(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>());
352TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
353 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
358using ::testing::internal::CanonicalizeForStdLibVersioning;
360TEST(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"));
369TEST(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::_"));
383TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
384 EXPECT_EQ(
"0", FormatTimeInMillisAsSeconds(0));
387TEST(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));
395TEST(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));
409class FormatEpochTimeInMillisAsIso8601Test :
public Test {
414 static const TimeInMillis kMillisPerSec = 1000;
417 void SetUp()
override {
420 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
421 if (getenv("TZ")) saved_tz_ = strdup(getenv("TZ"));
422 GTEST_DISABLE_MSC_DEPRECATED_POP_()
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) {
440#if _MSC_VER || GTEST_OS_WINDOWS_MINGW
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 )
448 GTEST_DISABLE_MSC_WARNINGS_POP_()
450#if GTEST_OS_LINUX_ANDROID && __ANDROID_API__ < 21
453 setenv(
"TZ",
"UTC", 1);
457 setenv((
"TZ"), time_zone, 1);
465 const char* saved_tz_;
468const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
470TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
471 EXPECT_EQ(
"2011-10-31T18:52:42.000",
472 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
475TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
476 EXPECT_EQ(
"2011-10-31T18:52:42.234",
477 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
480TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
481 EXPECT_EQ(
"2011-09-03T05:07:02.000",
482 FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
485TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
486 EXPECT_EQ(
"2011-09-28T17:08:22.000",
487 FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
490TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
491 EXPECT_EQ(
"1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
496#pragma option push -w-ccc -w-rch
501TEST(NullLiteralTest, LHSAllowsNullLiterals) {
502 EXPECT_EQ(0,
static_cast<void*
>(
nullptr));
503 ASSERT_EQ(0,
static_cast<void*
>(
nullptr));
504 EXPECT_EQ(NULL,
static_cast<void*
>(
nullptr));
505 ASSERT_EQ(NULL,
static_cast<void*
>(
nullptr));
506 EXPECT_EQ(
nullptr,
static_cast<void*
>(
nullptr));
507 ASSERT_EQ(
nullptr,
static_cast<void*
>(
nullptr));
509 const int*
const p =
nullptr;
514 EXPECT_EQ(
nullptr, p);
515 ASSERT_EQ(
nullptr, p);
519 template <
typename T>
525struct ConvertToPointer {
527 operator T*()
const {
532struct ConvertToAllButNoPointers {
533 template <
typename T,
534 typename std::enable_if<!std::is_pointer<T>::value,
int>::type = 0>
541inline bool operator==(
MyType const&,
MyType const&) {
return true; }
543TEST(NullLiteralTest, ImplicitConversion) {
544 EXPECT_EQ(ConvertToPointer{},
static_cast<void*
>(
nullptr));
545#if !defined(__GNUC__) || defined(__clang__)
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"
560TEST(NullLiteralTest, NoConversionNoWarning) {
568#pragma clang diagnostic pop
580TEST(CodePointToUtf8Test, CanEncodeNul) {
581 EXPECT_EQ(
"", CodePointToUtf8(L
'\0'));
585TEST(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'));
594TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
596 EXPECT_EQ(
"\xC3\x93", CodePointToUtf8(L
'\xD3'));
602 EXPECT_EQ(
"\xD5\xB6", CodePointToUtf8(
static_cast<wchar_t>(0x576)));
607TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
609 EXPECT_EQ(
"\xE0\xA3\x93", CodePointToUtf8(
static_cast<wchar_t>(0x8D3)));
612 EXPECT_EQ(
"\xEC\x9D\x8D", CodePointToUtf8(
static_cast<wchar_t>(0xC74D)));
615#if !GTEST_WIDE_STRING_USES_UTF16_
622TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
624 EXPECT_EQ(
"\xF0\x90\xA3\x93", CodePointToUtf8(L
'\x108D3'));
627 EXPECT_EQ(
"\xF0\x90\x90\x80", CodePointToUtf8(L
'\x10400'));
630 EXPECT_EQ(
"\xF4\x88\x98\xB4", CodePointToUtf8(L
'\x108634'));
634TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
635 EXPECT_EQ(
"(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L
'\x1234ABCD'));
643TEST(WideStringToUtf8Test, CanEncodeNul) {
644 EXPECT_STREQ(
"", WideStringToUtf8(L
"", 0).c_str());
645 EXPECT_STREQ(
"", WideStringToUtf8(L
"", -1).c_str());
649TEST(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());
658TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
660 EXPECT_STREQ(
"\xC3\x93", WideStringToUtf8(L
"\xD3", 1).c_str());
661 EXPECT_STREQ(
"\xC3\x93", WideStringToUtf8(L
"\xD3", -1).c_str());
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());
671TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
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());
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());
684TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
685 EXPECT_STREQ(
"ABC", WideStringToUtf8(L
"ABC\0XYZ", 100).c_str());
690TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
691 EXPECT_STREQ(
"ABC", WideStringToUtf8(L
"ABCDEF", 3).c_str());
694#if !GTEST_WIDE_STRING_USES_UTF16_
698TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
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());
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());
709TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
710 EXPECT_STREQ(
"(Invalid Unicode 0xABCDFF)",
711 WideStringToUtf8(L
"\xABCDFF", -1).c_str());
716TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
717 const wchar_t s[] = {0xD801, 0xDC00,
'\0'};
718 EXPECT_STREQ(
"\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
723TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
725 const wchar_t s1[] = {0xD800,
'\0'};
726 EXPECT_STREQ(
"\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
728 const wchar_t s2[] = {0xD800,
'M',
'\0'};
729 EXPECT_STREQ(
"\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
731 const wchar_t s3[] = {0xDC00,
'P',
'Q',
'R',
'\0'};
732 EXPECT_STREQ(
"\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
737#if !GTEST_WIDE_STRING_USES_UTF16_
738TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
739 const wchar_t s[] = {0x108634, 0xC74D,
'\n', 0x576, 0x8D3, 0x108634,
'\0'};
747 WideStringToUtf8(s, -1).c_str());
750TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
751 const wchar_t s[] = {0xC74D,
'\n', 0x576, 0x8D3,
'\0'};
757 WideStringToUtf8(s, -1).c_str());
763TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
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\\)");
773TEST(RandomTest, GeneratesNumbersWithinRange) {
774 constexpr uint32_t kRange = 10000;
776 for (
int i = 0; i < 10; i++) {
777 EXPECT_LT(random.Generate(kRange), kRange) <<
" for iteration " << i;
781 for (
int i = 0; i < 10; i++) {
782 EXPECT_LT(random2.Generate(kRange), kRange) <<
" for iteration " << i;
786TEST(RandomTest, RepeatsWhenReseeded) {
787 constexpr int kSeed = 123;
788 constexpr int kArraySize = 10;
789 constexpr uint32_t kRange = 10000;
790 uint32_t values[kArraySize];
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;
807static bool IsPositive(
int n) {
return n > 0; }
809TEST(ContainerUtilityTest, CountIf) {
811 EXPECT_EQ(0, CountIf(v, IsPositive));
815 EXPECT_EQ(0, CountIf(v, IsPositive));
820 EXPECT_EQ(2, CountIf(v, IsPositive));
826static void Accumulate(
int n) { g_sum += n; }
828TEST(ContainerUtilityTest, ForEach) {
831 ForEach(v, Accumulate);
836 ForEach(v, Accumulate);
842 ForEach(v, Accumulate);
843 EXPECT_EQ(321, g_sum);
847TEST(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'));
859TEST(ContainerUtilityDeathTest, ShuffleRange) {
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\\]");
880class 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);
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;
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);
928 return RangeIsShuffled(vector, 0,
static_cast<int>(vector.size()));
931 static bool VectorIsUnshuffled(
const TestingVector& vector) {
932 return !VectorIsShuffled(vector);
939const size_t VectorShuffleTest::kVectorSize;
941TEST_F(VectorShuffleTest, HandlesEmptyRange) {
943 ShuffleRange(&random_, 0, 0, &vector_);
944 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
945 ASSERT_PRED1(VectorIsUnshuffled, vector_);
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_);
958 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
959 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
960 ASSERT_PRED1(VectorIsUnshuffled, vector_);
963TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
965 ShuffleRange(&random_, 0, 1, &vector_);
966 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
967 ASSERT_PRED1(VectorIsUnshuffled, vector_);
970 ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2 + 1, &vector_);
971 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
972 ASSERT_PRED1(VectorIsUnshuffled, vector_);
975 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
976 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
977 ASSERT_PRED1(VectorIsUnshuffled, vector_);
983TEST_F(VectorShuffleTest, ShufflesEntireVector) {
984 Shuffle(&random_, &vector_);
985 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
986 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
990 EXPECT_NE(0, vector_[0]);
991 EXPECT_NE(
static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);
994TEST_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));
1005TEST_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));
1015TEST_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));
1026TEST_F(VectorShuffleTest, ShufflesRepeatably) {
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;
1047TEST(AssertHelperTest, AssertHelperIsSmall) {
1054TEST(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"));
1068static const wchar_t*
const kNull =
nullptr;
1071TEST(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"));
1085TEST(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
1092TEST(StringTest, AnsiAndUtf16Null) {
1093 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1094 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1097TEST(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));
1106TEST(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));
1119TEST(TestPropertyTest, StringValue) {
1121 EXPECT_STREQ(
"key", property.key());
1122 EXPECT_STREQ(
"1", property.value());
1126TEST(TestPropertyTest, ReplaceStringValue) {
1128 EXPECT_STREQ(
"1", property.value());
1129 property.SetValue(
"2");
1130 EXPECT_STREQ(
"2", property.value());
1136static void AddFatalFailure() { FAIL() <<
"Expected fatal failure."; }
1138static void AddNonfatalFailure() {
1139 ADD_FAILURE() <<
"Expected non-fatal failure.";
1142class ScopedFakeTestPartResultReporterTest :
public Test {
1144 enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
1145 static void AddFailure(FailureMode failure) {
1146 if (failure == FATAL_FAILURE) {
1149 AddNonfatalFailure();
1156TEST_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());
1171TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1172 TestPartResultArray results;
1175 ScopedFakeTestPartResultReporter reporter(&results);
1176 AddFailure(NONFATAL_FAILURE);
1178 EXPECT_EQ(1, results.size());
1181#if GTEST_IS_THREADSAFE
1183class ScopedFakeTestPartResultReporterWithThreadsTest
1184 :
public ScopedFakeTestPartResultReporterTest {
1186 static void AddFailureInOtherThread(FailureMode failure) {
1187 ThreadWithParam<FailureMode> thread(&AddFailure, failure,
nullptr);
1192TEST_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());
1217typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
1219TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1220 EXPECT_FATAL_FAILURE(AddFatalFailure(),
"Expected fatal failure.");
1223TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1224 EXPECT_FATAL_FAILURE(AddFatalFailure(),
1225 ::std::string(
"Expected fatal failure."));
1228TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1231 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
1232 "Expected fatal failure.");
1237#pragma option push -w-ccc
1243int NonVoidFunction() {
1244 EXPECT_FATAL_FAILURE(ASSERT_TRUE(
false),
"");
1245 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(),
"");
1249TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1256void DoesNotAbortHelper(
bool* aborted) {
1257 EXPECT_FATAL_FAILURE(ASSERT_TRUE(
false),
"");
1258 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(),
"");
1268TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1269 bool aborted =
true;
1270 DoesNotAbortHelper(&aborted);
1271 EXPECT_FALSE(aborted);
1278static int global_var = 0;
1279#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1281TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1284 EXPECT_FATAL_FAILURE(
1286 GTEST_USE_UNPROTECTED_COMMA_;
1292 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(
1294 GTEST_USE_UNPROTECTED_COMMA_;
1302typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1304TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1305 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
"Expected non-fatal failure.");
1308TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1309 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1310 ::std::string(
"Expected non-fatal failure."));
1313TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1316 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
1317 "Expected non-fatal failure.");
1323TEST_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
1341typedef ScopedFakeTestPartResultReporterWithThreadsTest
1342 ExpectFailureWithThreadsTest;
1344TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1345 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1346 "Expected fatal failure.");
1349TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1350 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1351 AddFailureInOtherThread(NONFATAL_FAILURE),
"Expected non-fatal failure.");
1358TEST(TestPropertyTest, ConstructorWorks) {
1360 EXPECT_STREQ(
"key", property.key());
1361 EXPECT_STREQ(
"value", property.value());
1364TEST(TestPropertyTest, SetValue) {
1366 EXPECT_STREQ(
"key", property.key());
1367 property.SetValue(
"value_2");
1368 EXPECT_STREQ(
"key", property.key());
1369 EXPECT_STREQ(
"value_2", property.value());
1375class TestResultTest :
public Test {
1377 typedef std::vector<TestPartResult> TPRVector;
1380 TestPartResult *pr1, *pr2;
1385 void SetUp()
override {
1387 pr1 =
new TestPartResult(TestPartResult::kSuccess,
"foo/bar.cc", 10,
1391 pr2 =
new TestPartResult(TestPartResult::kFatalFailure,
"foo/bar.cc",
1404 TPRVector* results1 =
1405 const_cast<TPRVector*
>(&TestResultAccessor::test_part_results(*r1));
1406 TPRVector* results2 =
1407 const_cast<TPRVector*
>(&TestResultAccessor::test_part_results(*r2));
1412 results1->push_back(*pr1);
1415 results2->push_back(*pr1);
1416 results2->push_back(*pr2);
1419 void TearDown()
override {
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());
1444TEST_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());
1451TEST_F(TestResultTest, Passed) {
1452 ASSERT_TRUE(r0->Passed());
1453 ASSERT_TRUE(r1->Passed());
1454 ASSERT_FALSE(r2->Passed());
1458TEST_F(TestResultTest, Failed) {
1459 ASSERT_FALSE(r0->Failed());
1460 ASSERT_FALSE(r1->Failed());
1461 ASSERT_TRUE(r2->Failed());
1466typedef TestResultTest TestResultDeathTest;
1468TEST_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),
"");
1476TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1478 ASSERT_EQ(0, test_result.test_property_count());
1482TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
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());
1493TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
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());
1510TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
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());
1532TEST(TestResultPropertyTest, GetTestProperty) {
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),
"");
1570class GTestFlagSaverTest :
public Test {
1575 static void SetUpTestSuite() {
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);
1600 static void TearDownTestSuite() {
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);
1658TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); }
1662TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); }
1667static void SetEnv(
const char* name,
const char* value) {
1668#if GTEST_OS_WINDOWS_MOBILE
1671#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1675 static std::map<std::string, std::string*> added_env;
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());
1689 putenv(
const_cast<char*
>(added_env[name]->c_str()));
1691#elif GTEST_OS_WINDOWS
1692 _putenv((
Message() << name <<
"=" << value).GetString().c_str());
1694 if (*value ==
'\0') {
1697 setenv(name, value, 1);
1702#if !GTEST_OS_WINDOWS_MOBILE
1705using testing::internal::Int32FromGTestEnv;
1711TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1712 SetEnv(GTEST_FLAG_PREFIX_UPPER_
"TEMP",
"");
1713 EXPECT_EQ(10, Int32FromGTestEnv(
"temp", 10));
1716#if !defined(GTEST_GET_INT32_FROM_ENV_)
1720TEST(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));
1732TEST(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));
1747TEST(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));
1760TEST(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);
1771TEST(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);
1785TEST(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);
1799TEST(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);
1811#if !GTEST_OS_WINDOWS_MOBILE
1812TEST(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));
1823TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1824 SetEnv(GTEST_FLAG_PREFIX_UPPER_
"VAR",
"xxx");
1825 EXPECT_DEATH_IF_SUPPORTED(
1826 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_
"VAR", 123),
".*");
1831TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1832 SetEnv(GTEST_FLAG_PREFIX_UPPER_
"VAR",
"1234567891234567891234");
1833 EXPECT_DEATH_IF_SUPPORTED(
1834 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_
"VAR", 123),
".*");
1839TEST(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));
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_;
1865TEST_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));
1874TEST_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));
1884#if !GTEST_OS_WINDOWS_MOBILE
1885TEST_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));
1905typedef ShouldShardTest ShouldShardDeathTest;
1907TEST_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),
".*");
1927TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1929 const int num_tests = 17;
1930 const int num_shards = 5;
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 "
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);
1970TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1971 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() !=
nullptr);
1972 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(),
"");
1975TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
1976 EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
1977 EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
1983void 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.";
1990void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
1992 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
1993 ASSERT_TRUE(test_info !=
nullptr);
1994 ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
1998void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2001 UnitTest::GetInstance()->current_test_suite();
2002 ASSERT_TRUE(test_suite !=
nullptr);
2003 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2004 test_suite->ad_hoc_test_result(), key);
2007void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2009 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2010 UnitTest::GetInstance()->ad_hoc_test_result(), key);
2016class UnitTestRecordPropertyTest
2019 static void SetUpTestSuite() {
2020 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2022 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2024 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2026 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2028 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2030 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2033 Test::RecordProperty(
"test_case_key_1",
"1");
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());
2049TEST_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());
2060TEST_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());
2076TEST_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());
2095TEST_F(UnitTestRecordPropertyTest,
2096 AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
2097 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"name");
2098 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2100 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2102 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"status");
2103 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"time");
2104 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2108TEST_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");
2116class UnitTestRecordPropertyTestEnvironment :
public Environment {
2118 void TearDown()
override {
2119 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2121 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2123 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2125 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2127 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2129 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2131 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2133 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2139static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ =
2140 AddGlobalTestEnvironment(
new UnitTestRecordPropertyTestEnvironment);
2151bool IsEven(
int n) {
return (n % 2) == 0; }
2154struct IsEvenFunctor {
2155 bool operator()(
int n) {
return IsEven(n); }
2160AssertionResult AssertIsEven(
const char* expr,
int n) {
2162 return AssertionSuccess();
2166 msg << expr <<
" evaluates to " << n <<
", which is not even.";
2167 return AssertionFailure(msg);
2172AssertionResult ResultIsEven(
int n) {
2174 return AssertionSuccess() << n <<
" is even";
2176 return AssertionFailure() << n <<
" is odd";
2182AssertionResult ResultIsEvenNoExplanation(
int n) {
2184 return AssertionSuccess();
2186 return AssertionFailure() << n <<
" is odd";
2191struct AssertIsEvenFunctor {
2192 AssertionResult operator()(
const char* expr,
int n) {
2193 return AssertIsEven(expr, n);
2198bool SumIsEven2(
int n1,
int n2) {
return IsEven(n1 + n2); }
2202struct SumIsEven3Functor {
2203 bool operator()(
int n1,
int n2,
int n3) {
return IsEven(n1 + n2 + n3); }
2208AssertionResult 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);
2225struct 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);
2245TEST(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");
2260TEST(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.");
2279TEST(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.";
2298TEST(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");
2319TEST(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.");
2345TEST(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.";
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.";
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.";
2392TEST(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 }");
2405bool IsPositive(
double x) {
return x > 0; }
2407template <
typename T>
2408bool IsNegative(T x) {
2412template <
typename T1,
typename T2>
2413bool GreaterThan(T1 x1, T2 x2) {
2419TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2421 EXPECT_PRED1((
bool (*)(
int))(IsPositive), 5);
2422 ASSERT_PRED1((
bool (*)(
double))(IsPositive), 6.0);
2427TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2428 EXPECT_PRED1(IsNegative<int>, -5);
2431 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2437AssertionResult IsPositiveFormat(
const char* ,
int n) {
2438 return n > 0 ? AssertionSuccess() : AssertionFailure(
Message() <<
"Failure");
2441AssertionResult IsPositiveFormat(
const char* ,
double x) {
2442 return x > 0 ? AssertionSuccess() : AssertionFailure(
Message() <<
"Failure");
2445template <
typename T>
2446AssertionResult IsNegativeFormat(
const char* , T x) {
2447 return x < 0 ? AssertionSuccess() : AssertionFailure(
Message() <<
"Failure");
2450template <
typename T1,
typename T2>
2451AssertionResult EqualsFormat(
const char* ,
const char* ,
2452 const T1& x1,
const T2& x2) {
2453 return x1 == x2 ? AssertionSuccess()
2454 : AssertionFailure(
Message() <<
"Failure");
2459TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2460 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2461 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2466TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2467 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2468 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2474TEST(StringAssertionTest, ASSERT_STREQ) {
2475 const char*
const p1 =
"good";
2476 ASSERT_STREQ(p1, p1);
2479 const char p2[] =
"good";
2480 ASSERT_STREQ(p1, p2);
2482 EXPECT_FATAL_FAILURE(ASSERT_STREQ(
"bad",
"good"),
" \"bad\"\n \"good\"");
2486TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2487 ASSERT_STREQ(
static_cast<const char*
>(
nullptr),
nullptr);
2488 EXPECT_FATAL_FAILURE(ASSERT_STREQ(
nullptr,
"non-null"),
"non-null");
2492TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2493 EXPECT_FATAL_FAILURE(ASSERT_STREQ(
"non-null",
nullptr),
"non-null");
2497TEST(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\"");
2509TEST(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");
2518TEST(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)");
2530TEST(StringAssertionTest, STREQ_Wide) {
2532 ASSERT_STREQ(
static_cast<const wchar_t*
>(
nullptr),
nullptr);
2535 ASSERT_STREQ(L
"", L
"");
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");
2547 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L
"abc\x8119", L
"abc\x8120"),
"abc");
2550 EXPECT_NONFATAL_FAILURE(
2552 EXPECT_STREQ(L
"abc\x8119", L
"abc\x8121") <<
"Expected failure";
2554 "Expected failure");
2558TEST(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\"\"");
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");
2579 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L
"abc\x8119", L
"abc\x8119"),
"abc");
2582 ASSERT_STRNE(L
"abc\x8119", L
"abc\x8120") <<
"This shouldn't happen";
2589TEST(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"));
2600TEST(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"));
2612TEST(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());
2624TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2625 EXPECT_TRUE(IsSubstring(
"",
"", std::string(
"hello"),
"ahellob"));
2626 EXPECT_FALSE(IsSubstring(
"",
"",
"hello", std::string(
"world")));
2629#if GTEST_HAS_STD_WSTRING
2632TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2633 EXPECT_TRUE(IsSubstring(
"",
"", ::std::wstring(L
"needle"), L
"two needles"));
2634 EXPECT_FALSE(IsSubstring(
"",
"", L
"needle", ::std::wstring(L
"haystack")));
2639TEST(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());
2656TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2657 EXPECT_TRUE(IsNotSubstring(
"",
"",
"needle",
"haystack"));
2658 EXPECT_FALSE(IsNotSubstring(
"",
"",
"needle",
"two needles"));
2663TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2664 EXPECT_TRUE(IsNotSubstring(
"",
"", L
"needle", L
"haystack"));
2665 EXPECT_FALSE(IsNotSubstring(
"",
"", L
"needle", L
"two needles"));
2670TEST(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());
2682TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2683 EXPECT_FALSE(IsNotSubstring(
"",
"", std::string(
"hello"),
"ahellob"));
2684 EXPECT_TRUE(IsNotSubstring(
"",
"",
"hello", std::string(
"world")));
2689TEST(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
2704TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2706 IsNotSubstring(
"",
"", ::std::wstring(L
"needle"), L
"two needles"));
2707 EXPECT_TRUE(IsNotSubstring(
"",
"", L
"needle", ::std::wstring(L
"haystack")));
2714template <
typename RawType>
2715class FloatingPointTest :
public Test {
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;
2735 typedef typename Floating::Bits Bits;
2737 void SetUp()
override {
2738 const uint32_t max_ulps = Floating::kMaxUlps;
2741 const Bits zero_bits = Floating(0).bits();
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);
2752 const Bits one_bits = Floating(1).bits();
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();
2763 const Bits infinity_bits = Floating(values_.infinity).bits();
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);
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_;
2787template <
typename RawType>
2788typename FloatingPointTest<RawType>::TestValues
2789 FloatingPointTest<RawType>::values_;
2792typedef FloatingPointTest<float> FloatTest;
2795TEST_F(FloatTest, Size) { TestSize(); }
2798TEST_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");
2809TEST_F(FloatTest, AlmostZeros) {
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");
2830TEST_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");
2837TEST_F(FloatTest, LargeDiff) {
2838 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
"3.0");
2845TEST_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");
2853 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2858TEST_F(FloatTest, NaN) {
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");
2875TEST_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);
2882TEST_F(FloatTest, Commutative) {
2884 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2887 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2892TEST_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),
2896 "The difference between 1.0f and 1.5f is 0.5, "
2897 "which exceeds 0.25f");
2901TEST_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),
2905 "The difference between 1.0f and 1.5f is 0.5, "
2906 "which exceeds 0.25f");
2910TEST_F(FloatTest, FloatLESucceeds) {
2911 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f);
2912 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f);
2915 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2919TEST_F(FloatTest, FloatLEFails) {
2921 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2922 "(2.0f) <= (1.0f)");
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)");
2949typedef FloatingPointTest<double> DoubleTest;
2952TEST_F(DoubleTest, Size) { TestSize(); }
2955TEST_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");
2966TEST_F(DoubleTest, AlmostZeros) {
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");
2988TEST_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");
2995TEST_F(DoubleTest, LargeDiff) {
2996 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
"3.0");
3003TEST_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");
3011 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
3016TEST_F(DoubleTest, NaN) {
3017 static const DoubleTest::TestValues& v = this->values_;
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");
3027TEST_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);
3034TEST_F(DoubleTest, Commutative) {
3036 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
3039 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3044TEST_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),
3048 "The difference between 1.0 and 1.5 is 0.5, "
3049 "which exceeds 0.25");
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 "
3060TEST_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),
3064 "The difference between 1.0 and 1.5 is 0.5, "
3065 "which exceeds 0.25");
3069TEST_F(DoubleTest, DoubleLESucceeds) {
3070 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0);
3071 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0);
3074 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3078TEST_F(DoubleTest, DoubleLEFails) {
3080 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
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)");
3113 FAIL() <<
"Unexpected failure: Disabled test should not be run.";
3118TEST(
DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); }
3122TEST(DISABLED_TestSuite, TestShouldNotRun) {
3123 FAIL() <<
"Unexpected failure: Test in disabled test case should not be run.";
3128TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {
3129 FAIL() <<
"Unexpected failure: Test in disabled test case should not be run.";
3134class 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.";
3147TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3148 FAIL() <<
"Unexpected failure: Disabled test should not be run.";
3151TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3152 FAIL() <<
"Unexpected failure: Disabled test should not be run.";
3157template <
typename T>
3161TYPED_TEST_SUITE(
TypedTest, NumericTypes);
3163TYPED_TEST(
TypedTest, DISABLED_ShouldNotRun) {
3164 FAIL() <<
"Unexpected failure: Disabled typed test should not run.";
3167template <
typename T>
3168class DISABLED_TypedTest :
public Test {};
3170TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
3172TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3173 FAIL() <<
"Unexpected failure: Disabled typed test should not run.";
3178template <
typename T>
3183TYPED_TEST_P(
TypedTestP, DISABLED_ShouldNotRun) {
3184 FAIL() <<
"Unexpected failure: "
3185 <<
"Disabled type-parameterized test should not run.";
3188REGISTER_TYPED_TEST_SUITE_P(
TypedTestP, DISABLED_ShouldNotRun);
3190INSTANTIATE_TYPED_TEST_SUITE_P(My,
TypedTestP, NumericTypes);
3192template <
typename T>
3193class DISABLED_TypedTestP :
public Test {};
3195TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
3197TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3198 FAIL() <<
"Unexpected failure: "
3199 <<
"Disabled type-parameterized test should not run.";
3202REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
3204INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
3208class SingleEvaluationTest :
public Test {
3213 static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); }
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_;
3236const char*
const SingleEvaluationTest::s1_ =
"01234";
3237const char*
const SingleEvaluationTest::s2_ =
"abcde";
3238const char* SingleEvaluationTest::p1_;
3239const char* SingleEvaluationTest::p2_;
3240int SingleEvaluationTest::a_;
3241int SingleEvaluationTest::b_;
3245TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3246 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3248 EXPECT_EQ(s1_ + 1, p1_);
3249 EXPECT_EQ(s2_ + 1, p2_);
3253TEST_F(SingleEvaluationTest, ASSERT_STR) {
3255 EXPECT_STRNE(p1_++, p2_++);
3256 EXPECT_EQ(s1_ + 1, p1_);
3257 EXPECT_EQ(s2_ + 1, p2_);
3260 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
"Ignoring case");
3261 EXPECT_EQ(s1_ + 2, p1_);
3262 EXPECT_EQ(s2_ + 2, p2_);
3267TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3268 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3269 "(a_++) != (b_++)");
3275TEST_F(SingleEvaluationTest, OtherCases) {
3277 EXPECT_TRUE(0 == a_++);
3281 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++),
"-1 == a_++");
3285 EXPECT_GT(a_++, b_++);
3290 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++),
"(a_++) < (b_++)");
3295 ASSERT_TRUE(0 < a_++);
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"
3316#define ERROR_DESC "an std::exception-derived error"
3320void ThrowAnInteger() {
throw 1; }
3321void ThrowRuntimeError(
const char* what) {
throw std::runtime_error(what); }
3324TEST_F(SingleEvaluationTest, ExceptionTests) {
3335 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(
3341 "throws a different type");
3345 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(
3348 ThrowRuntimeError(
"A description");
3351 "throws " ERROR_DESC
3352 " with description \"A description\"");
3356 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++,
bool),
"throws nothing");
3360 EXPECT_NO_THROW(a_++);
3364 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({
3379 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++),
"it doesn't");
3386class 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";
3403TEST_F(NoFatalFailureTest, NoFailure) {
3404 EXPECT_NO_FATAL_FAILURE(Succeeds());
3405 ASSERT_NO_FATAL_FAILURE(Succeeds());
3408TEST_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");
3415TEST_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());
3432TEST_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());
3453TEST_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::kFatalFailure,
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());
3472std::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]]);
3481std::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]));
3489std::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));
3497TEST(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))
3547TEST(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"
3598TEST(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",
3618TEST(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());
3630#pragma option push -w-ccc -w-rch
3634TEST(AssertionTest, ASSERT_TRUE) {
3636 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
"2 < 1");
3640TEST(AssertionTest, AssertTrueWithAssertionResult) {
3641 ASSERT_TRUE(ResultIsEven(2));
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"
3657TEST(AssertionTest, ASSERT_FALSE) {
3658 ASSERT_FALSE(2 < 1);
3659 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3666TEST(AssertionTest, AssertFalseWithAssertionResult) {
3667 ASSERT_FALSE(ResultIsEven(3));
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"
3690TEST(ExpectTest, ASSERT_EQ_Double) {
3692 ASSERT_EQ(5.6, 5.6);
3695 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
"5.1");
3699TEST(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"
3711TEST(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:");
3725TEST(ExpectTest, ASSERT_EQ_0) {
3732 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
" 0\n 5.6");
3736TEST(AssertionTest, ASSERT_NE) {
3738 EXPECT_FATAL_FAILURE(ASSERT_NE(
'a',
'a'),
3739 "Expected: ('a') != ('a'), "
3740 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3744TEST(AssertionTest, ASSERT_LE) {
3747 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
"Expected: (2) <= (0), actual: 2 vs 0");
3751TEST(AssertionTest, ASSERT_LT) {
3753 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
"Expected: (2) < (2), actual: 2 vs 2");
3757TEST(AssertionTest, ASSERT_GE) {
3760 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
"Expected: (2) >= (3), actual: 2 vs 3");
3764TEST(AssertionTest, ASSERT_GT) {
3766 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
"Expected: (2) > (2), actual: 2 vs 2");
3769#if GTEST_HAS_EXCEPTIONS
3771void ThrowNothing() {}
3774TEST(AssertionTest, ASSERT_THROW) {
3775 ASSERT_THROW(ThrowAnInteger(),
int);
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.");
3800TEST(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\".");
3814TEST(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.");
3825TEST(AssertionTest, AssertPrecedence) {
3826 ASSERT_EQ(1 < 2,
true);
3827 bool false_value =
false;
3828 ASSERT_EQ(
true && false_value,
false);
3832void TestEq1(
int x) { ASSERT_EQ(1, x); }
3835TEST(AssertionTest, NonFixtureSubroutine) {
3836 EXPECT_FATAL_FAILURE(TestEq1(2),
" x\n Which is: 2");
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();
3852 Uncopyable(
const Uncopyable&);
3857::std::ostream& operator<<(::std::ostream& os,
const Uncopyable& value) {
3858 return os << value.value();
3861bool IsPositiveUncopyable(
const Uncopyable& x) {
return x.value() > 0; }
3864void TestAssertNonPositive() {
3866 ASSERT_PRED1(IsPositiveUncopyable, y);
3869void TestAssertEqualsUncopyable() {
3876TEST(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");
3889TEST(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");
3902enum NamedEnum { kE1 = 0, kE2 = 1 };
3904TEST(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");
3912#if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3929 kCaseB = testing::internal::kMaxBiggestInt,
3940TEST(AssertionTest, AnonymousEnum) {
3943 EXPECT_EQ(
static_cast<int>(kCaseA),
static_cast<int>(kCaseB));
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);
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");
3977static HRESULT UnexpectedHRESULTFailure() {
return E_UNEXPECTED; }
3979static HRESULT OkHRESULTSuccess() {
return S_OK; }
3981static HRESULT FalseHRESULTSuccess() {
return S_FALSE; }
3987TEST(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");
3996TEST(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");
4005TEST(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"
4016TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4017 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
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"
4033TEST(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");
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");
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"
4068TEST(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
4092TEST(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++),
"");
4104TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
4105 EXPECT_THROW(
throw std::exception(), std::exception);
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"
4115TEST(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
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"
4150TEST(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
4177TEST(AssertionSyntaxTest, WorksWithSwitch) {
4187 EXPECT_FALSE(
false) <<
"EXPECT_FALSE failed in switch case";
4194 ASSERT_EQ(1, 1) <<
"ASSERT_EQ failed in default switch handler";
4202#if GTEST_HAS_EXCEPTIONS
4204void ThrowAString() {
throw "std::string"; }
4208TEST(AssertionSyntaxTest, WorksWithConst) {
4209 ASSERT_THROW(ThrowAString(),
const char*);
4211 EXPECT_THROW(ThrowAString(),
const char*);
4221TEST(SuccessfulAssertionTest, SUCCEED) {
4224 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4228TEST(SuccessfulAssertionTest, EXPECT) {
4230 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4234TEST(SuccessfulAssertionTest, EXPECT_STR) {
4235 EXPECT_STREQ(
"",
"");
4236 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4240TEST(SuccessfulAssertionTest, ASSERT) {
4242 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4246TEST(SuccessfulAssertionTest, ASSERT_STR) {
4247 ASSERT_STREQ(
"",
"");
4248 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4257TEST(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.";
4281TEST(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.");
4291TEST(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.");
4299TEST(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.",
4307TEST(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");
4318TEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0,
"0"); }
4321TEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() <<
"Success == " << 1; }
4324TEST(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);
4337TEST(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.");
4352TEST(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.");
4359 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4363 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
"2 > 3");
4367TEST(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"
4381TEST(ExpectTest, EXPECT_FALSE) {
4382 EXPECT_FALSE(2 < 1);
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");
4396TEST(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"
4415TEST(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");
4430TEST(ExpectTest, EXPECT_EQ_Double) {
4432 EXPECT_EQ(5.6, 5.6);
4435 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
"5.1");
4439TEST(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:");
4453TEST(ExpectTest, EXPECT_EQ_0) {
4460 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
" 0\n 5.6");
4464TEST(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");
4477 void* pv1 = (
void*)0x1234;
4478 char*
const p1 =
reinterpret_cast<char*
>(pv1);
4479 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
"p1");
4483TEST(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)");
4492TEST(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)");
4500TEST(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)");
4509TEST(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
4519TEST(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.");
4538TEST(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\".");
4552TEST(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.");
4562TEST(ExpectTest, ExpectPrecedence) {
4563 EXPECT_EQ(1 < 2,
true);
4564 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(
true,
true &&
false),
4565 " true && false\n Which is: false");
4571TEST(StreamableToStringTest, Scalar) {
4572 EXPECT_STREQ(
"5", StreamableToString(5).c_str());
4576TEST(StreamableToStringTest, Pointer) {
4579 EXPECT_STRNE(
"(null)", StreamableToString(p).c_str());
4583TEST(StreamableToStringTest, NullPointer) {
4585 EXPECT_STREQ(
"(null)", StreamableToString(p).c_str());
4589TEST(StreamableToStringTest, CString) {
4590 EXPECT_STREQ(
"Foo", StreamableToString(
"Foo").c_str());
4594TEST(StreamableToStringTest, NullCString) {
4596 EXPECT_STREQ(
"(null)", StreamableToString(p).c_str());
4602TEST(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());
4610TEST(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);
4616 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4617 "Here's a NUL\\0 and some more string");
4621TEST(StreamableTest, NULChar) {
4622 EXPECT_FATAL_FAILURE(
4624 FAIL() <<
"A NUL" <<
'\0' <<
" and some more string";
4626 "A NUL\\0 and some more string");
4630TEST(StreamableTest,
int) { EXPECT_FATAL_FAILURE(FAIL() << 900913,
"900913"); }
4637TEST(StreamableTest, NullCharPtr) {
4638 EXPECT_FATAL_FAILURE(FAIL() <<
static_cast<const char*
>(
nullptr),
"(null)");
4643TEST(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.");
4654void AddFailureHelper(
bool* aborted) {
4656 ADD_FAILURE() <<
"Intentional failure.";
4661TEST(MacroTest, ADD_FAILURE) {
4662 bool aborted =
true;
4663 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
"Intentional failure.");
4664 EXPECT_FALSE(aborted);
4668TEST(MacroTest, ADD_FAILURE_AT) {
4671 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT(
"foo.cc", 42) <<
"Wrong!",
"Wrong!");
4674 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT(
"foo.cc", 42),
"Failed");
4683TEST(MacroTest, FAIL) {
4684 EXPECT_FATAL_FAILURE(FAIL(),
"Failed");
4685 EXPECT_FATAL_FAILURE(FAIL() <<
"Intentional failure.",
4686 "Intentional failure.");
4690TEST(MacroTest, GTEST_FAIL_AT) {
4693 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT(
"foo.cc", 42) <<
"Wrong!",
"Wrong!");
4696 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT(
"foo.cc", 42),
"Failed");
4703TEST(MacroTest, SUCCEED) {
4705 SUCCEED() <<
"Explicit success.";
4716TEST(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");
4727TEST(EqAssertionTest, Int) {
4729 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
" 32\n 33");
4733TEST(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");
4740TEST(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'");
4748TEST(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'");
4767TEST(EqAssertionTest, StdString) {
4770 ASSERT_EQ(
"Test", ::std::string(
"Test"));
4773 static const ::std::string str1(
"A * in the middle");
4774 static const ::std::string str2(str1);
4775 EXPECT_EQ(str1, str2);
4779 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(
"Test", ::std::string(
"test")),
"\"test\"");
4782 char*
const p1 =
const_cast<char*
>(
"foo");
4783 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string(
"bar"), p1),
"p1");
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
4796TEST(EqAssertionTest, StdWideString) {
4798 const ::std::wstring wstr1(L
"A * in the middle");
4799 const ::std::wstring wstr2(wstr1);
4800 ASSERT_EQ(wstr1, wstr2);
4804 const wchar_t kTestX8119[] = {
'T',
'e',
's',
't', 0x8119,
'\0'};
4805 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4809 const wchar_t kTestX8120[] = {
'T',
'e',
's',
't', 0x8120,
'\0'};
4810 EXPECT_NONFATAL_FAILURE(
4812 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4818 ::std::wstring wstr3(wstr1);
4819 wstr3.at(2) = L
'\0';
4820 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
"wstr3");
4824 EXPECT_FATAL_FAILURE(
4826 ASSERT_EQ(
const_cast<wchar_t*
>(L
"foo"), ::std::wstring(L
"bar"));
4834TEST(EqAssertionTest, CharPointer) {
4835 char*
const p0 =
nullptr;
4840 void* pv1 = (
void*)0x1234;
4841 void* pv2 = (
void*)0xABC0;
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)),
4854TEST(EqAssertionTest, WideCharPointer) {
4855 wchar_t*
const p0 =
nullptr;
4860 void* pv1 = (
void*)0x1234;
4861 void* pv2 = (
void*)0xABC0;
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;
4869 void* pv4 = (
void*)0xABC0;
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");
4876TEST(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)),
4884class 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_;
4909TEST(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>");
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>");
4950 int Bar()
const {
return 1; }
4954 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4955 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4960TEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); }
4963class FRIEND_TEST_Test2 :
public Test {
4970TEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); }
4978class TestLifeCycleTest :
public Test {
4982 TestLifeCycleTest() { count_++; }
4986 ~TestLifeCycleTest()
override { count_--; }
4989 int count()
const {
return count_; }
4995int TestLifeCycleTest::count_ = 0;
4998TEST_F(TestLifeCycleTest, Test1) {
5001 ASSERT_EQ(1, count());
5005TEST_F(TestLifeCycleTest, Test2) {
5009 ASSERT_EQ(1, count());
5016TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5019 AssertionResult r1 = AssertionSuccess();
5020 AssertionResult r2 = r1;
5025 AssertionResult r3 = r1;
5026 EXPECT_EQ(
static_cast<bool>(r3),
static_cast<bool>(r1));
5027 EXPECT_STREQ(
"abc", r1.message());
5032TEST(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());
5055TEST(AssertionResultTest, NegationWorks) {
5056 AssertionResult r1 = AssertionSuccess() <<
"abc";
5058 EXPECT_STREQ(
"abc", (!r1).message());
5060 AssertionResult r2 = AssertionFailure() <<
"def";
5062 EXPECT_STREQ(
"def", (!r2).message());
5065TEST(AssertionResultTest, StreamingWorks) {
5066 AssertionResult r = AssertionSuccess();
5067 r <<
"abc" <<
'd' << 0 <<
true;
5068 EXPECT_STREQ(
"abcd0true", r.message());
5071TEST(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());
5079TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5080 struct ExplicitlyConvertibleToBool {
5081 explicit operator bool()
const {
return value; }
5084 ExplicitlyConvertibleToBool v1 = {
false};
5085 ExplicitlyConvertibleToBool v2 = {
true};
5091 operator AssertionResult()
const {
return AssertionResult(
true); }
5094TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5103 explicit Base(
int an_x) : x_(an_x) {}
5104 int x()
const {
return x_; }
5109std::ostream& operator<<(std::ostream& os,
const Base& val) {
5110 return os << val.x();
5112std::ostream& operator<<(std::ostream& os,
const Base* pointer) {
5113 return os <<
"(" << pointer->x() <<
")";
5116TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5121 EXPECT_STREQ(
"1(1)", msg.GetString().c_str());
5127class MyTypeInUnnamedNameSpace :
public Base {
5129 explicit MyTypeInUnnamedNameSpace(
int an_x) :
Base(an_x) {}
5131std::ostream& operator<<(std::ostream& os,
5132 const MyTypeInUnnamedNameSpace& val) {
5133 return os << val.x();
5135std::ostream& operator<<(std::ostream& os,
5136 const MyTypeInUnnamedNameSpace* pointer) {
5137 return os <<
"(" << pointer->x() <<
")";
5141TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5143 MyTypeInUnnamedNameSpace a(1);
5146 EXPECT_STREQ(
"1(1)", msg.GetString().c_str());
5151namespace namespace1 {
5157 return os << val.x();
5159std::ostream& operator<<(std::ostream& os,
const MyTypeInNameSpace1* pointer) {
5160 return os <<
"(" << pointer->x() <<
")";
5164TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5169 EXPECT_STREQ(
"1(1)", msg.GetString().c_str());
5174namespace namespace2 {
5180std::ostream& operator<<(std::ostream& os,
5182 return os << val.x();
5184std::ostream& operator<<(std::ostream& os,
5186 return os <<
"(" << pointer->x() <<
")";
5189TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5194 EXPECT_STREQ(
"1(1)", msg.GetString().c_str());
5198TEST(MessageTest, NullPointers) {
5200 char*
const p1 =
nullptr;
5201 unsigned char*
const p2 =
nullptr;
5203 double* p4 =
nullptr;
5207 msg << p1 << p2 << p3 << p4 << p5 << p6;
5208 ASSERT_STREQ(
"(null)(null)(null)(null)(null)(null)", msg.GetString().c_str());
5212TEST(MessageTest, WideStrings) {
5214 const wchar_t* const_wstr =
nullptr;
5215 EXPECT_STREQ(
"(null)", (
Message() << const_wstr).GetString().c_str());
5218 wchar_t* wstr =
nullptr;
5219 EXPECT_STREQ(
"(null)", (
Message() << wstr).GetString().c_str());
5222 const_wstr = L
"abc\x8119";
5223 EXPECT_STREQ(
"abc\xe8\x84\x99",
5224 (
Message() << const_wstr).GetString().c_str());
5227 wstr =
const_cast<wchar_t*
>(const_wstr);
5228 EXPECT_STREQ(
"abc\xe8\x84\x99", (
Message() << wstr).GetString().c_str());
5238 static const TestInfo* GetTestInfo(
const char* test_name) {
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;
5250 return test_info->result();
5256 const TestInfo*
const test_info = GetTestInfo(
"Names");
5258 ASSERT_STREQ(
"TestInfoTest", test_info->test_suite_name());
5259 ASSERT_STREQ(
"Names", test_info->name());
5263TEST_F(TestInfoTest, result) {
5264 const TestInfo*
const test_info = GetTestInfo(
"result");
5267 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
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())
5281TEST(CodeLocationForTEST, Verify) {
5282 VERIFY_CODE_LOCATION;
5288 VERIFY_CODE_LOCATION;
5294 VERIFY_CODE_LOCATION;
5297INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
5299template <
typename T>
5305 VERIFY_CODE_LOCATION;
5308template <
typename T>
5314 VERIFY_CODE_LOCATION;
5317REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
5319INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP,
int);
5321#undef VERIFY_CODE_LOCATION
5326#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5331 static void SetUpTestCase() {
5332 printf(
"Setting up the test case . . .\n");
5337 shared_resource_ =
"123";
5343 EXPECT_EQ(1, counter_);
5348 static void TearDownTestCase() {
5349 printf(
"Tearing down the test case . . .\n");
5355 EXPECT_EQ(0, counter_);
5358 shared_resource_ =
nullptr;
5362 void SetUp()
override {
5365 EXPECT_EQ(1, counter_);
5369 static int counter_;
5372 static const char* shared_resource_;
5375int SetUpTestCaseTest::counter_ = 0;
5376const char* SetUpTestCaseTest::shared_resource_ =
nullptr;
5382TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ(
"123", shared_resource_); }
5390 static void SetUpTestSuite() {
5391 printf(
"Setting up the test suite . . .\n");
5396 shared_resource_ =
"123";
5402 EXPECT_EQ(1, counter_);
5407 static void TearDownTestSuite() {
5408 printf(
"Tearing down the test suite . . .\n");
5414 EXPECT_EQ(0, counter_);
5417 shared_resource_ =
nullptr;
5421 void SetUp()
override {
5424 EXPECT_EQ(1, counter_);
5428 static int counter_;
5431 static const char* shared_resource_;
5434int SetUpTestSuiteTest::counter_ = 0;
5435const char* SetUpTestSuiteTest::shared_resource_ =
nullptr;
5439 EXPECT_STRNE(
nullptr, shared_resource_);
5443TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
5444 EXPECT_STREQ(
"123", shared_resource_);
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) {}
5475 static Flags AlsoRunDisabledTests(
bool also_run_disabled_tests) {
5477 flags.also_run_disabled_tests = also_run_disabled_tests;
5483 static Flags BreakOnFailure(
bool break_on_failure) {
5485 flags.break_on_failure = break_on_failure;
5491 static Flags CatchExceptions(
bool catch_exceptions) {
5493 flags.catch_exceptions = catch_exceptions;
5499 static Flags DeathTestUseFork(
bool death_test_use_fork) {
5501 flags.death_test_use_fork = death_test_use_fork;
5507 static Flags FailFast(
bool fail_fast) {
5509 flags.fail_fast = fail_fast;
5515 static Flags Filter(
const char* filter) {
5517 flags.filter = filter;
5523 static Flags ListTests(
bool list_tests) {
5525 flags.list_tests = list_tests;
5531 static Flags Output(
const char* output) {
5533 flags.output = output;
5539 static Flags Brief(
bool brief) {
5541 flags.brief = brief;
5547 static Flags PrintTime(
bool print_time) {
5549 flags.print_time = print_time;
5555 static Flags RandomSeed(int32_t random_seed) {
5557 flags.random_seed = random_seed;
5563 static Flags Repeat(int32_t repeat) {
5565 flags.repeat = repeat;
5571 static Flags RecreateEnvironmentsWhenRepeating(
5572 bool recreate_environments_when_repeating) {
5574 flags.recreate_environments_when_repeating =
5575 recreate_environments_when_repeating;
5581 static Flags Shuffle(
bool shuffle) {
5583 flags.shuffle = shuffle;
5589 static Flags StackTraceDepth(int32_t stack_trace_depth) {
5591 flags.stack_trace_depth = stack_trace_depth;
5597 static Flags StreamResultTo(
const char* stream_result_to) {
5599 flags.stream_result_to = stream_result_to;
5605 static Flags ThrowOnFailure(
bool throw_on_failure) {
5607 flags.throw_on_failure = throw_on_failure;
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;
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);
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;
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));
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
5706 internal::ParseGoogleTestFlagsOnly(&argc1,
const_cast<CharType**
>(argv1));
5708#if GTEST_HAS_STREAM_REDIRECTION
5709 const std::string captured_stdout = GetCapturedStdout();
5713 CheckFlags(expected);
5717 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
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,
5734 ::testing::internal::g_help_flag = saved_help_flag;
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, \
5748 const char* argv[] = {
nullptr};
5750 const char* argv2[] = {
nullptr};
5752 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(),
false);
5756TEST_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);
5765TEST_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);
5774TEST_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);
5783TEST_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);
5792TEST_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);
5801TEST_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);
5810TEST_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);
5819TEST_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);
5829TEST_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);
5838TEST_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);
5847TEST_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);
5857TEST_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);
5867TEST_F(ParseFlagsTest, UnrecognizedFlag) {
5868 const char* argv[] = {
"foo.exe",
"--gtest_break_on_failure",
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);
5881TEST_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);
5890TEST_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);
5899TEST_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);
5908TEST_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);
5917TEST_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);
5926TEST_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);
5935TEST_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);
5944TEST_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/"),
5955TEST_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);
5964TEST_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);
5973TEST_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);
5982TEST_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);
5991TEST_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);
6000TEST_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);
6009TEST_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);
6018TEST_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);
6027TEST_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);
6036TEST_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);
6045TEST_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);
6059TEST_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),
6069TEST_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),
6080TEST_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),
6091TEST_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);
6100TEST_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);
6109TEST_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);
6118TEST_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);
6126TEST_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);
6137TEST_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);
6146TEST_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);
6156TEST_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);
6165TEST_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
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);
6184TEST_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
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);
6203TEST_F(ParseFlagsTest, AbseilPositionalFlags) {
6204 const char* argv[] = {
"foo.exe",
"--gtest_throw_on_failure=1",
"--",
6205 "--other_flag",
nullptr};
6210 const char* argv2[] = {
"foo.exe",
"--other_flag",
nullptr};
6212 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(
true),
false);
6218TEST_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);
6237#if GTEST_USE_OWN_FLAGFILE_FLAG_
6238class 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_;
6269TEST_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);
6282TEST_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);
6296TEST_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);
6322 static void SetUpTestSuite() {
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.";
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.";
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.";
6354TEST_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.";
6368namespace my_namespace {
6385TEST(NestedTestingNamespaceTest, Success) {
6386 EXPECT_EQ(1, 1) <<
"This shouldn't fail.";
6390TEST(NestedTestingNamespaceTest, Failure) {
6391 EXPECT_FATAL_FAILURE(FAIL() <<
"This failure is expected.",
6392 "This failure is expected.");
6404 void SetUp()
override { Test::SetUp(); }
6405 void TearDown()
override { Test::TearDown(); }
6410TEST(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");
6419#pragma option push -w-ccc -w-rch
6422TEST(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");
6431TEST(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");
6445TEST(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");
6454TEST(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");
6463TEST(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");
6472TEST(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");
6481TEST(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");
6490TEST(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");
6499TEST(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
6510TEST(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");
6521TEST(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");
6531TEST(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");
6545TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6546 GTEST_FLAG_SET(color,
"yes");
6548 SetEnv(
"TERM",
"xterm");
6549 EXPECT_TRUE(ShouldUseColor(
true));
6550 EXPECT_TRUE(ShouldUseColor(
false));
6552 SetEnv(
"TERM",
"dumb");
6553 EXPECT_TRUE(ShouldUseColor(
true));
6554 EXPECT_TRUE(ShouldUseColor(
false));
6557TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6558 SetEnv(
"TERM",
"dumb");
6560 GTEST_FLAG_SET(color,
"True");
6561 EXPECT_TRUE(ShouldUseColor(
false));
6563 GTEST_FLAG_SET(color,
"t");
6564 EXPECT_TRUE(ShouldUseColor(
false));
6566 GTEST_FLAG_SET(color,
"1");
6567 EXPECT_TRUE(ShouldUseColor(
false));
6570TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6571 GTEST_FLAG_SET(color,
"no");
6573 SetEnv(
"TERM",
"xterm");
6574 EXPECT_FALSE(ShouldUseColor(
true));
6575 EXPECT_FALSE(ShouldUseColor(
false));
6577 SetEnv(
"TERM",
"dumb");
6578 EXPECT_FALSE(ShouldUseColor(
true));
6579 EXPECT_FALSE(ShouldUseColor(
false));
6582TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6583 SetEnv(
"TERM",
"xterm");
6585 GTEST_FLAG_SET(color,
"F");
6586 EXPECT_FALSE(ShouldUseColor(
true));
6588 GTEST_FLAG_SET(color,
"0");
6589 EXPECT_FALSE(ShouldUseColor(
true));
6591 GTEST_FLAG_SET(color,
"unknown");
6592 EXPECT_FALSE(ShouldUseColor(
true));
6595TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6596 GTEST_FLAG_SET(color,
"auto");
6598 SetEnv(
"TERM",
"xterm");
6599 EXPECT_FALSE(ShouldUseColor(
false));
6600 EXPECT_TRUE(ShouldUseColor(
true));
6603TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6604 GTEST_FLAG_SET(color,
"auto");
6606#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
6609 SetEnv(
"TERM",
"dumb");
6610 EXPECT_TRUE(ShouldUseColor(
true));
6613 EXPECT_TRUE(ShouldUseColor(
true));
6615 SetEnv(
"TERM",
"xterm");
6616 EXPECT_TRUE(ShouldUseColor(
true));
6621 SetEnv(
"TERM",
"dumb");
6622 EXPECT_FALSE(ShouldUseColor(
true));
6624 SetEnv(
"TERM",
"emacs");
6625 EXPECT_FALSE(ShouldUseColor(
true));
6627 SetEnv(
"TERM",
"vt100");
6628 EXPECT_FALSE(ShouldUseColor(
true));
6630 SetEnv(
"TERM",
"xterm-mono");
6631 EXPECT_FALSE(ShouldUseColor(
true));
6633 SetEnv(
"TERM",
"xterm");
6634 EXPECT_TRUE(ShouldUseColor(
true));
6636 SetEnv(
"TERM",
"xterm-color");
6637 EXPECT_TRUE(ShouldUseColor(
true));
6639 SetEnv(
"TERM",
"xterm-256color");
6640 EXPECT_TRUE(ShouldUseColor(
true));
6642 SetEnv(
"TERM",
"screen");
6643 EXPECT_TRUE(ShouldUseColor(
true));
6645 SetEnv(
"TERM",
"screen-256color");
6646 EXPECT_TRUE(ShouldUseColor(
true));
6648 SetEnv(
"TERM",
"tmux");
6649 EXPECT_TRUE(ShouldUseColor(
true));
6651 SetEnv(
"TERM",
"tmux-256color");
6652 EXPECT_TRUE(ShouldUseColor(
true));
6654 SetEnv(
"TERM",
"rxvt-unicode");
6655 EXPECT_TRUE(ShouldUseColor(
true));
6657 SetEnv(
"TERM",
"rxvt-unicode-256color");
6658 EXPECT_TRUE(ShouldUseColor(
true));
6660 SetEnv(
"TERM",
"linux");
6661 EXPECT_TRUE(ShouldUseColor(
true));
6663 SetEnv(
"TERM",
"cygwin");
6664 EXPECT_TRUE(ShouldUseColor(
true));
6670static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6671static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6672 StaticAssertTypeEq<const int, const int>();
6676template <
typename T>
6682TEST(StaticAssertTypeEqTest, WorksInClass) {
6688typedef int IntAlias;
6690TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6691 StaticAssertTypeEq<int, IntAlias>();
6692 StaticAssertTypeEq<int*, IntAlias*>();
6695TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6696 EXPECT_FALSE(HasNonfatalFailure());
6699static void FailFatally() { FAIL(); }
6701TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6703 const bool has_nonfatal_failure = HasNonfatalFailure();
6704 ClearCurrentTestPartResults();
6705 EXPECT_FALSE(has_nonfatal_failure);
6708TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6710 const bool has_nonfatal_failure = HasNonfatalFailure();
6711 ClearCurrentTestPartResults();
6712 EXPECT_TRUE(has_nonfatal_failure);
6715TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6718 const bool has_nonfatal_failure = HasNonfatalFailure();
6719 ClearCurrentTestPartResults();
6720 EXPECT_TRUE(has_nonfatal_failure);
6724static bool HasNonfatalFailureHelper() {
6725 return testing::Test::HasNonfatalFailure();
6728TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6729 EXPECT_FALSE(HasNonfatalFailureHelper());
6732TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6734 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6735 ClearCurrentTestPartResults();
6736 EXPECT_TRUE(has_nonfatal_failure);
6739TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6740 EXPECT_FALSE(HasFailure());
6743TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6745 const bool has_failure = HasFailure();
6746 ClearCurrentTestPartResults();
6747 EXPECT_TRUE(has_failure);
6750TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6752 const bool has_failure = HasFailure();
6753 ClearCurrentTestPartResults();
6754 EXPECT_TRUE(has_failure);
6757TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6760 const bool has_failure = HasFailure();
6761 ClearCurrentTestPartResults();
6762 EXPECT_TRUE(has_failure);
6766static bool HasFailureHelper() {
return testing::Test::HasFailure(); }
6768TEST(HasFailureTest, WorksOutsideOfTestBody) {
6769 EXPECT_FALSE(HasFailureHelper());
6772TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6774 const bool has_failure = HasFailureHelper();
6775 ClearCurrentTestPartResults();
6776 EXPECT_TRUE(has_failure);
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) {}
6786 if (is_destroyed_) *is_destroyed_ =
true;
6790 void OnTestProgramStart(
const UnitTest& )
override {
6791 if (on_start_counter_ !=
nullptr) (*on_start_counter_)++;
6795 int* on_start_counter_;
6796 bool* is_destroyed_;
6800TEST(TestEventListenersTest, ConstructionWorks) {
6803 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) !=
nullptr);
6804 EXPECT_TRUE(listeners.default_result_printer() ==
nullptr);
6805 EXPECT_TRUE(listeners.default_xml_generator() ==
nullptr);
6810TEST(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;
6815 new TestListener(
nullptr, &default_result_printer_is_destroyed);
6817 new TestListener(
nullptr, &default_xml_printer_is_destroyed);
6819 new TestListener(
nullptr, &extra_listener_is_destroyed);
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);
6836TEST(TestEventListenersTest, Append) {
6837 int on_start_counter = 0;
6838 bool is_destroyed =
false;
6842 listeners.Append(listener);
6843 TestEventListenersAccessor::GetRepeater(&listeners)
6844 ->OnTestProgramStart(*UnitTest::GetInstance());
6845 EXPECT_EQ(1, on_start_counter);
6847 EXPECT_TRUE(is_destroyed);
6856 : vector_(vector), id_(
id) {}
6859 void OnTestProgramStart(
const UnitTest& )
override {
6860 vector_->push_back(GetEventDescription(
"OnTestProgramStart"));
6863 void OnTestProgramEnd(
const UnitTest& )
override {
6864 vector_->push_back(GetEventDescription(
"OnTestProgramEnd"));
6867 void OnTestIterationStart(
const UnitTest& ,
6869 vector_->push_back(GetEventDescription(
"OnTestIterationStart"));
6872 void OnTestIterationEnd(
const UnitTest& ,
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_;
6891TEST(EventListenerTest, AppendKeepsOrder) {
6892 std::vector<std::string> vec;
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());
6932TEST(TestEventListenersTest, Release) {
6933 int on_start_counter = 0;
6934 bool is_destroyed =
false;
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);
6953TEST(EventListenerTest, SuppressEventForwarding) {
6954 int on_start_counter = 0;
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);
6969TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
6970 EXPECT_DEATH_IF_SUPPORTED(
6972 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
6973 *GetUnitTestImpl()->listeners()))
6974 <<
"expected failure";
6976 "expected failure");
6982TEST(EventListenerTest, default_result_printer) {
6983 int on_start_counter = 0;
6984 bool is_destroyed =
false;
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);
6999 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
nullptr);
7001 EXPECT_TRUE(listeners.default_result_printer() ==
nullptr);
7002 EXPECT_TRUE(is_destroyed);
7006 TestEventListenersAccessor::GetRepeater(&listeners)
7007 ->OnTestProgramStart(*UnitTest::GetInstance());
7008 EXPECT_EQ(1, on_start_counter);
7013TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
7014 int on_start_counter = 0;
7015 bool is_destroyed =
false;
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);
7029 TestEventListenersAccessor::GetRepeater(&listeners)
7030 ->OnTestProgramStart(*UnitTest::GetInstance());
7031 EXPECT_EQ(0, on_start_counter);
7034 EXPECT_FALSE(is_destroyed);
7041TEST(EventListenerTest, default_xml_generator) {
7042 int on_start_counter = 0;
7043 bool is_destroyed =
false;
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);
7058 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
nullptr);
7060 EXPECT_TRUE(listeners.default_xml_generator() ==
nullptr);
7061 EXPECT_TRUE(is_destroyed);
7065 TestEventListenersAccessor::GetRepeater(&listeners)
7066 ->OnTestProgramStart(*UnitTest::GetInstance());
7067 EXPECT_EQ(1, on_start_counter);
7072TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
7073 int on_start_counter = 0;
7074 bool is_destroyed =
false;
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);
7088 TestEventListenersAccessor::GetRepeater(&listeners)
7089 ->OnTestProgramStart(*UnitTest::GetInstance());
7090 EXPECT_EQ(0, on_start_counter);
7093 EXPECT_FALSE(is_destroyed);
7102GTEST_TEST(AlternativeNameTest, Works) {
7103 GTEST_SUCCEED() <<
"OK";
7106 EXPECT_FATAL_FAILURE(GTEST_FAIL() <<
"An expected failure",
7107 "An expected failure");
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");
7152 std::string DebugString()
const {
return ""; }
7153 std::string ShortDebugString()
const {
return ""; }
7159 std::string DebugString()
const {
return ""; }
7160 int ShortDebugString()
const {
return 1; }
7164 std::string DebugString() {
return ""; }
7165 std::string ShortDebugString()
const {
return ""; }
7169 std::string DebugString() {
return ""; }
7172struct IncompleteType;
7176TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
7201TEST(HasDebugStringAndShortDebugStringTest,
7202 ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
7209TEST(HasDebugStringAndShortDebugStringTest,
7210 ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7218template <
typename T1,
typename T2>
7219void TestGTestRemoveReferenceAndConst() {
7220 static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value,
7221 "GTEST_REMOVE_REFERENCE_AND_CONST_ failed.");
7224TEST(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*>();
7234template <
typename T1,
typename T2>
7235void TestGTestReferenceToConst() {
7236 static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value,
7237 "GTEST_REFERENCE_TO_CONST_ failed.");
7240TEST(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&>();
7251TEST(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)));
7257TEST(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)));
7264 using const_iterator =
int*;
7265 const_iterator begin()
const;
7266 const_iterator end()
const;
7271 const int& operator*()
const;
7278TEST(IsContainerTestTest, ConstOnlyContainer) {
7279 EXPECT_EQ(
sizeof(IsContainer),
7280 sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
7281 EXPECT_EQ(
sizeof(IsContainer),
7282 sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
7287 typedef void hasher;
7290 typedef void hasher;
7291 typedef void reverse_iterator;
7293TEST(IsHashTable, Basic) {
7302TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7303 EXPECT_TRUE(ArrayEq(5, 5L));
7304 EXPECT_FALSE(ArrayEq(
'a', 0));
7307TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
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));
7319TEST(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));
7333TEST(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'));
7339TEST(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));
7350TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7356TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7357 const char a[3] =
"hi";
7361 EXPECT_TRUE(ArrayEq(a, b));
7366 EXPECT_TRUE(ArrayEq(a, c));
7369TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7370 const int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
7374 EXPECT_TRUE(ArrayEq(a, b));
7379 EXPECT_TRUE(ArrayEq(a, c));
7384TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7385 const int a[3] = {0, 1, 2};
7387 EXPECT_EQ(3U, na.size());
7388 EXPECT_EQ(a, na.begin());
7391TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7392 typedef int Array[2];
7393 Array* a =
new Array[1];
7397 EXPECT_NE(*a, na.begin());
7399 EXPECT_EQ(0, na.begin()[0]);
7400 EXPECT_EQ(1, na.begin()[1]);
7406TEST(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>();
7414TEST(NativeArrayTest, MethodsWork) {
7415 const int a[3] = {0, 1, 2};
7417 ASSERT_EQ(3U, na.size());
7418 EXPECT_EQ(3, na.end() - na.begin());
7427 EXPECT_EQ(na.end(), it);
7429 EXPECT_TRUE(na == na);
7432 EXPECT_TRUE(na == na2);
7434 const int b1[3] = {0, 1, 1};
7435 const int b2[4] = {0, 1, 2, 3};
7440TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7441 const char a[2][3] = {
"hi",
"lo"};
7443 ASSERT_EQ(2U, na.size());
7444 EXPECT_EQ(a, na.begin());
7448TEST(IndexSequence, MakeIndexSequence) {
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));
7464TEST(ElemFromList, Basic) {
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));
7478TEST(FlatTuple, Basic) {
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*>(
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>());
7497std::string AddIntToString(
int i,
const std::string& s) {
7498 return s + std::to_string(i);
7502TEST(FlatTuple, Apply) {
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");
7517 tuple.Apply([](
int& i, std::string& s) {
7521 EXPECT_EQ(tuple.Get<0>(), 6);
7522 EXPECT_EQ(tuple.Get<1>(),
"HelloHello");
7531 ++copy_assignment_calls;
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;
7556int ConstructionCounting::default_ctor_calls = 0;
7557int ConstructionCounting::dtor_calls = 0;
7558int ConstructionCounting::copy_ctor_calls = 0;
7559int ConstructionCounting::move_ctor_calls = 0;
7560int ConstructionCounting::copy_assignment_calls = 0;
7561int ConstructionCounting::move_assignment_calls = 0;
7563TEST(FlatTuple, ConstructorCalls) {
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);
7577 ConstructionCounting::Reset();
7580 FlatTuple<ConstructionCounting> tuple{
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);
7591 ConstructionCounting::Reset();
7593 FlatTuple<ConstructionCounting> tuple{
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);
7606 ConstructionCounting::Reset();
7608 FlatTuple<ConstructionCounting> tuple;
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);
7622 ConstructionCounting::Reset();
7624 FlatTuple<ConstructionCounting> tuple;
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();
7637TEST(FlatTuple, ManyTypes) {
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
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>());
7664TEST(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);
7676TEST(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));
7689TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
7691 testing::UnitTest::GetInstance()->ad_hoc_test_result();
7692 EXPECT_FALSE(test_result.Failed());
7698 void TestBody()
override { EXPECT_TRUE(
true); }
7701auto* dynamic_test = testing::RegisterTest(
7702 "DynamicUnitTestFixture",
"DynamicTest",
"TYPE",
"VALUE", __FILE__,
7705TEST(RegisterTest, WasRegistered) {
7706 const 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!";
7724TEST(PatternGlobbingTest, MatchesFilterLinearRuntime) {
7725 std::string name(100,
'a');
7726 name.push_back(
'b');
7728 std::string pattern;
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()));
7738TEST(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*"));
7747TEST(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(
"",
""));
Definition gtest_unittest.cc:5101
Definition gtest_unittest.cc:7148
Definition gtest_unittest.cc:7149
Definition gtest_xml_output_unittest_.cc:63
Definition googletest-output-test_.cc:944
Definition gtest_unittest.cc:7695
Definition googletest-list-tests-unittest_.cc:66
Definition gtest_unittest.cc:7249
Definition gtest_unittest.cc:6402
Definition gtest_unittest.cc:6853
Definition gtest_unittest.cc:6677
Definition gtest_unittest.cc:6779
Definition gtest_unittest.cc:275
Definition googletest-list-tests-unittest_.cc:105
Definition googletest-output-test_.cc:732
Definition gtest_unittest.cc:6382
Definition gtest_unittest.cc:6377
Definition gtest_unittest.cc:6373
Definition gtest_unittest.cc:5152
Definition gtest_unittest.cc:5175
Definition gtest_unittest.cc:5285
Definition gtest_unittest.cc:5291
Definition gtest_unittest.cc:5300
Definition gtest_unittest.cc:5309
Definition gtest_unittest.cc:6318
Definition gtest-message.h:92
Definition gtest_unittest.cc:5632
Definition gtest_unittest.cc:5327
Definition gtest_unittest.cc:5386
Definition gtest_unittest.cc:5236
Definition gtest-internal.h:1279
Definition gtest-internal.h:245
Definition gtest-internal-inl.h:138
Definition gtest-internal.h:894
Definition gtest-internal.h:1097
Definition gtest-internal-inl.h:433
Definition gtest-internal-inl.h:404
Definition gtest-internal.h:868
Definition gtest-string.h:62
Definition gtest_unittest.cc:153
Definition gtest-internal-inl.h:1035
Definition gtest-internal-inl.h:504
Definition gtest_unittest.cc:177
Definition gtest_unittest.cc:7286
Definition gtest_pred_impl_unittest.cc:53
Definition gtest_unittest.cc:7270
Definition gtest_unittest.cc:7269
Definition gtest_unittest.cc:7263
Definition gtest_unittest.cc:7525
Definition gtest_unittest.cc:5090
Definition gtest_unittest.cc:7151
Definition gtest_unittest.cc:7156
Definition gtest_unittest.cc:7168
Definition gtest_unittest.cc:7163
Definition gtest_unittest.cc:7289
Definition gtest_unittest.cc:7158
Definition gtest_unittest.cc:5450
Definition gtest-internal.h:1209
Definition gtest-internal.h:1215
Definition gtest-internal.h:1159
Definition gtest-internal.h:965
Definition gtest-type-util.h:156
Definition gtest-internal.h:1086
Definition gtest-internal.h:1085