1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 // Tests for Google Test itself. This verifies that the basic constructs of
34 #include "gtest/gtest.h"
36 // Verifies that the command line flag variables can be accessed in
37 // code once "gtest.h" has been #included.
38 // Do not move it after other gtest #includes.
39 TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
40 bool dummy = testing::GTEST_FLAG(also_run_disabled_tests) ||
41 testing::GTEST_FLAG(break_on_failure) ||
42 testing::GTEST_FLAG(catch_exceptions) ||
43 testing::GTEST_FLAG(color) != "unknown" ||
44 testing::GTEST_FLAG(fail_fast) ||
45 testing::GTEST_FLAG(filter) != "unknown" ||
46 testing::GTEST_FLAG(list_tests) ||
47 testing::GTEST_FLAG(output) != "unknown" ||
48 testing::GTEST_FLAG(brief) || testing::GTEST_FLAG(print_time) ||
49 testing::GTEST_FLAG(random_seed) ||
50 testing::GTEST_FLAG(repeat) > 0 ||
51 testing::GTEST_FLAG(show_internal_stack_frames) ||
52 testing::GTEST_FLAG(shuffle) ||
53 testing::GTEST_FLAG(stack_trace_depth) > 0 ||
54 testing::GTEST_FLAG(stream_result_to) != "unknown" ||
55 testing::GTEST_FLAG(throw_on_failure);
56 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
59 #include <limits.h> // For INT_MAX.
68 #include <type_traits>
69 #include <unordered_set>
72 #include "gtest/gtest-spi.h"
73 #include "src/gtest-internal-inl.h"
78 #if GTEST_CAN_STREAM_RESULTS_
80 class StreamingListenerTest : public Test {
82 class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
84 // Sends a string to the socket.
85 void Send(const std::string& message) override { output_ += message; }
90 StreamingListenerTest()
91 : fake_sock_writer_(new FakeSocketWriter),
92 streamer_(fake_sock_writer_),
93 test_info_obj_("FooTest", "Bar", nullptr, nullptr,
94 CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {}
97 std::string* output() { return &(fake_sock_writer_->output_); }
99 FakeSocketWriter* const fake_sock_writer_;
100 StreamingListener streamer_;
102 TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test.
105 TEST_F(StreamingListenerTest, OnTestProgramEnd) {
107 streamer_.OnTestProgramEnd(unit_test_);
108 EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
111 TEST_F(StreamingListenerTest, OnTestIterationEnd) {
113 streamer_.OnTestIterationEnd(unit_test_, 42);
114 EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
117 TEST_F(StreamingListenerTest, OnTestCaseStart) {
119 streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", nullptr, nullptr));
120 EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
123 TEST_F(StreamingListenerTest, OnTestCaseEnd) {
125 streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", nullptr, nullptr));
126 EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
129 TEST_F(StreamingListenerTest, OnTestStart) {
131 streamer_.OnTestStart(test_info_obj_);
132 EXPECT_EQ("event=TestStart&name=Bar\n", *output());
135 TEST_F(StreamingListenerTest, OnTestEnd) {
137 streamer_.OnTestEnd(test_info_obj_);
138 EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
141 TEST_F(StreamingListenerTest, OnTestPartResult) {
143 streamer_.OnTestPartResult(TestPartResult(
144 TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
146 // Meta characters in the failure message should be properly escaped.
148 "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
152 #endif // GTEST_CAN_STREAM_RESULTS_
154 // Provides access to otherwise private parts of the TestEventListeners class
155 // that are needed to test it.
156 class TestEventListenersAccessor {
158 static TestEventListener* GetRepeater(TestEventListeners* listeners) {
159 return listeners->repeater();
162 static void SetDefaultResultPrinter(TestEventListeners* listeners,
163 TestEventListener* listener) {
164 listeners->SetDefaultResultPrinter(listener);
166 static void SetDefaultXmlGenerator(TestEventListeners* listeners,
167 TestEventListener* listener) {
168 listeners->SetDefaultXmlGenerator(listener);
171 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
172 return listeners.EventForwardingEnabled();
175 static void SuppressEventForwarding(TestEventListeners* listeners) {
176 listeners->SuppressEventForwarding();
180 class UnitTestRecordPropertyTestHelper : public Test {
182 UnitTestRecordPropertyTestHelper() {}
184 // Forwards to UnitTest::RecordProperty() to bypass access controls.
185 void UnitTestRecordProperty(const char* key, const std::string& value) {
186 unit_test_.RecordProperty(key, value);
192 } // namespace internal
193 } // namespace testing
195 using testing::AssertionFailure;
196 using testing::AssertionResult;
197 using testing::AssertionSuccess;
198 using testing::DoubleLE;
199 using testing::EmptyTestEventListener;
200 using testing::Environment;
201 using testing::FloatLE;
202 using testing::GTEST_FLAG(also_run_disabled_tests);
203 using testing::GTEST_FLAG(break_on_failure);
204 using testing::GTEST_FLAG(catch_exceptions);
205 using testing::GTEST_FLAG(color);
206 using testing::GTEST_FLAG(death_test_use_fork);
207 using testing::GTEST_FLAG(fail_fast);
208 using testing::GTEST_FLAG(filter);
209 using testing::GTEST_FLAG(list_tests);
210 using testing::GTEST_FLAG(output);
211 using testing::GTEST_FLAG(brief);
212 using testing::GTEST_FLAG(print_time);
213 using testing::GTEST_FLAG(random_seed);
214 using testing::GTEST_FLAG(repeat);
215 using testing::GTEST_FLAG(show_internal_stack_frames);
216 using testing::GTEST_FLAG(shuffle);
217 using testing::GTEST_FLAG(stack_trace_depth);
218 using testing::GTEST_FLAG(stream_result_to);
219 using testing::GTEST_FLAG(throw_on_failure);
220 using testing::IsNotSubstring;
221 using testing::IsSubstring;
222 using testing::kMaxStackTraceDepth;
223 using testing::Message;
224 using testing::ScopedFakeTestPartResultReporter;
225 using testing::StaticAssertTypeEq;
227 using testing::TestEventListeners;
228 using testing::TestInfo;
229 using testing::TestPartResult;
230 using testing::TestPartResultArray;
231 using testing::TestProperty;
232 using testing::TestResult;
233 using testing::TestSuite;
234 using testing::TimeInMillis;
235 using testing::UnitTest;
236 using testing::internal::AlwaysFalse;
237 using testing::internal::AlwaysTrue;
238 using testing::internal::AppendUserMessage;
239 using testing::internal::ArrayAwareFind;
240 using testing::internal::ArrayEq;
241 using testing::internal::CodePointToUtf8;
242 using testing::internal::CopyArray;
243 using testing::internal::CountIf;
244 using testing::internal::EqFailure;
245 using testing::internal::FloatingPoint;
246 using testing::internal::ForEach;
247 using testing::internal::FormatEpochTimeInMillisAsIso8601;
248 using testing::internal::FormatTimeInMillisAsSeconds;
249 using testing::internal::GetCurrentOsStackTraceExceptTop;
250 using testing::internal::GetElementOr;
251 using testing::internal::GetNextRandomSeed;
252 using testing::internal::GetRandomSeedFromFlag;
253 using testing::internal::GetTestTypeId;
254 using testing::internal::GetTimeInMillis;
255 using testing::internal::GetTypeId;
256 using testing::internal::GetUnitTestImpl;
257 using testing::internal::GTestFlagSaver;
258 using testing::internal::HasDebugStringAndShortDebugString;
259 using testing::internal::Int32FromEnvOrDie;
260 using testing::internal::IsContainer;
261 using testing::internal::IsContainerTest;
262 using testing::internal::IsNotContainer;
263 using testing::internal::kMaxRandomSeed;
264 using testing::internal::kTestTypeIdInGoogleTest;
265 using testing::internal::NativeArray;
266 using testing::internal::OsStackTraceGetter;
267 using testing::internal::OsStackTraceGetterInterface;
268 using testing::internal::ParseInt32Flag;
269 using testing::internal::RelationToSourceCopy;
270 using testing::internal::RelationToSourceReference;
271 using testing::internal::ShouldRunTestOnShard;
272 using testing::internal::ShouldShard;
273 using testing::internal::ShouldUseColor;
274 using testing::internal::Shuffle;
275 using testing::internal::ShuffleRange;
276 using testing::internal::SkipPrefix;
277 using testing::internal::StreamableToString;
278 using testing::internal::String;
279 using testing::internal::TestEventListenersAccessor;
280 using testing::internal::TestResultAccessor;
281 using testing::internal::UnitTestImpl;
282 using testing::internal::WideStringToUtf8;
283 using testing::internal::edit_distance::CalculateOptimalEdits;
284 using testing::internal::edit_distance::CreateUnifiedDiff;
285 using testing::internal::edit_distance::EditType;
287 #if GTEST_HAS_STREAM_REDIRECTION
288 using testing::internal::CaptureStdout;
289 using testing::internal::GetCapturedStdout;
292 #if GTEST_IS_THREADSAFE
293 using testing::internal::ThreadWithParam;
296 class TestingVector : public std::vector<int> {
299 ::std::ostream& operator<<(::std::ostream& os,
300 const TestingVector& vector) {
302 for (size_t i = 0; i < vector.size(); i++) {
303 os << vector[i] << " ";
309 // This line tests that we can define tests in an unnamed namespace.
312 TEST(GetRandomSeedFromFlagTest, HandlesZero) {
313 const int seed = GetRandomSeedFromFlag(0);
315 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
318 TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
319 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
320 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
321 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
322 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
323 GetRandomSeedFromFlag(kMaxRandomSeed));
326 TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
327 const int seed1 = GetRandomSeedFromFlag(-1);
329 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
331 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
333 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
336 TEST(GetNextRandomSeedTest, WorksForValidInput) {
337 EXPECT_EQ(2, GetNextRandomSeed(1));
338 EXPECT_EQ(3, GetNextRandomSeed(2));
339 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
340 GetNextRandomSeed(kMaxRandomSeed - 1));
341 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
343 // We deliberately don't test GetNextRandomSeed() with invalid
344 // inputs, as that requires death tests, which are expensive. This
345 // is fine as GetNextRandomSeed() is internal and has a
346 // straightforward definition.
349 static void ClearCurrentTestPartResults() {
350 TestResultAccessor::ClearTestPartResults(
351 GetUnitTestImpl()->current_test_result());
356 TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
357 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
358 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
361 class SubClassOfTest : public Test {};
362 class AnotherSubClassOfTest : public Test {};
364 TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
365 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
366 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
367 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
368 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
369 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
370 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
373 // Verifies that GetTestTypeId() returns the same value, no matter it
374 // is called from inside Google Test or outside of it.
375 TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
376 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
379 // Tests CanonicalizeForStdLibVersioning.
381 using ::testing::internal::CanonicalizeForStdLibVersioning;
383 TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) {
384 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind"));
385 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_"));
386 EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo"));
387 EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x"));
388 EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x"));
389 EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x"));
392 TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
393 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind"));
394 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_"));
396 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind"));
397 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_"));
399 EXPECT_EQ("std::bind",
400 CanonicalizeForStdLibVersioning("std::__google::bind"));
401 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_"));
404 // Tests FormatTimeInMillisAsSeconds().
406 TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
407 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
410 TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
411 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
412 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
413 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
414 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
415 EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
418 TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
419 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
420 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
421 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
422 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
423 EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
426 // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
427 // for particular dates below was verified in Python using
428 // datetime.datetime.fromutctimestamp(<timetamp>/1000).
430 // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
431 // have to set up a particular timezone to obtain predictable results.
432 class FormatEpochTimeInMillisAsIso8601Test : public Test {
434 // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
435 // 32 bits, even when 64-bit integer types are available. We have to
436 // force the constants to have a 64-bit type here.
437 static const TimeInMillis kMillisPerSec = 1000;
440 void SetUp() override {
443 GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
445 saved_tz_ = strdup(getenv("TZ"));
446 GTEST_DISABLE_MSC_DEPRECATED_POP_()
448 // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
449 // cannot use the local time zone because the function's output depends
451 SetTimeZone("UTC+00");
454 void TearDown() override {
455 SetTimeZone(saved_tz_);
456 free(const_cast<char*>(saved_tz_));
460 static void SetTimeZone(const char* time_zone) {
461 // tzset() distinguishes between the TZ variable being present and empty
462 // and not being present, so we have to consider the case of time_zone
464 #if _MSC_VER || GTEST_OS_WINDOWS_MINGW
465 // ...Unless it's MSVC, whose standard library's _putenv doesn't
466 // distinguish between an empty and a missing variable.
467 const std::string env_var =
468 std::string("TZ=") + (time_zone ? time_zone : "");
469 _putenv(env_var.c_str());
470 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
472 GTEST_DISABLE_MSC_WARNINGS_POP_()
475 setenv(("TZ"), time_zone, 1);
483 const char* saved_tz_;
486 const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
488 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
489 EXPECT_EQ("2011-10-31T18:52:42.000",
490 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
493 TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
495 "2011-10-31T18:52:42.234",
496 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
499 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
500 EXPECT_EQ("2011-09-03T05:07:02.000",
501 FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
504 TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
505 EXPECT_EQ("2011-09-28T17:08:22.000",
506 FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
509 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
510 EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
514 // Silences warnings: "Condition is always true", "Unreachable code"
515 # pragma option push -w-ccc -w-rch
518 // Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal
519 // when the RHS is a pointer type.
520 TEST(NullLiteralTest, LHSAllowsNullLiterals) {
521 EXPECT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
522 ASSERT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
523 EXPECT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
524 ASSERT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
525 EXPECT_EQ(nullptr, static_cast<void*>(nullptr));
526 ASSERT_EQ(nullptr, static_cast<void*>(nullptr));
528 const int* const p = nullptr;
529 EXPECT_EQ(0, p); // NOLINT
530 ASSERT_EQ(0, p); // NOLINT
531 EXPECT_EQ(NULL, p); // NOLINT
532 ASSERT_EQ(NULL, p); // NOLINT
533 EXPECT_EQ(nullptr, p);
534 ASSERT_EQ(nullptr, p);
537 struct ConvertToAll {
538 template <typename T>
539 operator T() const { // NOLINT
544 struct ConvertToPointer {
546 operator T*() const { // NOLINT
551 struct ConvertToAllButNoPointers {
552 template <typename T,
553 typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0>
554 operator T() const { // NOLINT
560 inline bool operator==(MyType const&, MyType const&) { return true; }
562 TEST(NullLiteralTest, ImplicitConversion) {
563 EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr));
564 #if !defined(__GNUC__) || defined(__clang__)
565 // Disabled due to GCC bug gcc.gnu.org/PR89580
566 EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr));
568 EXPECT_EQ(ConvertToAll{}, MyType{});
569 EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{});
573 #pragma clang diagnostic push
574 #if __has_warning("-Wzero-as-null-pointer-constant")
575 #pragma clang diagnostic error "-Wzero-as-null-pointer-constant"
579 TEST(NullLiteralTest, NoConversionNoWarning) {
580 // Test that gtests detection and handling of null pointer constants
581 // doesn't trigger a warning when '0' isn't actually used as null.
587 #pragma clang diagnostic pop
591 // Restores warnings after previous "#pragma option push" suppressed them.
596 // Tests CodePointToUtf8().
598 // Tests that the NUL character L'\0' is encoded correctly.
599 TEST(CodePointToUtf8Test, CanEncodeNul) {
600 EXPECT_EQ("", CodePointToUtf8(L'\0'));
603 // Tests that ASCII characters are encoded correctly.
604 TEST(CodePointToUtf8Test, CanEncodeAscii) {
605 EXPECT_EQ("a", CodePointToUtf8(L'a'));
606 EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
607 EXPECT_EQ("&", CodePointToUtf8(L'&'));
608 EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
611 // Tests that Unicode code-points that have 8 to 11 bits are encoded
612 // as 110xxxxx 10xxxxxx.
613 TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
614 // 000 1101 0011 => 110-00011 10-010011
615 EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
617 // 101 0111 0110 => 110-10101 10-110110
618 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
619 // in wide strings and wide chars. In order to accommodate them, we have to
620 // introduce such character constants as integers.
621 EXPECT_EQ("\xD5\xB6",
622 CodePointToUtf8(static_cast<wchar_t>(0x576)));
625 // Tests that Unicode code-points that have 12 to 16 bits are encoded
626 // as 1110xxxx 10xxxxxx 10xxxxxx.
627 TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
628 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
629 EXPECT_EQ("\xE0\xA3\x93",
630 CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
632 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
633 EXPECT_EQ("\xEC\x9D\x8D",
634 CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
637 #if !GTEST_WIDE_STRING_USES_UTF16_
638 // Tests in this group require a wchar_t to hold > 16 bits, and thus
639 // are skipped on Windows, and Cygwin, where a wchar_t is
640 // 16-bit wide. This code may not compile on those systems.
642 // Tests that Unicode code-points that have 17 to 21 bits are encoded
643 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
644 TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
645 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
646 EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
648 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
649 EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
651 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
652 EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
655 // Tests that encoding an invalid code-point generates the expected result.
656 TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
657 EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
660 #endif // !GTEST_WIDE_STRING_USES_UTF16_
662 // Tests WideStringToUtf8().
664 // Tests that the NUL character L'\0' is encoded correctly.
665 TEST(WideStringToUtf8Test, CanEncodeNul) {
666 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
667 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
670 // Tests that ASCII strings are encoded correctly.
671 TEST(WideStringToUtf8Test, CanEncodeAscii) {
672 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
673 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
674 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
675 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
678 // Tests that Unicode code-points that have 8 to 11 bits are encoded
679 // as 110xxxxx 10xxxxxx.
680 TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
681 // 000 1101 0011 => 110-00011 10-010011
682 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
683 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
685 // 101 0111 0110 => 110-10101 10-110110
686 const wchar_t s[] = { 0x576, '\0' };
687 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
688 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
691 // Tests that Unicode code-points that have 12 to 16 bits are encoded
692 // as 1110xxxx 10xxxxxx 10xxxxxx.
693 TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
694 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
695 const wchar_t s1[] = { 0x8D3, '\0' };
696 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
697 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
699 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
700 const wchar_t s2[] = { 0xC74D, '\0' };
701 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
702 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
705 // Tests that the conversion stops when the function encounters \0 character.
706 TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
707 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
710 // Tests that the conversion stops when the function reaches the limit
711 // specified by the 'length' parameter.
712 TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
713 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
716 #if !GTEST_WIDE_STRING_USES_UTF16_
717 // Tests that Unicode code-points that have 17 to 21 bits are encoded
718 // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
719 // on the systems using UTF-16 encoding.
720 TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
721 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
722 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
723 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
725 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
726 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
727 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
730 // Tests that encoding an invalid code-point generates the expected result.
731 TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
732 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
733 WideStringToUtf8(L"\xABCDFF", -1).c_str());
735 #else // !GTEST_WIDE_STRING_USES_UTF16_
736 // Tests that surrogate pairs are encoded correctly on the systems using
737 // UTF-16 encoding in the wide strings.
738 TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
739 const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
740 EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
743 // Tests that encoding an invalid UTF-16 surrogate pair
744 // generates the expected result.
745 TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
746 // Leading surrogate is at the end of the string.
747 const wchar_t s1[] = { 0xD800, '\0' };
748 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
749 // Leading surrogate is not followed by the trailing surrogate.
750 const wchar_t s2[] = { 0xD800, 'M', '\0' };
751 EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
752 // Trailing surrogate appearas without a leading surrogate.
753 const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
754 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
756 #endif // !GTEST_WIDE_STRING_USES_UTF16_
758 // Tests that codepoint concatenation works correctly.
759 #if !GTEST_WIDE_STRING_USES_UTF16_
760 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
761 const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
769 WideStringToUtf8(s, -1).c_str());
772 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
773 const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
775 "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
776 WideStringToUtf8(s, -1).c_str());
778 #endif // !GTEST_WIDE_STRING_USES_UTF16_
780 // Tests the Random class.
782 TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
783 testing::internal::Random random(42);
784 EXPECT_DEATH_IF_SUPPORTED(
786 "Cannot generate a number in the range \\[0, 0\\)");
787 EXPECT_DEATH_IF_SUPPORTED(
788 random.Generate(testing::internal::Random::kMaxRange + 1),
789 "Generation of a number in \\[0, 2147483649\\) was requested, "
790 "but this can only generate numbers in \\[0, 2147483648\\)");
793 TEST(RandomTest, GeneratesNumbersWithinRange) {
794 constexpr uint32_t kRange = 10000;
795 testing::internal::Random random(12345);
796 for (int i = 0; i < 10; i++) {
797 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
800 testing::internal::Random random2(testing::internal::Random::kMaxRange);
801 for (int i = 0; i < 10; i++) {
802 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
806 TEST(RandomTest, RepeatsWhenReseeded) {
807 constexpr int kSeed = 123;
808 constexpr int kArraySize = 10;
809 constexpr uint32_t kRange = 10000;
810 uint32_t values[kArraySize];
812 testing::internal::Random random(kSeed);
813 for (int i = 0; i < kArraySize; i++) {
814 values[i] = random.Generate(kRange);
817 random.Reseed(kSeed);
818 for (int i = 0; i < kArraySize; i++) {
819 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
823 // Tests STL container utilities.
827 static bool IsPositive(int n) { return n > 0; }
829 TEST(ContainerUtilityTest, CountIf) {
831 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
835 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
840 EXPECT_EQ(2, CountIf(v, IsPositive));
845 static int g_sum = 0;
846 static void Accumulate(int n) { g_sum += n; }
848 TEST(ContainerUtilityTest, ForEach) {
851 ForEach(v, Accumulate);
852 EXPECT_EQ(0, g_sum); // Works for an empty container;
856 ForEach(v, Accumulate);
857 EXPECT_EQ(1, g_sum); // Works for a container with one element.
862 ForEach(v, Accumulate);
863 EXPECT_EQ(321, g_sum);
866 // Tests GetElementOr().
867 TEST(ContainerUtilityTest, GetElementOr) {
869 EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
873 EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
874 EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
875 EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
876 EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
879 TEST(ContainerUtilityDeathTest, ShuffleRange) {
884 testing::internal::Random random(1);
886 EXPECT_DEATH_IF_SUPPORTED(
887 ShuffleRange(&random, -1, 1, &a),
888 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
889 EXPECT_DEATH_IF_SUPPORTED(
890 ShuffleRange(&random, 4, 4, &a),
891 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
892 EXPECT_DEATH_IF_SUPPORTED(
893 ShuffleRange(&random, 3, 2, &a),
894 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
895 EXPECT_DEATH_IF_SUPPORTED(
896 ShuffleRange(&random, 3, 4, &a),
897 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
900 class VectorShuffleTest : public Test {
902 static const size_t kVectorSize = 20;
904 VectorShuffleTest() : random_(1) {
905 for (int i = 0; i < static_cast<int>(kVectorSize); i++) {
906 vector_.push_back(i);
910 static bool VectorIsCorrupt(const TestingVector& vector) {
911 if (kVectorSize != vector.size()) {
915 bool found_in_vector[kVectorSize] = { false };
916 for (size_t i = 0; i < vector.size(); i++) {
917 const int e = vector[i];
918 if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {
921 found_in_vector[e] = true;
924 // Vector size is correct, elements' range is correct, no
925 // duplicate elements. Therefore no corruption has occurred.
929 static bool VectorIsNotCorrupt(const TestingVector& vector) {
930 return !VectorIsCorrupt(vector);
933 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
934 for (int i = begin; i < end; i++) {
935 if (i != vector[static_cast<size_t>(i)]) {
942 static bool RangeIsUnshuffled(
943 const TestingVector& vector, int begin, int end) {
944 return !RangeIsShuffled(vector, begin, end);
947 static bool VectorIsShuffled(const TestingVector& vector) {
948 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
951 static bool VectorIsUnshuffled(const TestingVector& vector) {
952 return !VectorIsShuffled(vector);
955 testing::internal::Random random_;
956 TestingVector vector_;
957 }; // class VectorShuffleTest
959 const size_t VectorShuffleTest::kVectorSize;
961 TEST_F(VectorShuffleTest, HandlesEmptyRange) {
962 // Tests an empty range at the beginning...
963 ShuffleRange(&random_, 0, 0, &vector_);
964 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
965 ASSERT_PRED1(VectorIsUnshuffled, vector_);
967 // ...in the middle...
968 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
969 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
970 ASSERT_PRED1(VectorIsUnshuffled, vector_);
973 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
974 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
975 ASSERT_PRED1(VectorIsUnshuffled, vector_);
977 // ...and past the end.
978 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
979 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
980 ASSERT_PRED1(VectorIsUnshuffled, vector_);
983 TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
984 // Tests a size one range at the beginning...
985 ShuffleRange(&random_, 0, 1, &vector_);
986 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
987 ASSERT_PRED1(VectorIsUnshuffled, vector_);
989 // ...in the middle...
990 ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
991 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
992 ASSERT_PRED1(VectorIsUnshuffled, vector_);
994 // ...and at the end.
995 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
996 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
997 ASSERT_PRED1(VectorIsUnshuffled, vector_);
1000 // Because we use our own random number generator and a fixed seed,
1001 // we can guarantee that the following "random" tests will succeed.
1003 TEST_F(VectorShuffleTest, ShufflesEntireVector) {
1004 Shuffle(&random_, &vector_);
1005 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1006 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
1008 // Tests the first and last elements in particular to ensure that
1009 // there are no off-by-one problems in our shuffle algorithm.
1010 EXPECT_NE(0, vector_[0]);
1011 EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);
1014 TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
1015 const int kRangeSize = kVectorSize/2;
1017 ShuffleRange(&random_, 0, kRangeSize, &vector_);
1019 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1020 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
1021 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize,
1022 static_cast<int>(kVectorSize));
1025 TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
1026 const int kRangeSize = kVectorSize / 2;
1027 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
1029 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1030 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1031 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize,
1032 static_cast<int>(kVectorSize));
1035 TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
1036 const int kRangeSize = static_cast<int>(kVectorSize) / 3;
1037 ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
1039 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1040 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1041 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
1042 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,
1043 static_cast<int>(kVectorSize));
1046 TEST_F(VectorShuffleTest, ShufflesRepeatably) {
1047 TestingVector vector2;
1048 for (size_t i = 0; i < kVectorSize; i++) {
1049 vector2.push_back(static_cast<int>(i));
1052 random_.Reseed(1234);
1053 Shuffle(&random_, &vector_);
1054 random_.Reseed(1234);
1055 Shuffle(&random_, &vector2);
1057 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1058 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
1060 for (size_t i = 0; i < kVectorSize; i++) {
1061 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
1065 // Tests the size of the AssertHelper class.
1067 TEST(AssertHelperTest, AssertHelperIsSmall) {
1068 // To avoid breaking clients that use lots of assertions in one
1069 // function, we cannot grow the size of AssertHelper.
1070 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
1073 // Tests String::EndsWithCaseInsensitive().
1074 TEST(StringTest, EndsWithCaseInsensitive) {
1075 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
1076 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
1077 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
1078 EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
1080 EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
1081 EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
1082 EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
1085 // C++Builder's preprocessor is buggy; it fails to expand macros that
1086 // appear in macro parameters after wide char literals. Provide an alias
1087 // for NULL as a workaround.
1088 static const wchar_t* const kNull = nullptr;
1090 // Tests String::CaseInsensitiveWideCStringEquals
1091 TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1092 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr));
1093 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1094 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1095 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1096 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
1097 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1098 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1099 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1102 #if GTEST_OS_WINDOWS
1104 // Tests String::ShowWideCString().
1105 TEST(StringTest, ShowWideCString) {
1106 EXPECT_STREQ("(null)",
1107 String::ShowWideCString(NULL).c_str());
1108 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1109 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1112 # if GTEST_OS_WINDOWS_MOBILE
1113 TEST(StringTest, AnsiAndUtf16Null) {
1114 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1115 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1118 TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1119 const char* ansi = String::Utf16ToAnsi(L"str");
1120 EXPECT_STREQ("str", ansi);
1122 const WCHAR* utf16 = String::AnsiToUtf16("str");
1123 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
1127 TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1128 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1129 EXPECT_STREQ(".:\\ \"*?", ansi);
1131 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
1132 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
1135 # endif // GTEST_OS_WINDOWS_MOBILE
1137 #endif // GTEST_OS_WINDOWS
1139 // Tests TestProperty construction.
1140 TEST(TestPropertyTest, StringValue) {
1141 TestProperty property("key", "1");
1142 EXPECT_STREQ("key", property.key());
1143 EXPECT_STREQ("1", property.value());
1146 // Tests TestProperty replacing a value.
1147 TEST(TestPropertyTest, ReplaceStringValue) {
1148 TestProperty property("key", "1");
1149 EXPECT_STREQ("1", property.value());
1150 property.SetValue("2");
1151 EXPECT_STREQ("2", property.value());
1154 // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1155 // functions (i.e. their definitions cannot be inlined at the call
1156 // sites), or C++Builder won't compile the code.
1157 static void AddFatalFailure() {
1158 FAIL() << "Expected fatal failure.";
1161 static void AddNonfatalFailure() {
1162 ADD_FAILURE() << "Expected non-fatal failure.";
1165 class ScopedFakeTestPartResultReporterTest : public Test {
1166 public: // Must be public and not protected due to a bug in g++ 3.4.2.
1171 static void AddFailure(FailureMode failure) {
1172 if (failure == FATAL_FAILURE) {
1175 AddNonfatalFailure();
1180 // Tests that ScopedFakeTestPartResultReporter intercepts test
1182 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
1183 TestPartResultArray results;
1185 ScopedFakeTestPartResultReporter reporter(
1186 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1188 AddFailure(NONFATAL_FAILURE);
1189 AddFailure(FATAL_FAILURE);
1192 EXPECT_EQ(2, results.size());
1193 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1194 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1197 TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1198 TestPartResultArray results;
1200 // Tests, that the deprecated constructor still works.
1201 ScopedFakeTestPartResultReporter reporter(&results);
1202 AddFailure(NONFATAL_FAILURE);
1204 EXPECT_EQ(1, results.size());
1207 #if GTEST_IS_THREADSAFE
1209 class ScopedFakeTestPartResultReporterWithThreadsTest
1210 : public ScopedFakeTestPartResultReporterTest {
1212 static void AddFailureInOtherThread(FailureMode failure) {
1213 ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
1218 TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1219 InterceptsTestFailuresInAllThreads) {
1220 TestPartResultArray results;
1222 ScopedFakeTestPartResultReporter reporter(
1223 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1224 AddFailure(NONFATAL_FAILURE);
1225 AddFailure(FATAL_FAILURE);
1226 AddFailureInOtherThread(NONFATAL_FAILURE);
1227 AddFailureInOtherThread(FATAL_FAILURE);
1230 EXPECT_EQ(4, results.size());
1231 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1232 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1233 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1234 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1237 #endif // GTEST_IS_THREADSAFE
1239 // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1240 // work even if the failure is generated in a called function rather than
1241 // the current context.
1243 typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
1245 TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1246 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
1249 TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1250 EXPECT_FATAL_FAILURE(AddFatalFailure(),
1251 ::std::string("Expected fatal failure."));
1254 TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1255 // We have another test below to verify that the macro catches fatal
1256 // failures generated on another thread.
1257 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
1258 "Expected fatal failure.");
1262 // Silences warnings: "Condition is always true"
1263 # pragma option push -w-ccc
1266 // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1267 // function even when the statement in it contains ASSERT_*.
1269 int NonVoidFunction() {
1270 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1271 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1275 TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1279 // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1280 // current function even though 'statement' generates a fatal failure.
1282 void DoesNotAbortHelper(bool* aborted) {
1283 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1284 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1290 // Restores warnings after previous "#pragma option push" suppressed them.
1294 TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1295 bool aborted = true;
1296 DoesNotAbortHelper(&aborted);
1297 EXPECT_FALSE(aborted);
1300 // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1301 // statement that contains a macro which expands to code containing an
1302 // unprotected comma.
1304 static int global_var = 0;
1305 #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1307 TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1308 #ifndef __BORLANDC__
1309 // ICE's in C++Builder.
1310 EXPECT_FATAL_FAILURE({
1311 GTEST_USE_UNPROTECTED_COMMA_;
1316 EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
1317 GTEST_USE_UNPROTECTED_COMMA_;
1322 // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1324 typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1326 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1327 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1328 "Expected non-fatal failure.");
1331 TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1332 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1333 ::std::string("Expected non-fatal failure."));
1336 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
1337 // We have another test below to verify that the macro catches
1338 // non-fatal failures generated on another thread.
1339 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
1340 "Expected non-fatal failure.");
1343 // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1344 // statement that contains a macro which expands to code containing an
1345 // unprotected comma.
1346 TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1347 EXPECT_NONFATAL_FAILURE({
1348 GTEST_USE_UNPROTECTED_COMMA_;
1349 AddNonfatalFailure();
1352 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
1353 GTEST_USE_UNPROTECTED_COMMA_;
1354 AddNonfatalFailure();
1358 #if GTEST_IS_THREADSAFE
1360 typedef ScopedFakeTestPartResultReporterWithThreadsTest
1361 ExpectFailureWithThreadsTest;
1363 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1364 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1365 "Expected fatal failure.");
1368 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1369 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
1370 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1373 #endif // GTEST_IS_THREADSAFE
1375 // Tests the TestProperty class.
1377 TEST(TestPropertyTest, ConstructorWorks) {
1378 const TestProperty property("key", "value");
1379 EXPECT_STREQ("key", property.key());
1380 EXPECT_STREQ("value", property.value());
1383 TEST(TestPropertyTest, SetValue) {
1384 TestProperty property("key", "value_1");
1385 EXPECT_STREQ("key", property.key());
1386 property.SetValue("value_2");
1387 EXPECT_STREQ("key", property.key());
1388 EXPECT_STREQ("value_2", property.value());
1391 // Tests the TestResult class
1393 // The test fixture for testing TestResult.
1394 class TestResultTest : public Test {
1396 typedef std::vector<TestPartResult> TPRVector;
1398 // We make use of 2 TestPartResult objects,
1399 TestPartResult * pr1, * pr2;
1401 // ... and 3 TestResult objects.
1402 TestResult * r0, * r1, * r2;
1404 void SetUp() override {
1405 // pr1 is for success.
1406 pr1 = new TestPartResult(TestPartResult::kSuccess,
1411 // pr2 is for fatal failure.
1412 pr2 = new TestPartResult(TestPartResult::kFatalFailure,
1414 -1, // This line number means "unknown"
1417 // Creates the TestResult objects.
1418 r0 = new TestResult();
1419 r1 = new TestResult();
1420 r2 = new TestResult();
1422 // In order to test TestResult, we need to modify its internal
1423 // state, in particular the TestPartResult vector it holds.
1424 // test_part_results() returns a const reference to this vector.
1425 // We cast it to a non-const object s.t. it can be modified
1426 TPRVector* results1 = const_cast<TPRVector*>(
1427 &TestResultAccessor::test_part_results(*r1));
1428 TPRVector* results2 = const_cast<TPRVector*>(
1429 &TestResultAccessor::test_part_results(*r2));
1431 // r0 is an empty TestResult.
1433 // r1 contains a single SUCCESS TestPartResult.
1434 results1->push_back(*pr1);
1436 // r2 contains a SUCCESS, and a FAILURE.
1437 results2->push_back(*pr1);
1438 results2->push_back(*pr2);
1441 void TearDown() override {
1450 // Helper that compares two TestPartResults.
1451 static void CompareTestPartResult(const TestPartResult& expected,
1452 const TestPartResult& actual) {
1453 EXPECT_EQ(expected.type(), actual.type());
1454 EXPECT_STREQ(expected.file_name(), actual.file_name());
1455 EXPECT_EQ(expected.line_number(), actual.line_number());
1456 EXPECT_STREQ(expected.summary(), actual.summary());
1457 EXPECT_STREQ(expected.message(), actual.message());
1458 EXPECT_EQ(expected.passed(), actual.passed());
1459 EXPECT_EQ(expected.failed(), actual.failed());
1460 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1461 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
1465 // Tests TestResult::total_part_count().
1466 TEST_F(TestResultTest, total_part_count) {
1467 ASSERT_EQ(0, r0->total_part_count());
1468 ASSERT_EQ(1, r1->total_part_count());
1469 ASSERT_EQ(2, r2->total_part_count());
1472 // Tests TestResult::Passed().
1473 TEST_F(TestResultTest, Passed) {
1474 ASSERT_TRUE(r0->Passed());
1475 ASSERT_TRUE(r1->Passed());
1476 ASSERT_FALSE(r2->Passed());
1479 // Tests TestResult::Failed().
1480 TEST_F(TestResultTest, Failed) {
1481 ASSERT_FALSE(r0->Failed());
1482 ASSERT_FALSE(r1->Failed());
1483 ASSERT_TRUE(r2->Failed());
1486 // Tests TestResult::GetTestPartResult().
1488 typedef TestResultTest TestResultDeathTest;
1490 TEST_F(TestResultDeathTest, GetTestPartResult) {
1491 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1492 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1493 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
1494 EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
1497 // Tests TestResult has no properties when none are added.
1498 TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1499 TestResult test_result;
1500 ASSERT_EQ(0, test_result.test_property_count());
1503 // Tests TestResult has the expected property when added.
1504 TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1505 TestResult test_result;
1506 TestProperty property("key_1", "1");
1507 TestResultAccessor::RecordProperty(&test_result, "testcase", property);
1508 ASSERT_EQ(1, test_result.test_property_count());
1509 const TestProperty& actual_property = test_result.GetTestProperty(0);
1510 EXPECT_STREQ("key_1", actual_property.key());
1511 EXPECT_STREQ("1", actual_property.value());
1514 // Tests TestResult has multiple properties when added.
1515 TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1516 TestResult test_result;
1517 TestProperty property_1("key_1", "1");
1518 TestProperty property_2("key_2", "2");
1519 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1520 TestResultAccessor::RecordProperty(&test_result, "testcase", property_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("1", 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("2", actual_property_2.value());
1531 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
1532 TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1533 TestResult test_result;
1534 TestProperty property_1_1("key_1", "1");
1535 TestProperty property_2_1("key_2", "2");
1536 TestProperty property_1_2("key_1", "12");
1537 TestProperty property_2_2("key_2", "22");
1538 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
1539 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
1540 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
1541 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
1543 ASSERT_EQ(2, test_result.test_property_count());
1544 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1545 EXPECT_STREQ("key_1", actual_property_1.key());
1546 EXPECT_STREQ("12", actual_property_1.value());
1548 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1549 EXPECT_STREQ("key_2", actual_property_2.key());
1550 EXPECT_STREQ("22", actual_property_2.value());
1553 // Tests TestResult::GetTestProperty().
1554 TEST(TestResultPropertyTest, GetTestProperty) {
1555 TestResult test_result;
1556 TestProperty property_1("key_1", "1");
1557 TestProperty property_2("key_2", "2");
1558 TestProperty property_3("key_3", "3");
1559 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1560 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1561 TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
1563 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1564 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1565 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
1567 EXPECT_STREQ("key_1", fetched_property_1.key());
1568 EXPECT_STREQ("1", fetched_property_1.value());
1570 EXPECT_STREQ("key_2", fetched_property_2.key());
1571 EXPECT_STREQ("2", fetched_property_2.value());
1573 EXPECT_STREQ("key_3", fetched_property_3.key());
1574 EXPECT_STREQ("3", fetched_property_3.value());
1576 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1577 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
1580 // Tests the Test class.
1582 // It's difficult to test every public method of this class (we are
1583 // already stretching the limit of Google Test by using it to test itself!).
1584 // Fortunately, we don't have to do that, as we are already testing
1585 // the functionalities of the Test class extensively by using Google Test
1588 // Therefore, this section only contains one test.
1590 // Tests that GTestFlagSaver works on Windows and Mac.
1592 class GTestFlagSaverTest : public Test {
1594 // Saves the Google Test flags such that we can restore them later, and
1595 // then sets them to their default values. This will be called
1596 // before the first test in this test case is run.
1597 static void SetUpTestSuite() {
1598 saver_ = new GTestFlagSaver;
1600 GTEST_FLAG(also_run_disabled_tests) = false;
1601 GTEST_FLAG(break_on_failure) = false;
1602 GTEST_FLAG(catch_exceptions) = false;
1603 GTEST_FLAG(death_test_use_fork) = false;
1604 GTEST_FLAG(color) = "auto";
1605 GTEST_FLAG(fail_fast) = false;
1606 GTEST_FLAG(filter) = "";
1607 GTEST_FLAG(list_tests) = false;
1608 GTEST_FLAG(output) = "";
1609 GTEST_FLAG(brief) = false;
1610 GTEST_FLAG(print_time) = true;
1611 GTEST_FLAG(random_seed) = 0;
1612 GTEST_FLAG(repeat) = 1;
1613 GTEST_FLAG(shuffle) = false;
1614 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
1615 GTEST_FLAG(stream_result_to) = "";
1616 GTEST_FLAG(throw_on_failure) = false;
1619 // Restores the Google Test flags that the tests have modified. This will
1620 // be called after the last test in this test case is run.
1621 static void TearDownTestSuite() {
1626 // Verifies that the Google Test flags have their default values, and then
1627 // modifies each of them.
1628 void VerifyAndModifyFlags() {
1629 EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
1630 EXPECT_FALSE(GTEST_FLAG(break_on_failure));
1631 EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
1632 EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
1633 EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
1634 EXPECT_FALSE(GTEST_FLAG(fail_fast));
1635 EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
1636 EXPECT_FALSE(GTEST_FLAG(list_tests));
1637 EXPECT_STREQ("", GTEST_FLAG(output).c_str());
1638 EXPECT_FALSE(GTEST_FLAG(brief));
1639 EXPECT_TRUE(GTEST_FLAG(print_time));
1640 EXPECT_EQ(0, GTEST_FLAG(random_seed));
1641 EXPECT_EQ(1, GTEST_FLAG(repeat));
1642 EXPECT_FALSE(GTEST_FLAG(shuffle));
1643 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
1644 EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
1645 EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
1647 GTEST_FLAG(also_run_disabled_tests) = true;
1648 GTEST_FLAG(break_on_failure) = true;
1649 GTEST_FLAG(catch_exceptions) = true;
1650 GTEST_FLAG(color) = "no";
1651 GTEST_FLAG(death_test_use_fork) = true;
1652 GTEST_FLAG(fail_fast) = true;
1653 GTEST_FLAG(filter) = "abc";
1654 GTEST_FLAG(list_tests) = true;
1655 GTEST_FLAG(output) = "xml:foo.xml";
1656 GTEST_FLAG(brief) = true;
1657 GTEST_FLAG(print_time) = false;
1658 GTEST_FLAG(random_seed) = 1;
1659 GTEST_FLAG(repeat) = 100;
1660 GTEST_FLAG(shuffle) = true;
1661 GTEST_FLAG(stack_trace_depth) = 1;
1662 GTEST_FLAG(stream_result_to) = "localhost:1234";
1663 GTEST_FLAG(throw_on_failure) = true;
1667 // For saving Google Test flags during this test case.
1668 static GTestFlagSaver* saver_;
1671 GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;
1673 // Google Test doesn't guarantee the order of tests. The following two
1674 // tests are designed to work regardless of their order.
1676 // Modifies the Google Test flags in the test body.
1677 TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
1678 VerifyAndModifyFlags();
1681 // Verifies that the Google Test flags in the body of the previous test were
1682 // restored to their original values.
1683 TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
1684 VerifyAndModifyFlags();
1687 // Sets an environment variable with the given name to the given
1688 // value. If the value argument is "", unsets the environment
1689 // variable. The caller must ensure that both arguments are not NULL.
1690 static void SetEnv(const char* name, const char* value) {
1691 #if GTEST_OS_WINDOWS_MOBILE
1692 // Environment variables are not supported on Windows CE.
1694 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
1695 // C++Builder's putenv only stores a pointer to its parameter; we have to
1696 // ensure that the string remains valid as long as it might be needed.
1697 // We use an std::map to do so.
1698 static std::map<std::string, std::string*> added_env;
1700 // Because putenv stores a pointer to the string buffer, we can't delete the
1701 // previous string (if present) until after it's replaced.
1702 std::string *prev_env = NULL;
1703 if (added_env.find(name) != added_env.end()) {
1704 prev_env = added_env[name];
1706 added_env[name] = new std::string(
1707 (Message() << name << "=" << value).GetString());
1709 // The standard signature of putenv accepts a 'char*' argument. Other
1710 // implementations, like C++Builder's, accept a 'const char*'.
1711 // We cast away the 'const' since that would work for both variants.
1712 putenv(const_cast<char*>(added_env[name]->c_str()));
1714 #elif GTEST_OS_WINDOWS // If we are on Windows proper.
1715 _putenv((Message() << name << "=" << value).GetString().c_str());
1717 if (*value == '\0') {
1720 setenv(name, value, 1);
1722 #endif // GTEST_OS_WINDOWS_MOBILE
1725 #if !GTEST_OS_WINDOWS_MOBILE
1726 // Environment variables are not supported on Windows CE.
1728 using testing::internal::Int32FromGTestEnv;
1730 // Tests Int32FromGTestEnv().
1732 // Tests that Int32FromGTestEnv() returns the default value when the
1733 // environment variable is not set.
1734 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1735 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1736 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1739 # if !defined(GTEST_GET_INT32_FROM_ENV_)
1741 // Tests that Int32FromGTestEnv() returns the default value when the
1742 // environment variable overflows as an Int32.
1743 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1744 printf("(expecting 2 warnings)\n");
1746 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1747 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1749 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1750 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1753 // Tests that Int32FromGTestEnv() returns the default value when the
1754 // environment variable does not represent a valid decimal integer.
1755 TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1756 printf("(expecting 2 warnings)\n");
1758 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1759 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1761 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1762 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1765 # endif // !defined(GTEST_GET_INT32_FROM_ENV_)
1767 // Tests that Int32FromGTestEnv() parses and returns the value of the
1768 // environment variable when it represents a valid decimal integer in
1769 // the range of an Int32.
1770 TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1771 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1772 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1774 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1775 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1777 #endif // !GTEST_OS_WINDOWS_MOBILE
1779 // Tests ParseInt32Flag().
1781 // Tests that ParseInt32Flag() returns false and doesn't change the
1782 // output value when the flag has wrong format
1783 TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1784 int32_t value = 123;
1785 EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
1786 EXPECT_EQ(123, value);
1788 EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
1789 EXPECT_EQ(123, value);
1792 // Tests that ParseInt32Flag() returns false and doesn't change the
1793 // output value when the flag overflows as an Int32.
1794 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1795 printf("(expecting 2 warnings)\n");
1797 int32_t value = 123;
1798 EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
1799 EXPECT_EQ(123, value);
1801 EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
1802 EXPECT_EQ(123, value);
1805 // Tests that ParseInt32Flag() returns false and doesn't change the
1806 // output value when the flag does not represent a valid decimal
1808 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1809 printf("(expecting 2 warnings)\n");
1811 int32_t value = 123;
1812 EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
1813 EXPECT_EQ(123, value);
1815 EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
1816 EXPECT_EQ(123, value);
1819 // Tests that ParseInt32Flag() parses the value of the flag and
1820 // returns true when the flag represents a valid decimal integer in
1821 // the range of an Int32.
1822 TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1823 int32_t value = 123;
1824 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1825 EXPECT_EQ(456, value);
1827 EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
1829 EXPECT_EQ(-789, value);
1832 // Tests that Int32FromEnvOrDie() parses the value of the var or
1833 // returns the correct default.
1834 // Environment variables are not supported on Windows CE.
1835 #if !GTEST_OS_WINDOWS_MOBILE
1836 TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1837 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1838 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1839 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1840 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1841 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1843 #endif // !GTEST_OS_WINDOWS_MOBILE
1845 // Tests that Int32FromEnvOrDie() aborts with an error message
1846 // if the variable is not an int32_t.
1847 TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1848 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1849 EXPECT_DEATH_IF_SUPPORTED(
1850 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1854 // Tests that Int32FromEnvOrDie() aborts with an error message
1855 // if the variable cannot be represented by an int32_t.
1856 TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1857 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1858 EXPECT_DEATH_IF_SUPPORTED(
1859 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
1863 // Tests that ShouldRunTestOnShard() selects all tests
1864 // where there is 1 shard.
1865 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1866 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1867 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1868 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1869 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1870 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1873 class ShouldShardTest : public testing::Test {
1875 void SetUp() override {
1876 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1877 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1880 void TearDown() override {
1881 SetEnv(index_var_, "");
1882 SetEnv(total_var_, "");
1885 const char* index_var_;
1886 const char* total_var_;
1889 // Tests that sharding is disabled if neither of the environment variables
1891 TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1892 SetEnv(index_var_, "");
1893 SetEnv(total_var_, "");
1895 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1896 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1899 // Tests that sharding is not enabled if total_shards == 1.
1900 TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1901 SetEnv(index_var_, "0");
1902 SetEnv(total_var_, "1");
1903 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1904 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1907 // Tests that sharding is enabled if total_shards > 1 and
1908 // we are not in a death test subprocess.
1909 // Environment variables are not supported on Windows CE.
1910 #if !GTEST_OS_WINDOWS_MOBILE
1911 TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1912 SetEnv(index_var_, "4");
1913 SetEnv(total_var_, "22");
1914 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1915 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1917 SetEnv(index_var_, "8");
1918 SetEnv(total_var_, "9");
1919 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1920 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1922 SetEnv(index_var_, "0");
1923 SetEnv(total_var_, "9");
1924 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1925 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1927 #endif // !GTEST_OS_WINDOWS_MOBILE
1929 // Tests that we exit in error if the sharding values are not valid.
1931 typedef ShouldShardTest ShouldShardDeathTest;
1933 TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
1934 SetEnv(index_var_, "4");
1935 SetEnv(total_var_, "4");
1936 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1938 SetEnv(index_var_, "4");
1939 SetEnv(total_var_, "-2");
1940 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1942 SetEnv(index_var_, "5");
1943 SetEnv(total_var_, "");
1944 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1946 SetEnv(index_var_, "");
1947 SetEnv(total_var_, "5");
1948 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1951 // Tests that ShouldRunTestOnShard is a partition when 5
1953 TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1954 // Choose an arbitrary number of tests and shards.
1955 const int num_tests = 17;
1956 const int num_shards = 5;
1958 // Check partitioning: each test should be on exactly 1 shard.
1959 for (int test_id = 0; test_id < num_tests; test_id++) {
1960 int prev_selected_shard_index = -1;
1961 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1962 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1963 if (prev_selected_shard_index < 0) {
1964 prev_selected_shard_index = shard_index;
1966 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1967 << shard_index << " are both selected to run test " << test_id;
1973 // Check balance: This is not required by the sharding protocol, but is a
1974 // desirable property for performance.
1975 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1976 int num_tests_on_shard = 0;
1977 for (int test_id = 0; test_id < num_tests; test_id++) {
1978 num_tests_on_shard +=
1979 ShouldRunTestOnShard(num_shards, shard_index, test_id);
1981 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1985 // For the same reason we are not explicitly testing everything in the
1986 // Test class, there are no separate tests for the following classes
1987 // (except for some trivial cases):
1989 // TestSuite, UnitTest, UnitTestResultPrinter.
1991 // Similarly, there are no separate tests for the following macros:
1993 // TEST, TEST_F, RUN_ALL_TESTS
1995 TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1996 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr);
1997 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
2000 TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
2001 EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
2002 EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
2005 // When a property using a reserved key is supplied to this function, it
2006 // tests that a non-fatal failure is added, a fatal failure is not added,
2007 // and that the property is not recorded.
2008 void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2009 const TestResult& test_result, const char* key) {
2010 EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
2011 ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
2012 << "' recorded unexpectedly.";
2015 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2017 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
2018 ASSERT_TRUE(test_info != nullptr);
2019 ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
2023 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2025 const testing::TestSuite* test_suite =
2026 UnitTest::GetInstance()->current_test_suite();
2027 ASSERT_TRUE(test_suite != nullptr);
2028 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2029 test_suite->ad_hoc_test_result(), key);
2032 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2034 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2035 UnitTest::GetInstance()->ad_hoc_test_result(), key);
2038 // Tests that property recording functions in UnitTest outside of tests
2039 // functions correcly. Creating a separate instance of UnitTest ensures it
2040 // is in a state similar to the UnitTest's singleton's between tests.
2041 class UnitTestRecordPropertyTest :
2042 public testing::internal::UnitTestRecordPropertyTestHelper {
2044 static void SetUpTestSuite() {
2045 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2047 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2049 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2051 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2053 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2055 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2058 Test::RecordProperty("test_case_key_1", "1");
2060 const testing::TestSuite* test_suite =
2061 UnitTest::GetInstance()->current_test_suite();
2063 ASSERT_TRUE(test_suite != nullptr);
2065 ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count());
2066 EXPECT_STREQ("test_case_key_1",
2067 test_suite->ad_hoc_test_result().GetTestProperty(0).key());
2069 test_suite->ad_hoc_test_result().GetTestProperty(0).value());
2073 // Tests TestResult has the expected property when added.
2074 TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
2075 UnitTestRecordProperty("key_1", "1");
2077 ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
2079 EXPECT_STREQ("key_1",
2080 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2082 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2085 // Tests TestResult has multiple properties when added.
2086 TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
2087 UnitTestRecordProperty("key_1", "1");
2088 UnitTestRecordProperty("key_2", "2");
2090 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2092 EXPECT_STREQ("key_1",
2093 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2094 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2096 EXPECT_STREQ("key_2",
2097 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2098 EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2101 // Tests TestResult::RecordProperty() overrides values for duplicate keys.
2102 TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
2103 UnitTestRecordProperty("key_1", "1");
2104 UnitTestRecordProperty("key_2", "2");
2105 UnitTestRecordProperty("key_1", "12");
2106 UnitTestRecordProperty("key_2", "22");
2108 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2110 EXPECT_STREQ("key_1",
2111 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2113 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2115 EXPECT_STREQ("key_2",
2116 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2118 unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2121 TEST_F(UnitTestRecordPropertyTest,
2122 AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
2123 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2125 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2127 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2129 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2131 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2133 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2137 TEST_F(UnitTestRecordPropertyTest,
2138 AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
2139 EXPECT_NONFATAL_FAILURE(
2140 Test::RecordProperty("name", "1"),
2141 "'classname', 'name', 'status', 'time', 'type_param', 'value_param',"
2142 " 'file', and 'line' are reserved");
2145 class UnitTestRecordPropertyTestEnvironment : public Environment {
2147 void TearDown() override {
2148 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2150 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2152 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2154 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2156 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2158 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2160 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2162 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2167 // This will test property recording outside of any test or test case.
2168 static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ =
2169 AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
2171 // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2172 // of various arities. They do not attempt to be exhaustive. Rather,
2173 // view them as smoke tests that can be easily reviewed and verified.
2174 // A more complete set of tests for predicate assertions can be found
2175 // in gtest_pred_impl_unittest.cc.
2177 // First, some predicates and predicate-formatters needed by the tests.
2179 // Returns true if and only if the argument is an even number.
2180 bool IsEven(int n) {
2181 return (n % 2) == 0;
2184 // A functor that returns true if and only if the argument is an even number.
2185 struct IsEvenFunctor {
2186 bool operator()(int n) { return IsEven(n); }
2189 // A predicate-formatter function that asserts the argument is an even
2191 AssertionResult AssertIsEven(const char* expr, int n) {
2193 return AssertionSuccess();
2197 msg << expr << " evaluates to " << n << ", which is not even.";
2198 return AssertionFailure(msg);
2201 // A predicate function that returns AssertionResult for use in
2202 // EXPECT/ASSERT_TRUE/FALSE.
2203 AssertionResult ResultIsEven(int n) {
2205 return AssertionSuccess() << n << " is even";
2207 return AssertionFailure() << n << " is odd";
2210 // A predicate function that returns AssertionResult but gives no
2211 // explanation why it succeeds. Needed for testing that
2212 // EXPECT/ASSERT_FALSE handles such functions correctly.
2213 AssertionResult ResultIsEvenNoExplanation(int n) {
2215 return AssertionSuccess();
2217 return AssertionFailure() << n << " is odd";
2220 // A predicate-formatter functor that asserts the argument is an even
2222 struct AssertIsEvenFunctor {
2223 AssertionResult operator()(const char* expr, int n) {
2224 return AssertIsEven(expr, n);
2228 // Returns true if and only if the sum of the arguments is an even number.
2229 bool SumIsEven2(int n1, int n2) {
2230 return IsEven(n1 + n2);
2233 // A functor that returns true if and only if the sum of the arguments is an
2235 struct SumIsEven3Functor {
2236 bool operator()(int n1, int n2, int n3) {
2237 return IsEven(n1 + n2 + n3);
2241 // A predicate-formatter function that asserts the sum of the
2242 // arguments is an even number.
2243 AssertionResult AssertSumIsEven4(
2244 const char* e1, const char* e2, const char* e3, const char* e4,
2245 int n1, int n2, int n3, int n4) {
2246 const int sum = n1 + n2 + n3 + n4;
2248 return AssertionSuccess();
2252 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
2253 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
2254 << ") evaluates to " << sum << ", which is not even.";
2255 return AssertionFailure(msg);
2258 // A predicate-formatter functor that asserts the sum of the arguments
2259 // is an even number.
2260 struct AssertSumIsEven5Functor {
2261 AssertionResult operator()(
2262 const char* e1, const char* e2, const char* e3, const char* e4,
2263 const char* e5, int n1, int n2, int n3, int n4, int n5) {
2264 const int sum = n1 + n2 + n3 + n4 + n5;
2266 return AssertionSuccess();
2270 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2272 << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
2273 << ") evaluates to " << sum << ", which is not even.";
2274 return AssertionFailure(msg);
2279 // Tests unary predicate assertions.
2281 // Tests unary predicate assertions that don't use a custom formatter.
2282 TEST(Pred1Test, WithoutFormat) {
2284 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2285 ASSERT_PRED1(IsEven, 4);
2288 EXPECT_NONFATAL_FAILURE({ // NOLINT
2289 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2290 }, "This failure is expected.");
2291 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
2292 "evaluates to false");
2295 // Tests unary predicate assertions that use a custom formatter.
2296 TEST(Pred1Test, WithFormat) {
2298 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2299 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2300 << "This failure is UNEXPECTED!";
2304 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2305 "n evaluates to 5, which is not even.");
2306 EXPECT_FATAL_FAILURE({ // NOLINT
2307 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2308 }, "This failure is expected.");
2311 // Tests that unary predicate assertions evaluates their arguments
2313 TEST(Pred1Test, SingleEvaluationOnFailure) {
2316 EXPECT_PRED1(IsEven, n++);
2317 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2320 EXPECT_FATAL_FAILURE({ // NOLINT
2321 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2322 << "This failure is expected.";
2323 }, "This failure is expected.");
2324 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2328 // Tests predicate assertions whose arity is >= 2.
2330 // Tests predicate assertions that don't use a custom formatter.
2331 TEST(PredTest, WithoutFormat) {
2333 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2334 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2339 EXPECT_NONFATAL_FAILURE({ // NOLINT
2340 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2341 }, "This failure is expected.");
2342 EXPECT_FATAL_FAILURE({ // NOLINT
2343 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2344 }, "evaluates to false");
2347 // Tests predicate assertions that use a custom formatter.
2348 TEST(PredTest, WithFormat) {
2350 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
2351 "This failure is UNEXPECTED!";
2352 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2359 EXPECT_NONFATAL_FAILURE({ // NOLINT
2360 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2361 }, "evaluates to 13, which is not even.");
2362 EXPECT_FATAL_FAILURE({ // NOLINT
2363 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2364 << "This failure is expected.";
2365 }, "This failure is expected.");
2368 // Tests that predicate assertions evaluates their arguments
2370 TEST(PredTest, SingleEvaluationOnFailure) {
2374 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2375 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2376 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2378 // Another success case.
2383 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
2384 n1++, n2++, n3++, n4++, n5++)
2385 << "This failure is UNEXPECTED!";
2386 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2387 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2388 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2389 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2390 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2394 EXPECT_NONFATAL_FAILURE({ // NOLINT
2395 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2396 << "This failure is expected.";
2397 }, "This failure is expected.");
2398 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2399 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2400 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2402 // Another failure case.
2403 n1 = n2 = n3 = n4 = 0;
2404 EXPECT_NONFATAL_FAILURE({ // NOLINT
2405 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2406 }, "evaluates to 1, which is not even.");
2407 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2408 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2409 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2410 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2413 // Test predicate assertions for sets
2414 TEST(PredTest, ExpectPredEvalFailure) {
2415 std::set<int> set_a = {2, 1, 3, 4, 5};
2416 std::set<int> set_b = {0, 4, 8};
2417 const auto compare_sets = [] (std::set<int>, std::set<int>) { return false; };
2418 EXPECT_NONFATAL_FAILURE(
2419 EXPECT_PRED2(compare_sets, set_a, set_b),
2420 "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates "
2421 "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }");
2424 // Some helper functions for testing using overloaded/template
2425 // functions with ASSERT_PREDn and EXPECT_PREDn.
2427 bool IsPositive(double x) {
2431 template <typename T>
2432 bool IsNegative(T x) {
2436 template <typename T1, typename T2>
2437 bool GreaterThan(T1 x1, T2 x2) {
2441 // Tests that overloaded functions can be used in *_PRED* as long as
2442 // their types are explicitly specified.
2443 TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2444 // C++Builder requires C-style casts rather than static_cast.
2445 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2446 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
2449 // Tests that template functions can be used in *_PRED* as long as
2450 // their types are explicitly specified.
2451 TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2452 EXPECT_PRED1(IsNegative<int>, -5);
2453 // Makes sure that we can handle templates with more than one
2455 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2459 // Some helper functions for testing using overloaded/template
2460 // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2462 AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2463 return n > 0 ? AssertionSuccess() :
2464 AssertionFailure(Message() << "Failure");
2467 AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2468 return x > 0 ? AssertionSuccess() :
2469 AssertionFailure(Message() << "Failure");
2472 template <typename T>
2473 AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2474 return x < 0 ? AssertionSuccess() :
2475 AssertionFailure(Message() << "Failure");
2478 template <typename T1, typename T2>
2479 AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2480 const T1& x1, const T2& x2) {
2481 return x1 == x2 ? AssertionSuccess() :
2482 AssertionFailure(Message() << "Failure");
2485 // Tests that overloaded functions can be used in *_PRED_FORMAT*
2486 // without explicitly specifying their types.
2487 TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2488 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2489 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2492 // Tests that template functions can be used in *_PRED_FORMAT* without
2493 // explicitly specifying their types.
2494 TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2495 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2496 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2500 // Tests string assertions.
2502 // Tests ASSERT_STREQ with non-NULL arguments.
2503 TEST(StringAssertionTest, ASSERT_STREQ) {
2504 const char * const p1 = "good";
2505 ASSERT_STREQ(p1, p1);
2507 // Let p2 have the same content as p1, but be at a different address.
2508 const char p2[] = "good";
2509 ASSERT_STREQ(p1, p2);
2511 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
2512 " \"bad\"\n \"good\"");
2515 // Tests ASSERT_STREQ with NULL arguments.
2516 TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2517 ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr);
2518 EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null");
2521 // Tests ASSERT_STREQ with NULL arguments.
2522 TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2523 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null");
2526 // Tests ASSERT_STRNE.
2527 TEST(StringAssertionTest, ASSERT_STRNE) {
2528 ASSERT_STRNE("hi", "Hi");
2529 ASSERT_STRNE("Hi", nullptr);
2530 ASSERT_STRNE(nullptr, "Hi");
2531 ASSERT_STRNE("", nullptr);
2532 ASSERT_STRNE(nullptr, "");
2533 ASSERT_STRNE("", "Hi");
2534 ASSERT_STRNE("Hi", "");
2535 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
2536 "\"Hi\" vs \"Hi\"");
2539 // Tests ASSERT_STRCASEEQ.
2540 TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2541 ASSERT_STRCASEEQ("hi", "Hi");
2542 ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);
2544 ASSERT_STRCASEEQ("", "");
2545 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
2549 // Tests ASSERT_STRCASENE.
2550 TEST(StringAssertionTest, ASSERT_STRCASENE) {
2551 ASSERT_STRCASENE("hi1", "Hi2");
2552 ASSERT_STRCASENE("Hi", nullptr);
2553 ASSERT_STRCASENE(nullptr, "Hi");
2554 ASSERT_STRCASENE("", nullptr);
2555 ASSERT_STRCASENE(nullptr, "");
2556 ASSERT_STRCASENE("", "Hi");
2557 ASSERT_STRCASENE("Hi", "");
2558 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
2562 // Tests *_STREQ on wide strings.
2563 TEST(StringAssertionTest, STREQ_Wide) {
2565 ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr);
2568 ASSERT_STREQ(L"", L"");
2570 // Non-null vs NULL.
2571 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null");
2574 EXPECT_STREQ(L"Hi", L"Hi");
2577 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
2580 // Strings containing wide characters.
2581 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
2584 // The streaming variation.
2585 EXPECT_NONFATAL_FAILURE({ // NOLINT
2586 EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
2587 }, "Expected failure");
2590 // Tests *_STRNE on wide strings.
2591 TEST(StringAssertionTest, STRNE_Wide) {
2593 EXPECT_NONFATAL_FAILURE(
2595 EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr);
2600 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
2603 // Non-null vs NULL.
2604 ASSERT_STRNE(L"non-null", nullptr);
2607 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
2611 EXPECT_STRNE(L"abc", L"Abc");
2613 // Strings containing wide characters.
2614 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
2617 // The streaming variation.
2618 ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
2621 // Tests for ::testing::IsSubstring().
2623 // Tests that IsSubstring() returns the correct result when the input
2624 // argument type is const char*.
2625 TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2626 EXPECT_FALSE(IsSubstring("", "", nullptr, "a"));
2627 EXPECT_FALSE(IsSubstring("", "", "b", nullptr));
2628 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2630 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr));
2631 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2634 // Tests that IsSubstring() returns the correct result when the input
2635 // argument type is const wchar_t*.
2636 TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2637 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2638 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
2639 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2642 IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr));
2643 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2646 // Tests that IsSubstring() generates the correct message when the input
2647 // argument type is const char*.
2648 TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2649 EXPECT_STREQ("Value of: needle_expr\n"
2650 " Actual: \"needle\"\n"
2651 "Expected: a substring of haystack_expr\n"
2652 "Which is: \"haystack\"",
2653 IsSubstring("needle_expr", "haystack_expr",
2654 "needle", "haystack").failure_message());
2657 // Tests that IsSubstring returns the correct result when the input
2658 // argument type is ::std::string.
2659 TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2660 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2661 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2664 #if GTEST_HAS_STD_WSTRING
2665 // Tests that IsSubstring returns the correct result when the input
2666 // argument type is ::std::wstring.
2667 TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2668 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2669 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2672 // Tests that IsSubstring() generates the correct message when the input
2673 // argument type is ::std::wstring.
2674 TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2675 EXPECT_STREQ("Value of: needle_expr\n"
2676 " Actual: L\"needle\"\n"
2677 "Expected: a substring of haystack_expr\n"
2678 "Which is: L\"haystack\"",
2680 "needle_expr", "haystack_expr",
2681 ::std::wstring(L"needle"), L"haystack").failure_message());
2684 #endif // GTEST_HAS_STD_WSTRING
2686 // Tests for ::testing::IsNotSubstring().
2688 // Tests that IsNotSubstring() returns the correct result when the input
2689 // argument type is const char*.
2690 TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2691 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2692 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2695 // Tests that IsNotSubstring() returns the correct result when the input
2696 // argument type is const wchar_t*.
2697 TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2698 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2699 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2702 // Tests that IsNotSubstring() generates the correct message when the input
2703 // argument type is const wchar_t*.
2704 TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2705 EXPECT_STREQ("Value of: needle_expr\n"
2706 " Actual: L\"needle\"\n"
2707 "Expected: not a substring of haystack_expr\n"
2708 "Which is: L\"two needles\"",
2710 "needle_expr", "haystack_expr",
2711 L"needle", L"two needles").failure_message());
2714 // Tests that IsNotSubstring returns the correct result when the input
2715 // argument type is ::std::string.
2716 TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2717 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2718 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2721 // Tests that IsNotSubstring() generates the correct message when the input
2722 // argument type is ::std::string.
2723 TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2724 EXPECT_STREQ("Value of: needle_expr\n"
2725 " Actual: \"needle\"\n"
2726 "Expected: not a substring of haystack_expr\n"
2727 "Which is: \"two needles\"",
2729 "needle_expr", "haystack_expr",
2730 ::std::string("needle"), "two needles").failure_message());
2733 #if GTEST_HAS_STD_WSTRING
2735 // Tests that IsNotSubstring returns the correct result when the input
2736 // argument type is ::std::wstring.
2737 TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2739 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2740 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2743 #endif // GTEST_HAS_STD_WSTRING
2745 // Tests floating-point assertions.
2747 template <typename RawType>
2748 class FloatingPointTest : public Test {
2750 // Pre-calculated numbers to be used by the tests.
2752 RawType close_to_positive_zero;
2753 RawType close_to_negative_zero;
2754 RawType further_from_negative_zero;
2756 RawType close_to_one;
2757 RawType further_from_one;
2760 RawType close_to_infinity;
2761 RawType further_from_infinity;
2767 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2768 typedef typename Floating::Bits Bits;
2770 void SetUp() override {
2771 const uint32_t max_ulps = Floating::kMaxUlps;
2773 // The bits that represent 0.0.
2774 const Bits zero_bits = Floating(0).bits();
2776 // Makes some numbers close to 0.0.
2777 values_.close_to_positive_zero = Floating::ReinterpretBits(
2778 zero_bits + max_ulps/2);
2779 values_.close_to_negative_zero = -Floating::ReinterpretBits(
2780 zero_bits + max_ulps - max_ulps/2);
2781 values_.further_from_negative_zero = -Floating::ReinterpretBits(
2782 zero_bits + max_ulps + 1 - max_ulps/2);
2784 // The bits that represent 1.0.
2785 const Bits one_bits = Floating(1).bits();
2787 // Makes some numbers close to 1.0.
2788 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2789 values_.further_from_one = Floating::ReinterpretBits(
2790 one_bits + max_ulps + 1);
2793 values_.infinity = Floating::Infinity();
2795 // The bits that represent +infinity.
2796 const Bits infinity_bits = Floating(values_.infinity).bits();
2798 // Makes some numbers close to infinity.
2799 values_.close_to_infinity = Floating::ReinterpretBits(
2800 infinity_bits - max_ulps);
2801 values_.further_from_infinity = Floating::ReinterpretBits(
2802 infinity_bits - max_ulps - 1);
2804 // Makes some NAN's. Sets the most significant bit of the fraction so that
2805 // our NaN's are quiet; trying to process a signaling NaN would raise an
2806 // exception if our environment enables floating point exceptions.
2807 values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
2808 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2809 values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
2810 | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
2814 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2817 static TestValues values_;
2820 template <typename RawType>
2821 typename FloatingPointTest<RawType>::TestValues
2822 FloatingPointTest<RawType>::values_;
2824 // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2825 typedef FloatingPointTest<float> FloatTest;
2827 // Tests that the size of Float::Bits matches the size of float.
2828 TEST_F(FloatTest, Size) {
2832 // Tests comparing with +0 and -0.
2833 TEST_F(FloatTest, Zeros) {
2834 EXPECT_FLOAT_EQ(0.0, -0.0);
2835 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
2837 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
2841 // Tests comparing numbers close to 0.
2843 // This ensures that *_FLOAT_EQ handles the sign correctly and no
2844 // overflow occurs when comparing numbers whose absolute value is very
2846 TEST_F(FloatTest, AlmostZeros) {
2847 // In C++Builder, names within local classes (such as used by
2848 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2849 // scoping class. Use a static local alias as a workaround.
2850 // We use the assignment syntax since some compilers, like Sun Studio,
2851 // don't allow initializing references using construction syntax
2853 static const FloatTest::TestValues& v = this->values_;
2855 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2856 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2857 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2859 EXPECT_FATAL_FAILURE({ // NOLINT
2860 ASSERT_FLOAT_EQ(v.close_to_positive_zero,
2861 v.further_from_negative_zero);
2862 }, "v.further_from_negative_zero");
2865 // Tests comparing numbers close to each other.
2866 TEST_F(FloatTest, SmallDiff) {
2867 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2868 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2869 "values_.further_from_one");
2872 // Tests comparing numbers far apart.
2873 TEST_F(FloatTest, LargeDiff) {
2874 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
2878 // Tests comparing with infinity.
2880 // This ensures that no overflow occurs when comparing numbers whose
2881 // absolute value is very large.
2882 TEST_F(FloatTest, Infinity) {
2883 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2884 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
2885 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2886 "-values_.infinity");
2888 // This is interesting as the representations of infinity and nan1
2889 // are only 1 DLP apart.
2890 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2894 // Tests that comparing with NAN always returns false.
2895 TEST_F(FloatTest, NaN) {
2896 // In C++Builder, names within local classes (such as used by
2897 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2898 // scoping class. Use a static local alias as a workaround.
2899 // We use the assignment syntax since some compilers, like Sun Studio,
2900 // don't allow initializing references using construction syntax
2902 static const FloatTest::TestValues& v = this->values_;
2904 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
2906 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
2908 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
2911 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
2915 // Tests that *_FLOAT_EQ are reflexive.
2916 TEST_F(FloatTest, Reflexive) {
2917 EXPECT_FLOAT_EQ(0.0, 0.0);
2918 EXPECT_FLOAT_EQ(1.0, 1.0);
2919 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
2922 // Tests that *_FLOAT_EQ are commutative.
2923 TEST_F(FloatTest, Commutative) {
2924 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2925 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2927 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2928 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2932 // Tests EXPECT_NEAR.
2933 TEST_F(FloatTest, EXPECT_NEAR) {
2934 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2935 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2936 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
2937 "The difference between 1.0f and 1.5f is 0.5, "
2938 "which exceeds 0.25f");
2941 // Tests ASSERT_NEAR.
2942 TEST_F(FloatTest, ASSERT_NEAR) {
2943 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2944 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2945 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
2946 "The difference between 1.0f and 1.5f is 0.5, "
2947 "which exceeds 0.25f");
2950 // Tests the cases where FloatLE() should succeed.
2951 TEST_F(FloatTest, FloatLESucceeds) {
2952 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2953 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
2955 // or when val1 is greater than, but almost equals to, val2.
2956 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2959 // Tests the cases where FloatLE() should fail.
2960 TEST_F(FloatTest, FloatLEFails) {
2961 // When val1 is greater than val2 by a large margin,
2962 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2963 "(2.0f) <= (1.0f)");
2965 // or by a small yet non-negligible margin,
2966 EXPECT_NONFATAL_FAILURE({ // NOLINT
2967 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2968 }, "(values_.further_from_one) <= (1.0f)");
2970 EXPECT_NONFATAL_FAILURE({ // NOLINT
2971 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2972 }, "(values_.nan1) <= (values_.infinity)");
2973 EXPECT_NONFATAL_FAILURE({ // NOLINT
2974 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2975 }, "(-values_.infinity) <= (values_.nan1)");
2976 EXPECT_FATAL_FAILURE({ // NOLINT
2977 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2978 }, "(values_.nan1) <= (values_.nan1)");
2981 // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2982 typedef FloatingPointTest<double> DoubleTest;
2984 // Tests that the size of Double::Bits matches the size of double.
2985 TEST_F(DoubleTest, Size) {
2989 // Tests comparing with +0 and -0.
2990 TEST_F(DoubleTest, Zeros) {
2991 EXPECT_DOUBLE_EQ(0.0, -0.0);
2992 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
2994 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
2998 // Tests comparing numbers close to 0.
3000 // This ensures that *_DOUBLE_EQ handles the sign correctly and no
3001 // overflow occurs when comparing numbers whose absolute value is very
3003 TEST_F(DoubleTest, AlmostZeros) {
3004 // In C++Builder, names within local classes (such as used by
3005 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
3006 // scoping class. Use a static local alias as a workaround.
3007 // We use the assignment syntax since some compilers, like Sun Studio,
3008 // don't allow initializing references using construction syntax
3010 static const DoubleTest::TestValues& v = this->values_;
3012 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
3013 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
3014 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
3016 EXPECT_FATAL_FAILURE({ // NOLINT
3017 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
3018 v.further_from_negative_zero);
3019 }, "v.further_from_negative_zero");
3022 // Tests comparing numbers close to each other.
3023 TEST_F(DoubleTest, SmallDiff) {
3024 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
3025 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
3026 "values_.further_from_one");
3029 // Tests comparing numbers far apart.
3030 TEST_F(DoubleTest, LargeDiff) {
3031 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
3035 // Tests comparing with infinity.
3037 // This ensures that no overflow occurs when comparing numbers whose
3038 // absolute value is very large.
3039 TEST_F(DoubleTest, Infinity) {
3040 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
3041 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
3042 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
3043 "-values_.infinity");
3045 // This is interesting as the representations of infinity_ and nan1_
3046 // are only 1 DLP apart.
3047 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
3051 // Tests that comparing with NAN always returns false.
3052 TEST_F(DoubleTest, NaN) {
3053 static const DoubleTest::TestValues& v = this->values_;
3055 // Nokia's STLport crashes if we try to output infinity or NaN.
3056 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
3058 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
3059 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3060 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
3064 // Tests that *_DOUBLE_EQ are reflexive.
3065 TEST_F(DoubleTest, Reflexive) {
3066 EXPECT_DOUBLE_EQ(0.0, 0.0);
3067 EXPECT_DOUBLE_EQ(1.0, 1.0);
3068 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
3071 // Tests that *_DOUBLE_EQ are commutative.
3072 TEST_F(DoubleTest, Commutative) {
3073 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3074 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
3076 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3077 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3081 // Tests EXPECT_NEAR.
3082 TEST_F(DoubleTest, EXPECT_NEAR) {
3083 EXPECT_NEAR(-1.0, -1.1, 0.2);
3084 EXPECT_NEAR(2.0, 3.0, 1.0);
3085 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3086 "The difference between 1.0 and 1.5 is 0.5, "
3087 "which exceeds 0.25");
3088 // At this magnitude adjacent doubles are 512.0 apart, so this triggers a
3089 // slightly different failure reporting path.
3090 EXPECT_NONFATAL_FAILURE(
3091 EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),
3092 "The abs_error parameter 1.0 evaluates to 1 which is smaller than the "
3093 "minimum distance between doubles for numbers of this magnitude which is "
3097 // Tests ASSERT_NEAR.
3098 TEST_F(DoubleTest, ASSERT_NEAR) {
3099 ASSERT_NEAR(-1.0, -1.1, 0.2);
3100 ASSERT_NEAR(2.0, 3.0, 1.0);
3101 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3102 "The difference between 1.0 and 1.5 is 0.5, "
3103 "which exceeds 0.25");
3106 // Tests the cases where DoubleLE() should succeed.
3107 TEST_F(DoubleTest, DoubleLESucceeds) {
3108 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3109 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
3111 // or when val1 is greater than, but almost equals to, val2.
3112 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3115 // Tests the cases where DoubleLE() should fail.
3116 TEST_F(DoubleTest, DoubleLEFails) {
3117 // When val1 is greater than val2 by a large margin,
3118 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
3121 // or by a small yet non-negligible margin,
3122 EXPECT_NONFATAL_FAILURE({ // NOLINT
3123 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3124 }, "(values_.further_from_one) <= (1.0)");
3126 EXPECT_NONFATAL_FAILURE({ // NOLINT
3127 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3128 }, "(values_.nan1) <= (values_.infinity)");
3129 EXPECT_NONFATAL_FAILURE({ // NOLINT
3130 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3131 }, " (-values_.infinity) <= (values_.nan1)");
3132 EXPECT_FATAL_FAILURE({ // NOLINT
3133 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3134 }, "(values_.nan1) <= (values_.nan1)");
3138 // Verifies that a test or test case whose name starts with DISABLED_ is
3141 // A test whose name starts with DISABLED_.
3143 TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3144 FAIL() << "Unexpected failure: Disabled test should not be run.";
3147 // A test whose name does not start with DISABLED_.
3149 TEST(DisabledTest, NotDISABLED_TestShouldRun) {
3153 // A test case whose name starts with DISABLED_.
3155 TEST(DISABLED_TestSuite, TestShouldNotRun) {
3156 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3159 // A test case and test whose names start with DISABLED_.
3161 TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {
3162 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3165 // Check that when all tests in a test case are disabled, SetUpTestSuite() and
3166 // TearDownTestSuite() are not called.
3167 class DisabledTestsTest : public Test {
3169 static void SetUpTestSuite() {
3170 FAIL() << "Unexpected failure: All tests disabled in test case. "
3171 "SetUpTestSuite() should not be called.";
3174 static void TearDownTestSuite() {
3175 FAIL() << "Unexpected failure: All tests disabled in test case. "
3176 "TearDownTestSuite() should not be called.";
3180 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3181 FAIL() << "Unexpected failure: Disabled test should not be run.";
3184 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3185 FAIL() << "Unexpected failure: Disabled test should not be run.";
3188 // Tests that disabled typed tests aren't run.
3190 template <typename T>
3191 class TypedTest : public Test {
3194 typedef testing::Types<int, double> NumericTypes;
3195 TYPED_TEST_SUITE(TypedTest, NumericTypes);
3197 TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3198 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3201 template <typename T>
3202 class DISABLED_TypedTest : public Test {
3205 TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
3207 TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3208 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3211 // Tests that disabled type-parameterized tests aren't run.
3213 template <typename T>
3214 class TypedTestP : public Test {
3217 TYPED_TEST_SUITE_P(TypedTestP);
3219 TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3220 FAIL() << "Unexpected failure: "
3221 << "Disabled type-parameterized test should not run.";
3224 REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
3226 INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);
3228 template <typename T>
3229 class DISABLED_TypedTestP : public Test {
3232 TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
3234 TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3235 FAIL() << "Unexpected failure: "
3236 << "Disabled type-parameterized test should not run.";
3239 REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
3241 INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
3243 // Tests that assertion macros evaluate their arguments exactly once.
3245 class SingleEvaluationTest : public Test {
3246 public: // Must be public and not protected due to a bug in g++ 3.4.2.
3247 // This helper function is needed by the FailedASSERT_STREQ test
3248 // below. It's public to work around C++Builder's bug with scoping local
3250 static void CompareAndIncrementCharPtrs() {
3251 ASSERT_STREQ(p1_++, p2_++);
3254 // This helper function is needed by the FailedASSERT_NE test below. It's
3255 // public to work around C++Builder's bug with scoping local classes.
3256 static void CompareAndIncrementInts() {
3257 ASSERT_NE(a_++, b_++);
3261 SingleEvaluationTest() {
3268 static const char* const s1_;
3269 static const char* const s2_;
3270 static const char* p1_;
3271 static const char* p2_;
3277 const char* const SingleEvaluationTest::s1_ = "01234";
3278 const char* const SingleEvaluationTest::s2_ = "abcde";
3279 const char* SingleEvaluationTest::p1_;
3280 const char* SingleEvaluationTest::p2_;
3281 int SingleEvaluationTest::a_;
3282 int SingleEvaluationTest::b_;
3284 // Tests that when ASSERT_STREQ fails, it evaluates its arguments
3286 TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3287 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3289 EXPECT_EQ(s1_ + 1, p1_);
3290 EXPECT_EQ(s2_ + 1, p2_);
3293 // Tests that string assertion arguments are evaluated exactly once.
3294 TEST_F(SingleEvaluationTest, ASSERT_STR) {
3295 // successful EXPECT_STRNE
3296 EXPECT_STRNE(p1_++, p2_++);
3297 EXPECT_EQ(s1_ + 1, p1_);
3298 EXPECT_EQ(s2_ + 1, p2_);
3300 // failed EXPECT_STRCASEEQ
3301 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3303 EXPECT_EQ(s1_ + 2, p1_);
3304 EXPECT_EQ(s2_ + 2, p2_);
3307 // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3309 TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3310 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3311 "(a_++) != (b_++)");
3316 // Tests that assertion arguments are evaluated exactly once.
3317 TEST_F(SingleEvaluationTest, OtherCases) {
3318 // successful EXPECT_TRUE
3319 EXPECT_TRUE(0 == a_++); // NOLINT
3322 // failed EXPECT_TRUE
3323 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3326 // successful EXPECT_GT
3327 EXPECT_GT(a_++, b_++);
3332 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3336 // successful ASSERT_TRUE
3337 ASSERT_TRUE(0 < a_++); // NOLINT
3340 // successful ASSERT_GT
3341 ASSERT_GT(a_++, b_++);
3346 #if GTEST_HAS_EXCEPTIONS
3351 #define ERROR_DESC "class std::runtime_error"
3353 #define ERROR_DESC "std::runtime_error"
3356 #else // GTEST_HAS_RTTI
3358 #define ERROR_DESC "an std::exception-derived error"
3360 #endif // GTEST_HAS_RTTI
3362 void ThrowAnInteger() {
3365 void ThrowRuntimeError(const char* what) {
3366 throw std::runtime_error(what);
3369 // Tests that assertion arguments are evaluated exactly once.
3370 TEST_F(SingleEvaluationTest, ExceptionTests) {
3371 // successful EXPECT_THROW
3372 EXPECT_THROW({ // NOLINT
3378 // failed EXPECT_THROW, throws different
3379 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3382 }, bool), "throws a different type");
3385 // failed EXPECT_THROW, throws runtime error
3386 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3388 ThrowRuntimeError("A description");
3389 }, bool), "throws " ERROR_DESC " with description \"A description\"");
3392 // failed EXPECT_THROW, throws nothing
3393 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3396 // successful EXPECT_NO_THROW
3397 EXPECT_NO_THROW(a_++);
3400 // failed EXPECT_NO_THROW
3401 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3407 // successful EXPECT_ANY_THROW
3408 EXPECT_ANY_THROW({ // NOLINT
3414 // failed EXPECT_ANY_THROW
3415 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3419 #endif // GTEST_HAS_EXCEPTIONS
3421 // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3422 class NoFatalFailureTest : public Test {
3425 void FailsNonFatal() {
3426 ADD_FAILURE() << "some non-fatal failure";
3429 FAIL() << "some fatal failure";
3432 void DoAssertNoFatalFailureOnFails() {
3433 ASSERT_NO_FATAL_FAILURE(Fails());
3434 ADD_FAILURE() << "should not reach here.";
3437 void DoExpectNoFatalFailureOnFails() {
3438 EXPECT_NO_FATAL_FAILURE(Fails());
3439 ADD_FAILURE() << "other failure";
3443 TEST_F(NoFatalFailureTest, NoFailure) {
3444 EXPECT_NO_FATAL_FAILURE(Succeeds());
3445 ASSERT_NO_FATAL_FAILURE(Succeeds());
3448 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3449 EXPECT_NONFATAL_FAILURE(
3450 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3451 "some non-fatal failure");
3452 EXPECT_NONFATAL_FAILURE(
3453 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3454 "some non-fatal failure");
3457 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3458 TestPartResultArray gtest_failures;
3460 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3461 DoAssertNoFatalFailureOnFails();
3463 ASSERT_EQ(2, gtest_failures.size());
3464 EXPECT_EQ(TestPartResult::kFatalFailure,
3465 gtest_failures.GetTestPartResult(0).type());
3466 EXPECT_EQ(TestPartResult::kFatalFailure,
3467 gtest_failures.GetTestPartResult(1).type());
3468 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3469 gtest_failures.GetTestPartResult(0).message());
3470 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3471 gtest_failures.GetTestPartResult(1).message());
3474 TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3475 TestPartResultArray gtest_failures;
3477 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3478 DoExpectNoFatalFailureOnFails();
3480 ASSERT_EQ(3, gtest_failures.size());
3481 EXPECT_EQ(TestPartResult::kFatalFailure,
3482 gtest_failures.GetTestPartResult(0).type());
3483 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3484 gtest_failures.GetTestPartResult(1).type());
3485 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3486 gtest_failures.GetTestPartResult(2).type());
3487 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3488 gtest_failures.GetTestPartResult(0).message());
3489 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3490 gtest_failures.GetTestPartResult(1).message());
3491 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3492 gtest_failures.GetTestPartResult(2).message());
3495 TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3496 TestPartResultArray gtest_failures;
3498 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3499 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3501 ASSERT_EQ(2, gtest_failures.size());
3502 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3503 gtest_failures.GetTestPartResult(0).type());
3504 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3505 gtest_failures.GetTestPartResult(1).type());
3506 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3507 gtest_failures.GetTestPartResult(0).message());
3508 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3509 gtest_failures.GetTestPartResult(1).message());
3512 // Tests non-string assertions.
3514 std::string EditsToString(const std::vector<EditType>& edits) {
3516 for (size_t i = 0; i < edits.size(); ++i) {
3517 static const char kEdits[] = " +-/";
3518 out.append(1, kEdits[edits[i]]);
3523 std::vector<size_t> CharsToIndices(const std::string& str) {
3524 std::vector<size_t> out;
3525 for (size_t i = 0; i < str.size(); ++i) {
3526 out.push_back(static_cast<size_t>(str[i]));
3531 std::vector<std::string> CharsToLines(const std::string& str) {
3532 std::vector<std::string> out;
3533 for (size_t i = 0; i < str.size(); ++i) {
3534 out.push_back(str.substr(i, 1));
3539 TEST(EditDistance, TestSuites) {
3544 const char* expected_edits;
3545 const char* expected_diff;
3547 static const Case kCases[] = {
3549 {__LINE__, "A", "A", " ", ""},
3550 {__LINE__, "ABCDE", "ABCDE", " ", ""},
3552 {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
3553 {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
3555 {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
3556 {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
3558 {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
3559 {__LINE__, "ABCD", "abcd", "////",
3560 "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
3562 {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
3563 "@@ -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"},
3564 {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
3565 "@@ -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"},
3566 {__LINE__, "ABCDE", "BCDCD", "- +/",
3567 "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
3568 {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
3569 "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
3570 "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
3572 for (const Case* c = kCases; c->left; ++c) {
3573 EXPECT_TRUE(c->expected_edits ==
3574 EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3575 CharsToIndices(c->right))))
3576 << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
3577 << EditsToString(CalculateOptimalEdits(
3578 CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
3579 EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
3580 CharsToLines(c->right)))
3581 << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
3582 << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
3587 // Tests EqFailure(), used for implementing *EQ* assertions.
3588 TEST(AssertionTest, EqFailure) {
3589 const std::string foo_val("5"), bar_val("6");
3590 const std::string msg1(
3591 EqFailure("foo", "bar", foo_val, bar_val, false)
3592 .failure_message());
3594 "Expected equality of these values:\n"
3601 const std::string msg2(
3602 EqFailure("foo", "6", foo_val, bar_val, false)
3603 .failure_message());
3605 "Expected equality of these values:\n"
3611 const std::string msg3(
3612 EqFailure("5", "bar", foo_val, bar_val, false)
3613 .failure_message());
3615 "Expected equality of these values:\n"
3621 const std::string msg4(
3622 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3624 "Expected equality of these values:\n"
3629 const std::string msg5(
3630 EqFailure("foo", "bar",
3631 std::string("\"x\""), std::string("\"y\""),
3632 true).failure_message());
3634 "Expected equality of these values:\n"
3636 " Which is: \"x\"\n"
3638 " Which is: \"y\"\n"
3643 TEST(AssertionTest, EqFailureWithDiff) {
3644 const std::string left(
3645 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
3646 const std::string right(
3647 "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
3648 const std::string msg1(
3649 EqFailure("left", "right", left, right, false).failure_message());
3651 "Expected equality of these values:\n"
3654 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3656 " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3657 "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
3658 "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
3662 // Tests AppendUserMessage(), used for implementing the *EQ* macros.
3663 TEST(AssertionTest, AppendUserMessage) {
3664 const std::string foo("foo");
3668 AppendUserMessage(foo, msg).c_str());
3671 EXPECT_STREQ("foo\nbar",
3672 AppendUserMessage(foo, msg).c_str());
3676 // Silences warnings: "Condition is always true", "Unreachable code"
3677 # pragma option push -w-ccc -w-rch
3680 // Tests ASSERT_TRUE.
3681 TEST(AssertionTest, ASSERT_TRUE) {
3682 ASSERT_TRUE(2 > 1); // NOLINT
3683 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3687 // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3688 TEST(AssertionTest, AssertTrueWithAssertionResult) {
3689 ASSERT_TRUE(ResultIsEven(2));
3690 #ifndef __BORLANDC__
3691 // ICE's in C++Builder.
3692 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3693 "Value of: ResultIsEven(3)\n"
3694 " Actual: false (3 is odd)\n"
3697 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3698 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3699 "Value of: ResultIsEvenNoExplanation(3)\n"
3700 " Actual: false (3 is odd)\n"
3704 // Tests ASSERT_FALSE.
3705 TEST(AssertionTest, ASSERT_FALSE) {
3706 ASSERT_FALSE(2 < 1); // NOLINT
3707 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3713 // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3714 TEST(AssertionTest, AssertFalseWithAssertionResult) {
3715 ASSERT_FALSE(ResultIsEven(3));
3716 #ifndef __BORLANDC__
3717 // ICE's in C++Builder.
3718 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3719 "Value of: ResultIsEven(2)\n"
3720 " Actual: true (2 is even)\n"
3723 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3724 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3725 "Value of: ResultIsEvenNoExplanation(2)\n"
3731 // Restores warnings after previous "#pragma option push" suppressed them
3735 // Tests using ASSERT_EQ on double values. The purpose is to make
3736 // sure that the specialization we did for integer and anonymous enums
3737 // isn't used for double arguments.
3738 TEST(ExpectTest, ASSERT_EQ_Double) {
3740 ASSERT_EQ(5.6, 5.6);
3743 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3748 TEST(AssertionTest, ASSERT_EQ) {
3749 ASSERT_EQ(5, 2 + 3);
3750 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3751 "Expected equality of these values:\n"
3757 // Tests ASSERT_EQ(NULL, pointer).
3758 TEST(AssertionTest, ASSERT_EQ_NULL) {
3760 const char* p = nullptr;
3761 ASSERT_EQ(nullptr, p);
3765 EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:");
3768 // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3769 // treated as a null pointer by the compiler, we need to make sure
3770 // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3771 // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3772 TEST(ExpectTest, ASSERT_EQ_0) {
3779 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3784 TEST(AssertionTest, ASSERT_NE) {
3786 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3787 "Expected: ('a') != ('a'), "
3788 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3792 TEST(AssertionTest, ASSERT_LE) {
3795 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3796 "Expected: (2) <= (0), actual: 2 vs 0");
3800 TEST(AssertionTest, ASSERT_LT) {
3802 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3803 "Expected: (2) < (2), actual: 2 vs 2");
3807 TEST(AssertionTest, ASSERT_GE) {
3810 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3811 "Expected: (2) >= (3), actual: 2 vs 3");
3815 TEST(AssertionTest, ASSERT_GT) {
3817 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3818 "Expected: (2) > (2), actual: 2 vs 2");
3821 #if GTEST_HAS_EXCEPTIONS
3823 void ThrowNothing() {}
3825 // Tests ASSERT_THROW.
3826 TEST(AssertionTest, ASSERT_THROW) {
3827 ASSERT_THROW(ThrowAnInteger(), int);
3829 # ifndef __BORLANDC__
3831 // ICE's in C++Builder 2007 and 2009.
3832 EXPECT_FATAL_FAILURE(
3833 ASSERT_THROW(ThrowAnInteger(), bool),
3834 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3835 " Actual: it throws a different type.");
3836 EXPECT_FATAL_FAILURE(
3837 ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
3838 "Expected: ThrowRuntimeError(\"A description\") "
3839 "throws an exception of type std::logic_error.\n "
3840 "Actual: it throws " ERROR_DESC " "
3841 "with description \"A description\".");
3844 EXPECT_FATAL_FAILURE(
3845 ASSERT_THROW(ThrowNothing(), bool),
3846 "Expected: ThrowNothing() throws an exception of type bool.\n"
3847 " Actual: it throws nothing.");
3850 // Tests ASSERT_NO_THROW.
3851 TEST(AssertionTest, ASSERT_NO_THROW) {
3852 ASSERT_NO_THROW(ThrowNothing());
3853 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3854 "Expected: ThrowAnInteger() doesn't throw an exception."
3855 "\n Actual: it throws.");
3856 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
3857 "Expected: ThrowRuntimeError(\"A description\") "
3858 "doesn't throw an exception.\n "
3859 "Actual: it throws " ERROR_DESC " "
3860 "with description \"A description\".");
3863 // Tests ASSERT_ANY_THROW.
3864 TEST(AssertionTest, ASSERT_ANY_THROW) {
3865 ASSERT_ANY_THROW(ThrowAnInteger());
3866 EXPECT_FATAL_FAILURE(
3867 ASSERT_ANY_THROW(ThrowNothing()),
3868 "Expected: ThrowNothing() throws an exception.\n"
3869 " Actual: it doesn't.");
3872 #endif // GTEST_HAS_EXCEPTIONS
3874 // Makes sure we deal with the precedence of <<. This test should
3876 TEST(AssertionTest, AssertPrecedence) {
3877 ASSERT_EQ(1 < 2, true);
3878 bool false_value = false;
3879 ASSERT_EQ(true && false_value, false);
3882 // A subroutine used by the following test.
3883 void TestEq1(int x) {
3887 // Tests calling a test subroutine that's not part of a fixture.
3888 TEST(AssertionTest, NonFixtureSubroutine) {
3889 EXPECT_FATAL_FAILURE(TestEq1(2),
3890 " x\n Which is: 2");
3893 // An uncopyable class.
3896 explicit Uncopyable(int a_value) : value_(a_value) {}
3898 int value() const { return value_; }
3899 bool operator==(const Uncopyable& rhs) const {
3900 return value() == rhs.value();
3903 // This constructor deliberately has no implementation, as we don't
3904 // want this class to be copyable.
3905 Uncopyable(const Uncopyable&); // NOLINT
3910 ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3911 return os << value.value();
3915 bool IsPositiveUncopyable(const Uncopyable& x) {
3916 return x.value() > 0;
3919 // A subroutine used by the following test.
3920 void TestAssertNonPositive() {
3922 ASSERT_PRED1(IsPositiveUncopyable, y);
3924 // A subroutine used by the following test.
3925 void TestAssertEqualsUncopyable() {
3931 // Tests that uncopyable objects can be used in assertions.
3932 TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3934 ASSERT_PRED1(IsPositiveUncopyable, x);
3936 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3937 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3938 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3939 "Expected equality of these values:\n"
3940 " x\n Which is: 5\n y\n Which is: -1");
3943 // Tests that uncopyable objects can be used in expects.
3944 TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3946 EXPECT_PRED1(IsPositiveUncopyable, x);
3948 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3949 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3951 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3952 "Expected equality of these values:\n"
3953 " x\n Which is: 5\n y\n Which is: -1");
3961 TEST(AssertionTest, NamedEnum) {
3962 EXPECT_EQ(kE1, kE1);
3963 EXPECT_LT(kE1, kE2);
3964 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3965 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
3968 // Sun Studio and HP aCC2reject this code.
3969 #if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3971 // Tests using assertions with anonymous enums.
3977 // We want to test the case where the size of the anonymous enum is
3978 // larger than sizeof(int), to make sure our implementation of the
3979 // assertions doesn't truncate the enums. However, MSVC
3980 // (incorrectly) doesn't allow an enum value to exceed the range of
3981 // an int, so this has to be conditionally compiled.
3983 // On Linux, kCaseB and kCaseA have the same value when truncated to
3984 // int size. We want to test whether this will confuse the
3986 kCaseB = testing::internal::kMaxBiggestInt,
3992 # endif // GTEST_OS_LINUX
3997 TEST(AssertionTest, AnonymousEnum) {
4000 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
4002 # endif // GTEST_OS_LINUX
4004 EXPECT_EQ(kCaseA, kCaseA);
4005 EXPECT_NE(kCaseA, kCaseB);
4006 EXPECT_LT(kCaseA, kCaseB);
4007 EXPECT_LE(kCaseA, kCaseB);
4008 EXPECT_GT(kCaseB, kCaseA);
4009 EXPECT_GE(kCaseA, kCaseA);
4010 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
4011 "(kCaseA) >= (kCaseB)");
4012 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
4015 ASSERT_EQ(kCaseA, kCaseA);
4016 ASSERT_NE(kCaseA, kCaseB);
4017 ASSERT_LT(kCaseA, kCaseB);
4018 ASSERT_LE(kCaseA, kCaseB);
4019 ASSERT_GT(kCaseB, kCaseA);
4020 ASSERT_GE(kCaseA, kCaseA);
4022 # ifndef __BORLANDC__
4024 // ICE's in C++Builder.
4025 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
4026 " kCaseB\n Which is: ");
4027 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
4031 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
4035 #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
4037 #if GTEST_OS_WINDOWS
4039 static HRESULT UnexpectedHRESULTFailure() {
4040 return E_UNEXPECTED;
4043 static HRESULT OkHRESULTSuccess() {
4047 static HRESULT FalseHRESULTSuccess() {
4051 // HRESULT assertion tests test both zero and non-zero
4052 // success codes as well as failure message for each.
4054 // Windows CE doesn't support message texts.
4055 TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
4056 EXPECT_HRESULT_SUCCEEDED(S_OK);
4057 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
4059 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4060 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4061 " Actual: 0x8000FFFF");
4064 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
4065 ASSERT_HRESULT_SUCCEEDED(S_OK);
4066 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
4068 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4069 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4070 " Actual: 0x8000FFFF");
4073 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
4074 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
4076 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
4077 "Expected: (OkHRESULTSuccess()) fails.\n"
4079 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
4080 "Expected: (FalseHRESULTSuccess()) fails.\n"
4084 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4085 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
4087 # ifndef __BORLANDC__
4089 // ICE's in C++Builder 2007 and 2009.
4090 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4091 "Expected: (OkHRESULTSuccess()) fails.\n"
4095 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4096 "Expected: (FalseHRESULTSuccess()) fails.\n"
4100 // Tests that streaming to the HRESULT macros works.
4101 TEST(HRESULTAssertionTest, Streaming) {
4102 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4103 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4104 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4105 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4107 EXPECT_NONFATAL_FAILURE(
4108 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4109 "expected failure");
4111 # ifndef __BORLANDC__
4113 // ICE's in C++Builder 2007 and 2009.
4114 EXPECT_FATAL_FAILURE(
4115 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4116 "expected failure");
4119 EXPECT_NONFATAL_FAILURE(
4120 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4121 "expected failure");
4123 EXPECT_FATAL_FAILURE(
4124 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4125 "expected failure");
4128 #endif // GTEST_OS_WINDOWS
4130 // The following code intentionally tests a suboptimal syntax.
4132 #pragma GCC diagnostic push
4133 #pragma GCC diagnostic ignored "-Wdangling-else"
4134 #pragma GCC diagnostic ignored "-Wempty-body"
4135 #pragma GCC diagnostic ignored "-Wpragmas"
4137 // Tests that the assertion macros behave like single statements.
4138 TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4140 ASSERT_TRUE(false) << "This should never be executed; "
4141 "It's a compilation test only.";
4144 EXPECT_FALSE(false);
4154 EXPECT_GT(3, 2) << "";
4157 #pragma GCC diagnostic pop
4160 #if GTEST_HAS_EXCEPTIONS
4161 // Tests that the compiler will not complain about unreachable code in the
4162 // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4163 TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4166 EXPECT_THROW(throw 1, int);
4167 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4168 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4169 EXPECT_NO_THROW(n++);
4170 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4171 EXPECT_ANY_THROW(throw 1);
4172 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4175 TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
4176 EXPECT_THROW(throw std::exception(), std::exception);
4179 // The following code intentionally tests a suboptimal syntax.
4181 #pragma GCC diagnostic push
4182 #pragma GCC diagnostic ignored "-Wdangling-else"
4183 #pragma GCC diagnostic ignored "-Wempty-body"
4184 #pragma GCC diagnostic ignored "-Wpragmas"
4186 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4188 EXPECT_THROW(ThrowNothing(), bool);
4191 EXPECT_THROW(ThrowAnInteger(), int);
4196 EXPECT_NO_THROW(ThrowAnInteger());
4199 EXPECT_NO_THROW(ThrowNothing());
4204 EXPECT_ANY_THROW(ThrowNothing());
4207 EXPECT_ANY_THROW(ThrowAnInteger());
4212 #pragma GCC diagnostic pop
4215 #endif // GTEST_HAS_EXCEPTIONS
4217 // The following code intentionally tests a suboptimal syntax.
4219 #pragma GCC diagnostic push
4220 #pragma GCC diagnostic ignored "-Wdangling-else"
4221 #pragma GCC diagnostic ignored "-Wempty-body"
4222 #pragma GCC diagnostic ignored "-Wpragmas"
4224 TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4226 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4227 << "It's a compilation test only.";
4232 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4237 EXPECT_NO_FATAL_FAILURE(SUCCEED());
4244 ASSERT_NO_FATAL_FAILURE(SUCCEED());
4247 #pragma GCC diagnostic pop
4250 // Tests that the assertion macros work well with switch statements.
4251 TEST(AssertionSyntaxTest, WorksWithSwitch) {
4261 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4263 // Binary assertions are implemented using a different code path
4264 // than the Boolean assertions. Hence we test them separately.
4268 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4276 #if GTEST_HAS_EXCEPTIONS
4278 void ThrowAString() {
4279 throw "std::string";
4282 // Test that the exception assertion macros compile and work with const
4284 TEST(AssertionSyntaxTest, WorksWithConst) {
4285 ASSERT_THROW(ThrowAString(), const char*);
4287 EXPECT_THROW(ThrowAString(), const char*);
4290 #endif // GTEST_HAS_EXCEPTIONS
4296 // Tests that Google Test tracks SUCCEED*.
4297 TEST(SuccessfulAssertionTest, SUCCEED) {
4300 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4303 // Tests that Google Test doesn't track successful EXPECT_*.
4304 TEST(SuccessfulAssertionTest, EXPECT) {
4306 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4309 // Tests that Google Test doesn't track successful EXPECT_STR*.
4310 TEST(SuccessfulAssertionTest, EXPECT_STR) {
4311 EXPECT_STREQ("", "");
4312 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4315 // Tests that Google Test doesn't track successful ASSERT_*.
4316 TEST(SuccessfulAssertionTest, ASSERT) {
4318 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4321 // Tests that Google Test doesn't track successful ASSERT_STR*.
4322 TEST(SuccessfulAssertionTest, ASSERT_STR) {
4323 ASSERT_STREQ("", "");
4324 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4327 } // namespace testing
4331 // Tests the message streaming variation of assertions.
4333 TEST(AssertionWithMessageTest, EXPECT) {
4334 EXPECT_EQ(1, 1) << "This should succeed.";
4335 EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4336 "Expected failure #1");
4337 EXPECT_LE(1, 2) << "This should succeed.";
4338 EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4339 "Expected failure #2.");
4340 EXPECT_GE(1, 0) << "This should succeed.";
4341 EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4342 "Expected failure #3.");
4344 EXPECT_STREQ("1", "1") << "This should succeed.";
4345 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4346 "Expected failure #4.");
4347 EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4348 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4349 "Expected failure #5.");
4351 EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4352 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4353 "Expected failure #6.");
4354 EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4357 TEST(AssertionWithMessageTest, ASSERT) {
4358 ASSERT_EQ(1, 1) << "This should succeed.";
4359 ASSERT_NE(1, 2) << "This should succeed.";
4360 ASSERT_LE(1, 2) << "This should succeed.";
4361 ASSERT_LT(1, 2) << "This should succeed.";
4362 ASSERT_GE(1, 0) << "This should succeed.";
4363 EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4364 "Expected failure.");
4367 TEST(AssertionWithMessageTest, ASSERT_STR) {
4368 ASSERT_STREQ("1", "1") << "This should succeed.";
4369 ASSERT_STRNE("1", "2") << "This should succeed.";
4370 ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4371 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4372 "Expected failure.");
4375 TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4376 ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4377 ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4378 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT
4382 // Tests using ASSERT_FALSE with a streamed message.
4383 TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4384 ASSERT_FALSE(false) << "This shouldn't fail.";
4385 EXPECT_FATAL_FAILURE({ // NOLINT
4386 ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4387 << " evaluates to " << true;
4388 }, "Expected failure");
4391 // Tests using FAIL with a streamed message.
4392 TEST(AssertionWithMessageTest, FAIL) {
4393 EXPECT_FATAL_FAILURE(FAIL() << 0,
4397 // Tests using SUCCEED with a streamed message.
4398 TEST(AssertionWithMessageTest, SUCCEED) {
4399 SUCCEED() << "Success == " << 1;
4402 // Tests using ASSERT_TRUE with a streamed message.
4403 TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4404 ASSERT_TRUE(true) << "This should succeed.";
4405 ASSERT_TRUE(true) << true;
4406 EXPECT_FATAL_FAILURE(
4408 ASSERT_TRUE(false) << static_cast<const char*>(nullptr)
4409 << static_cast<char*>(nullptr);
4414 #if GTEST_OS_WINDOWS
4415 // Tests using wide strings in assertion messages.
4416 TEST(AssertionWithMessageTest, WideStringMessage) {
4417 EXPECT_NONFATAL_FAILURE({ // NOLINT
4418 EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4419 }, "This failure is expected.");
4420 EXPECT_FATAL_FAILURE({ // NOLINT
4421 ASSERT_EQ(1, 2) << "This failure is "
4422 << L"expected too.\x8120";
4423 }, "This failure is expected too.");
4425 #endif // GTEST_OS_WINDOWS
4427 // Tests EXPECT_TRUE.
4428 TEST(ExpectTest, EXPECT_TRUE) {
4429 EXPECT_TRUE(true) << "Intentional success";
4430 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4431 "Intentional failure #1.");
4432 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4433 "Intentional failure #2.");
4434 EXPECT_TRUE(2 > 1); // NOLINT
4435 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4439 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4443 // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4444 TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4445 EXPECT_TRUE(ResultIsEven(2));
4446 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4447 "Value of: ResultIsEven(3)\n"
4448 " Actual: false (3 is odd)\n"
4450 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4451 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4452 "Value of: ResultIsEvenNoExplanation(3)\n"
4453 " Actual: false (3 is odd)\n"
4457 // Tests EXPECT_FALSE with a streamed message.
4458 TEST(ExpectTest, EXPECT_FALSE) {
4459 EXPECT_FALSE(2 < 1); // NOLINT
4460 EXPECT_FALSE(false) << "Intentional success";
4461 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4462 "Intentional failure #1.");
4463 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4464 "Intentional failure #2.");
4465 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4469 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4473 // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4474 TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4475 EXPECT_FALSE(ResultIsEven(3));
4476 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4477 "Value of: ResultIsEven(2)\n"
4478 " Actual: true (2 is even)\n"
4480 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4481 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4482 "Value of: ResultIsEvenNoExplanation(2)\n"
4488 // Restores warnings after previous "#pragma option push" suppressed them
4493 TEST(ExpectTest, EXPECT_EQ) {
4494 EXPECT_EQ(5, 2 + 3);
4495 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4496 "Expected equality of these values:\n"
4500 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4504 // Tests using EXPECT_EQ on double values. The purpose is to make
4505 // sure that the specialization we did for integer and anonymous enums
4506 // isn't used for double arguments.
4507 TEST(ExpectTest, EXPECT_EQ_Double) {
4509 EXPECT_EQ(5.6, 5.6);
4512 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4516 // Tests EXPECT_EQ(NULL, pointer).
4517 TEST(ExpectTest, EXPECT_EQ_NULL) {
4519 const char* p = nullptr;
4520 EXPECT_EQ(nullptr, p);
4524 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:");
4527 // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4528 // treated as a null pointer by the compiler, we need to make sure
4529 // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4530 // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4531 TEST(ExpectTest, EXPECT_EQ_0) {
4538 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4543 TEST(ExpectTest, EXPECT_NE) {
4546 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4547 "Expected: ('a') != ('a'), "
4548 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4549 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4551 char* const p0 = nullptr;
4552 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4554 // Only way to get the Nokia compiler to compile the cast
4555 // is to have a separate void* variable first. Putting
4556 // the two casts on the same line doesn't work, neither does
4557 // a direct C-style to char*.
4558 void* pv1 = (void*)0x1234; // NOLINT
4559 char* const p1 = reinterpret_cast<char*>(pv1);
4560 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4565 TEST(ExpectTest, EXPECT_LE) {
4568 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4569 "Expected: (2) <= (0), actual: 2 vs 0");
4570 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4575 TEST(ExpectTest, EXPECT_LT) {
4577 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4578 "Expected: (2) < (2), actual: 2 vs 2");
4579 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4584 TEST(ExpectTest, EXPECT_GE) {
4587 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4588 "Expected: (2) >= (3), actual: 2 vs 3");
4589 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4594 TEST(ExpectTest, EXPECT_GT) {
4596 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4597 "Expected: (2) > (2), actual: 2 vs 2");
4598 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4602 #if GTEST_HAS_EXCEPTIONS
4604 // Tests EXPECT_THROW.
4605 TEST(ExpectTest, EXPECT_THROW) {
4606 EXPECT_THROW(ThrowAnInteger(), int);
4607 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4608 "Expected: ThrowAnInteger() throws an exception of "
4609 "type bool.\n Actual: it throws a different type.");
4610 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"),
4612 "Expected: ThrowRuntimeError(\"A description\") "
4613 "throws an exception of type std::logic_error.\n "
4614 "Actual: it throws " ERROR_DESC " "
4615 "with description \"A description\".");
4616 EXPECT_NONFATAL_FAILURE(
4617 EXPECT_THROW(ThrowNothing(), bool),
4618 "Expected: ThrowNothing() throws an exception of type bool.\n"
4619 " Actual: it throws nothing.");
4622 // Tests EXPECT_NO_THROW.
4623 TEST(ExpectTest, EXPECT_NO_THROW) {
4624 EXPECT_NO_THROW(ThrowNothing());
4625 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4626 "Expected: ThrowAnInteger() doesn't throw an "
4627 "exception.\n Actual: it throws.");
4628 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
4629 "Expected: ThrowRuntimeError(\"A description\") "
4630 "doesn't throw an exception.\n "
4631 "Actual: it throws " ERROR_DESC " "
4632 "with description \"A description\".");
4635 // Tests EXPECT_ANY_THROW.
4636 TEST(ExpectTest, EXPECT_ANY_THROW) {
4637 EXPECT_ANY_THROW(ThrowAnInteger());
4638 EXPECT_NONFATAL_FAILURE(
4639 EXPECT_ANY_THROW(ThrowNothing()),
4640 "Expected: ThrowNothing() throws an exception.\n"
4641 " Actual: it doesn't.");
4644 #endif // GTEST_HAS_EXCEPTIONS
4646 // Make sure we deal with the precedence of <<.
4647 TEST(ExpectTest, ExpectPrecedence) {
4648 EXPECT_EQ(1 < 2, true);
4649 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4650 " true && false\n Which is: false");
4654 // Tests the StreamableToString() function.
4656 // Tests using StreamableToString() on a scalar.
4657 TEST(StreamableToStringTest, Scalar) {
4658 EXPECT_STREQ("5", StreamableToString(5).c_str());
4661 // Tests using StreamableToString() on a non-char pointer.
4662 TEST(StreamableToStringTest, Pointer) {
4665 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4668 // Tests using StreamableToString() on a NULL non-char pointer.
4669 TEST(StreamableToStringTest, NullPointer) {
4671 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4674 // Tests using StreamableToString() on a C string.
4675 TEST(StreamableToStringTest, CString) {
4676 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4679 // Tests using StreamableToString() on a NULL C string.
4680 TEST(StreamableToStringTest, NullCString) {
4682 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4685 // Tests using streamable values as assertion messages.
4687 // Tests using std::string as an assertion message.
4688 TEST(StreamableTest, string) {
4689 static const std::string str(
4690 "This failure message is a std::string, and is expected.");
4691 EXPECT_FATAL_FAILURE(FAIL() << str,
4695 // Tests that we can output strings containing embedded NULs.
4696 // Limited to Linux because we can only do this with std::string's.
4697 TEST(StreamableTest, stringWithEmbeddedNUL) {
4698 static const char char_array_with_nul[] =
4699 "Here's a NUL\0 and some more string";
4700 static const std::string string_with_nul(char_array_with_nul,
4701 sizeof(char_array_with_nul)
4702 - 1); // drops the trailing NUL
4703 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4704 "Here's a NUL\\0 and some more string");
4707 // Tests that we can output a NUL char.
4708 TEST(StreamableTest, NULChar) {
4709 EXPECT_FATAL_FAILURE({ // NOLINT
4710 FAIL() << "A NUL" << '\0' << " and some more string";
4711 }, "A NUL\\0 and some more string");
4714 // Tests using int as an assertion message.
4715 TEST(StreamableTest, int) {
4716 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4720 // Tests using NULL char pointer as an assertion message.
4722 // In MSVC, streaming a NULL char * causes access violation. Google Test
4723 // implemented a workaround (substituting "(null)" for NULL). This
4724 // tests whether the workaround works.
4725 TEST(StreamableTest, NullCharPtr) {
4726 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)");
4729 // Tests that basic IO manipulators (endl, ends, and flush) can be
4730 // streamed to testing::Message.
4731 TEST(StreamableTest, BasicIoManip) {
4732 EXPECT_FATAL_FAILURE({ // NOLINT
4733 FAIL() << "Line 1." << std::endl
4734 << "A NUL char " << std::ends << std::flush << " in line 2.";
4735 }, "Line 1.\nA NUL char \\0 in line 2.");
4738 // Tests the macros that haven't been covered so far.
4740 void AddFailureHelper(bool* aborted) {
4742 ADD_FAILURE() << "Intentional failure.";
4746 // Tests ADD_FAILURE.
4747 TEST(MacroTest, ADD_FAILURE) {
4748 bool aborted = true;
4749 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4750 "Intentional failure.");
4751 EXPECT_FALSE(aborted);
4754 // Tests ADD_FAILURE_AT.
4755 TEST(MacroTest, ADD_FAILURE_AT) {
4756 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4757 // the failure message contains the user-streamed part.
4758 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4760 // Verifies that the user-streamed part is optional.
4761 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4763 // Unfortunately, we cannot verify that the failure message contains
4764 // the right file path and line number the same way, as
4765 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4766 // line number. Instead, we do that in googletest-output-test_.cc.
4770 TEST(MacroTest, FAIL) {
4771 EXPECT_FATAL_FAILURE(FAIL(),
4773 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4774 "Intentional failure.");
4777 // Tests GTEST_FAIL_AT.
4778 TEST(MacroTest, GTEST_FAIL_AT) {
4779 // Verifies that GTEST_FAIL_AT does generate a fatal failure and
4780 // the failure message contains the user-streamed part.
4781 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4783 // Verifies that the user-streamed part is optional.
4784 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed");
4786 // See the ADD_FAIL_AT test above to see how we test that the failure message
4787 // contains the right filename and line number -- the same applies here.
4791 TEST(MacroTest, SUCCEED) {
4793 SUCCEED() << "Explicit success.";
4796 // Tests for EXPECT_EQ() and ASSERT_EQ().
4798 // These tests fail *intentionally*, s.t. the failure messages can be
4799 // generated and tested.
4801 // We have different tests for different argument types.
4803 // Tests using bool values in {EXPECT|ASSERT}_EQ.
4804 TEST(EqAssertionTest, Bool) {
4805 EXPECT_EQ(true, true);
4806 EXPECT_FATAL_FAILURE({
4807 bool false_value = false;
4808 ASSERT_EQ(false_value, true);
4809 }, " false_value\n Which is: false\n true");
4812 // Tests using int values in {EXPECT|ASSERT}_EQ.
4813 TEST(EqAssertionTest, Int) {
4815 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4819 // Tests using time_t values in {EXPECT|ASSERT}_EQ.
4820 TEST(EqAssertionTest, Time_T) {
4821 EXPECT_EQ(static_cast<time_t>(0),
4822 static_cast<time_t>(0));
4823 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4824 static_cast<time_t>(1234)),
4828 // Tests using char values in {EXPECT|ASSERT}_EQ.
4829 TEST(EqAssertionTest, Char) {
4830 ASSERT_EQ('z', 'z');
4831 const char ch = 'b';
4832 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4833 " ch\n Which is: 'b'");
4834 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4835 " ch\n Which is: 'b'");
4838 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4839 TEST(EqAssertionTest, WideChar) {
4840 EXPECT_EQ(L'b', L'b');
4842 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4843 "Expected equality of these values:\n"
4845 " Which is: L'\0' (0, 0x0)\n"
4847 " Which is: L'x' (120, 0x78)");
4849 static wchar_t wchar;
4851 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4854 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
4855 " wchar\n Which is: L'");
4858 // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4859 TEST(EqAssertionTest, StdString) {
4860 // Compares a const char* to an std::string that has identical
4862 ASSERT_EQ("Test", ::std::string("Test"));
4864 // Compares two identical std::strings.
4865 static const ::std::string str1("A * in the middle");
4866 static const ::std::string str2(str1);
4867 EXPECT_EQ(str1, str2);
4869 // Compares a const char* to an std::string that has different
4871 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4874 // Compares an std::string to a char* that has different content.
4875 char* const p1 = const_cast<char*>("foo");
4876 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4879 // Compares two std::strings that have different contents, one of
4880 // which having a NUL character in the middle. This should fail.
4881 static ::std::string str3(str1);
4883 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4884 " str3\n Which is: \"A \\0 in the middle\"");
4887 #if GTEST_HAS_STD_WSTRING
4889 // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4890 TEST(EqAssertionTest, StdWideString) {
4891 // Compares two identical std::wstrings.
4892 const ::std::wstring wstr1(L"A * in the middle");
4893 const ::std::wstring wstr2(wstr1);
4894 ASSERT_EQ(wstr1, wstr2);
4896 // Compares an std::wstring to a const wchar_t* that has identical
4898 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4899 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4901 // Compares an std::wstring to a const wchar_t* that has different
4903 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4904 EXPECT_NONFATAL_FAILURE({ // NOLINT
4905 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4908 // Compares two std::wstrings that have different contents, one of
4909 // which having a NUL character in the middle.
4910 ::std::wstring wstr3(wstr1);
4911 wstr3.at(2) = L'\0';
4912 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4915 // Compares a wchar_t* to an std::wstring that has different
4917 EXPECT_FATAL_FAILURE({ // NOLINT
4918 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4922 #endif // GTEST_HAS_STD_WSTRING
4924 // Tests using char pointers in {EXPECT|ASSERT}_EQ.
4925 TEST(EqAssertionTest, CharPointer) {
4926 char* const p0 = nullptr;
4927 // Only way to get the Nokia compiler to compile the cast
4928 // is to have a separate void* variable first. Putting
4929 // the two casts on the same line doesn't work, neither does
4930 // a direct C-style to char*.
4931 void* pv1 = (void*)0x1234; // NOLINT
4932 void* pv2 = (void*)0xABC0; // NOLINT
4933 char* const p1 = reinterpret_cast<char*>(pv1);
4934 char* const p2 = reinterpret_cast<char*>(pv2);
4937 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4939 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4941 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4942 reinterpret_cast<char*>(0xABC0)),
4946 // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4947 TEST(EqAssertionTest, WideCharPointer) {
4948 wchar_t* const p0 = nullptr;
4949 // Only way to get the Nokia compiler to compile the cast
4950 // is to have a separate void* variable first. Putting
4951 // the two casts on the same line doesn't work, neither does
4952 // a direct C-style to char*.
4953 void* pv1 = (void*)0x1234; // NOLINT
4954 void* pv2 = (void*)0xABC0; // NOLINT
4955 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4956 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4959 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4961 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4963 void* pv3 = (void*)0x1234; // NOLINT
4964 void* pv4 = (void*)0xABC0; // NOLINT
4965 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4966 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4967 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4971 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4972 TEST(EqAssertionTest, OtherPointer) {
4973 ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));
4974 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),
4975 reinterpret_cast<const int*>(0x1234)),
4979 // A class that supports binary comparison operators but not streaming.
4980 class UnprintableChar {
4982 explicit UnprintableChar(char ch) : char_(ch) {}
4984 bool operator==(const UnprintableChar& rhs) const {
4985 return char_ == rhs.char_;
4987 bool operator!=(const UnprintableChar& rhs) const {
4988 return char_ != rhs.char_;
4990 bool operator<(const UnprintableChar& rhs) const {
4991 return char_ < rhs.char_;
4993 bool operator<=(const UnprintableChar& rhs) const {
4994 return char_ <= rhs.char_;
4996 bool operator>(const UnprintableChar& rhs) const {
4997 return char_ > rhs.char_;
4999 bool operator>=(const UnprintableChar& rhs) const {
5000 return char_ >= rhs.char_;
5007 // Tests that ASSERT_EQ() and friends don't require the arguments to
5009 TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
5010 const UnprintableChar x('x'), y('y');
5018 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
5019 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
5020 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
5021 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
5022 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
5024 // Code tested by EXPECT_FATAL_FAILURE cannot reference local
5025 // variables, so we have to write UnprintableChar('x') instead of x.
5026 #ifndef __BORLANDC__
5027 // ICE's in C++Builder.
5028 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
5029 "1-byte object <78>");
5030 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
5031 "1-byte object <78>");
5033 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
5034 "1-byte object <79>");
5035 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
5036 "1-byte object <78>");
5037 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
5038 "1-byte object <79>");
5041 // Tests the FRIEND_TEST macro.
5043 // This class has a private member we want to test. We will test it
5044 // both in a TEST and in a TEST_F.
5050 int Bar() const { return 1; }
5052 // Declares the friend tests that can access the private member
5054 FRIEND_TEST(FRIEND_TEST_Test, TEST);
5055 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
5058 // Tests that the FRIEND_TEST declaration allows a TEST to access a
5059 // class's private members. This should compile.
5060 TEST(FRIEND_TEST_Test, TEST) {
5061 ASSERT_EQ(1, Foo().Bar());
5064 // The fixture needed to test using FRIEND_TEST with TEST_F.
5065 class FRIEND_TEST_Test2 : public Test {
5070 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
5071 // class's private members. This should compile.
5072 TEST_F(FRIEND_TEST_Test2, TEST_F) {
5073 ASSERT_EQ(1, foo.Bar());
5076 // Tests the life cycle of Test objects.
5078 // The test fixture for testing the life cycle of Test objects.
5080 // This class counts the number of live test objects that uses this
5082 class TestLifeCycleTest : public Test {
5084 // Constructor. Increments the number of test objects that uses
5086 TestLifeCycleTest() { count_++; }
5088 // Destructor. Decrements the number of test objects that uses this
5090 ~TestLifeCycleTest() override { count_--; }
5092 // Returns the number of live test objects that uses this fixture.
5093 int count() const { return count_; }
5099 int TestLifeCycleTest::count_ = 0;
5101 // Tests the life cycle of test objects.
5102 TEST_F(TestLifeCycleTest, Test1) {
5103 // There should be only one test object in this test case that's
5105 ASSERT_EQ(1, count());
5108 // Tests the life cycle of test objects.
5109 TEST_F(TestLifeCycleTest, Test2) {
5110 // After Test1 is done and Test2 is started, there should still be
5111 // only one live test object, as the object for Test1 should've been
5113 ASSERT_EQ(1, count());
5118 // Tests that the copy constructor works when it is NOT optimized away by
5120 TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5121 // Checks that the copy constructor doesn't try to dereference NULL pointers
5122 // in the source object.
5123 AssertionResult r1 = AssertionSuccess();
5124 AssertionResult r2 = r1;
5125 // The following line is added to prevent the compiler from optimizing
5126 // away the constructor call.
5129 AssertionResult r3 = r1;
5130 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
5131 EXPECT_STREQ("abc", r1.message());
5134 // Tests that AssertionSuccess and AssertionFailure construct
5135 // AssertionResult objects as expected.
5136 TEST(AssertionResultTest, ConstructionWorks) {
5137 AssertionResult r1 = AssertionSuccess();
5139 EXPECT_STREQ("", r1.message());
5141 AssertionResult r2 = AssertionSuccess() << "abc";
5143 EXPECT_STREQ("abc", r2.message());
5145 AssertionResult r3 = AssertionFailure();
5147 EXPECT_STREQ("", r3.message());
5149 AssertionResult r4 = AssertionFailure() << "def";
5151 EXPECT_STREQ("def", r4.message());
5153 AssertionResult r5 = AssertionFailure(Message() << "ghi");
5155 EXPECT_STREQ("ghi", r5.message());
5158 // Tests that the negation flips the predicate result but keeps the message.
5159 TEST(AssertionResultTest, NegationWorks) {
5160 AssertionResult r1 = AssertionSuccess() << "abc";
5162 EXPECT_STREQ("abc", (!r1).message());
5164 AssertionResult r2 = AssertionFailure() << "def";
5166 EXPECT_STREQ("def", (!r2).message());
5169 TEST(AssertionResultTest, StreamingWorks) {
5170 AssertionResult r = AssertionSuccess();
5171 r << "abc" << 'd' << 0 << true;
5172 EXPECT_STREQ("abcd0true", r.message());
5175 TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5176 AssertionResult r = AssertionSuccess();
5177 r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5178 EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5181 // The next test uses explicit conversion operators
5183 TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5184 struct ExplicitlyConvertibleToBool {
5185 explicit operator bool() const { return value; }
5188 ExplicitlyConvertibleToBool v1 = {false};
5189 ExplicitlyConvertibleToBool v2 = {true};
5194 struct ConvertibleToAssertionResult {
5195 operator AssertionResult() const { return AssertionResult(true); }
5198 TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5199 ConvertibleToAssertionResult obj;
5203 // Tests streaming a user type whose definition and operator << are
5204 // both in the global namespace.
5207 explicit Base(int an_x) : x_(an_x) {}
5208 int x() const { return x_; }
5212 std::ostream& operator<<(std::ostream& os,
5214 return os << val.x();
5216 std::ostream& operator<<(std::ostream& os,
5217 const Base* pointer) {
5218 return os << "(" << pointer->x() << ")";
5221 TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5225 msg << a << &a; // Uses ::operator<<.
5226 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5229 // Tests streaming a user type whose definition and operator<< are
5230 // both in an unnamed namespace.
5232 class MyTypeInUnnamedNameSpace : public Base {
5234 explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
5236 std::ostream& operator<<(std::ostream& os,
5237 const MyTypeInUnnamedNameSpace& val) {
5238 return os << val.x();
5240 std::ostream& operator<<(std::ostream& os,
5241 const MyTypeInUnnamedNameSpace* pointer) {
5242 return os << "(" << pointer->x() << ")";
5246 TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5248 MyTypeInUnnamedNameSpace a(1);
5250 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
5251 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5254 // Tests streaming a user type whose definition and operator<< are
5255 // both in a user namespace.
5256 namespace namespace1 {
5257 class MyTypeInNameSpace1 : public Base {
5259 explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
5261 std::ostream& operator<<(std::ostream& os,
5262 const MyTypeInNameSpace1& val) {
5263 return os << val.x();
5265 std::ostream& operator<<(std::ostream& os,
5266 const MyTypeInNameSpace1* pointer) {
5267 return os << "(" << pointer->x() << ")";
5269 } // namespace namespace1
5271 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5273 namespace1::MyTypeInNameSpace1 a(1);
5275 msg << a << &a; // Uses namespace1::operator<<.
5276 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5279 // Tests streaming a user type whose definition is in a user namespace
5280 // but whose operator<< is in the global namespace.
5281 namespace namespace2 {
5282 class MyTypeInNameSpace2 : public ::Base {
5284 explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
5286 } // namespace namespace2
5287 std::ostream& operator<<(std::ostream& os,
5288 const namespace2::MyTypeInNameSpace2& val) {
5289 return os << val.x();
5291 std::ostream& operator<<(std::ostream& os,
5292 const namespace2::MyTypeInNameSpace2* pointer) {
5293 return os << "(" << pointer->x() << ")";
5296 TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5298 namespace2::MyTypeInNameSpace2 a(1);
5300 msg << a << &a; // Uses ::operator<<.
5301 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5304 // Tests streaming NULL pointers to testing::Message.
5305 TEST(MessageTest, NullPointers) {
5307 char* const p1 = nullptr;
5308 unsigned char* const p2 = nullptr;
5310 double* p4 = nullptr;
5312 Message* p6 = nullptr;
5314 msg << p1 << p2 << p3 << p4 << p5 << p6;
5315 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5316 msg.GetString().c_str());
5319 // Tests streaming wide strings to testing::Message.
5320 TEST(MessageTest, WideStrings) {
5321 // Streams a NULL of type const wchar_t*.
5322 const wchar_t* const_wstr = nullptr;
5323 EXPECT_STREQ("(null)",
5324 (Message() << const_wstr).GetString().c_str());
5326 // Streams a NULL of type wchar_t*.
5327 wchar_t* wstr = nullptr;
5328 EXPECT_STREQ("(null)",
5329 (Message() << wstr).GetString().c_str());
5331 // Streams a non-NULL of type const wchar_t*.
5332 const_wstr = L"abc\x8119";
5333 EXPECT_STREQ("abc\xe8\x84\x99",
5334 (Message() << const_wstr).GetString().c_str());
5336 // Streams a non-NULL of type wchar_t*.
5337 wstr = const_cast<wchar_t*>(const_wstr);
5338 EXPECT_STREQ("abc\xe8\x84\x99",
5339 (Message() << wstr).GetString().c_str());
5343 // This line tests that we can define tests in the testing namespace.
5346 // Tests the TestInfo class.
5348 class TestInfoTest : public Test {
5350 static const TestInfo* GetTestInfo(const char* test_name) {
5351 const TestSuite* const test_suite =
5352 GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr);
5354 for (int i = 0; i < test_suite->total_test_count(); ++i) {
5355 const TestInfo* const test_info = test_suite->GetTestInfo(i);
5356 if (strcmp(test_name, test_info->name()) == 0)
5362 static const TestResult* GetTestResult(
5363 const TestInfo* test_info) {
5364 return test_info->result();
5368 // Tests TestInfo::test_case_name() and TestInfo::name().
5369 TEST_F(TestInfoTest, Names) {
5370 const TestInfo* const test_info = GetTestInfo("Names");
5372 ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
5373 ASSERT_STREQ("Names", test_info->name());
5376 // Tests TestInfo::result().
5377 TEST_F(TestInfoTest, result) {
5378 const TestInfo* const test_info = GetTestInfo("result");
5380 // Initially, there is no TestPartResult for this test.
5381 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5383 // After the previous assertion, there is still none.
5384 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5387 #define VERIFY_CODE_LOCATION \
5388 const int expected_line = __LINE__ - 1; \
5389 const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
5390 ASSERT_TRUE(test_info); \
5391 EXPECT_STREQ(__FILE__, test_info->file()); \
5392 EXPECT_EQ(expected_line, test_info->line())
5394 TEST(CodeLocationForTEST, Verify) {
5395 VERIFY_CODE_LOCATION;
5398 class CodeLocationForTESTF : public Test {
5401 TEST_F(CodeLocationForTESTF, Verify) {
5402 VERIFY_CODE_LOCATION;
5405 class CodeLocationForTESTP : public TestWithParam<int> {
5408 TEST_P(CodeLocationForTESTP, Verify) {
5409 VERIFY_CODE_LOCATION;
5412 INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
5414 template <typename T>
5415 class CodeLocationForTYPEDTEST : public Test {
5418 TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);
5420 TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
5421 VERIFY_CODE_LOCATION;
5424 template <typename T>
5425 class CodeLocationForTYPEDTESTP : public Test {
5428 TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
5430 TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
5431 VERIFY_CODE_LOCATION;
5434 REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
5436 INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
5438 #undef VERIFY_CODE_LOCATION
5440 // Tests setting up and tearing down a test case.
5441 // Legacy API is deprecated but still available
5442 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5443 class SetUpTestCaseTest : public Test {
5445 // This will be called once before the first test in this test case
5447 static void SetUpTestCase() {
5448 printf("Setting up the test case . . .\n");
5450 // Initializes some shared resource. In this simple example, we
5451 // just create a C string. More complex stuff can be done if
5453 shared_resource_ = "123";
5455 // Increments the number of test cases that have been set up.
5458 // SetUpTestCase() should be called only once.
5459 EXPECT_EQ(1, counter_);
5462 // This will be called once after the last test in this test case is
5464 static void TearDownTestCase() {
5465 printf("Tearing down the test case . . .\n");
5467 // Decrements the number of test cases that have been set up.
5470 // TearDownTestCase() should be called only once.
5471 EXPECT_EQ(0, counter_);
5473 // Cleans up the shared resource.
5474 shared_resource_ = nullptr;
5477 // This will be called before each test in this test case.
5478 void SetUp() override {
5479 // SetUpTestCase() should be called only once, so counter_ should
5481 EXPECT_EQ(1, counter_);
5484 // Number of test cases that have been set up.
5485 static int counter_;
5487 // Some resource to be shared by all tests in this test case.
5488 static const char* shared_resource_;
5491 int SetUpTestCaseTest::counter_ = 0;
5492 const char* SetUpTestCaseTest::shared_resource_ = nullptr;
5494 // A test that uses the shared resource.
5495 TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
5497 // Another test that uses the shared resource.
5498 TEST_F(SetUpTestCaseTest, Test2) {
5499 EXPECT_STREQ("123", shared_resource_);
5501 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5503 // Tests SetupTestSuite/TearDown TestSuite
5504 class SetUpTestSuiteTest : public Test {
5506 // This will be called once before the first test in this test case
5508 static void SetUpTestSuite() {
5509 printf("Setting up the test suite . . .\n");
5511 // Initializes some shared resource. In this simple example, we
5512 // just create a C string. More complex stuff can be done if
5514 shared_resource_ = "123";
5516 // Increments the number of test cases that have been set up.
5519 // SetUpTestSuite() should be called only once.
5520 EXPECT_EQ(1, counter_);
5523 // This will be called once after the last test in this test case is
5525 static void TearDownTestSuite() {
5526 printf("Tearing down the test suite . . .\n");
5528 // Decrements the number of test suites that have been set up.
5531 // TearDownTestSuite() should be called only once.
5532 EXPECT_EQ(0, counter_);
5534 // Cleans up the shared resource.
5535 shared_resource_ = nullptr;
5538 // This will be called before each test in this test case.
5539 void SetUp() override {
5540 // SetUpTestSuite() should be called only once, so counter_ should
5542 EXPECT_EQ(1, counter_);
5545 // Number of test suites that have been set up.
5546 static int counter_;
5548 // Some resource to be shared by all tests in this test case.
5549 static const char* shared_resource_;
5552 int SetUpTestSuiteTest::counter_ = 0;
5553 const char* SetUpTestSuiteTest::shared_resource_ = nullptr;
5555 // A test that uses the shared resource.
5556 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) {
5557 EXPECT_STRNE(nullptr, shared_resource_);
5560 // Another test that uses the shared resource.
5561 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
5562 EXPECT_STREQ("123", shared_resource_);
5565 // The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.
5567 // The Flags struct stores a copy of all Google Test flags.
5569 // Constructs a Flags struct where each flag has its default value.
5571 : also_run_disabled_tests(false),
5572 break_on_failure(false),
5573 catch_exceptions(false),
5574 death_test_use_fork(false),
5584 stack_trace_depth(kMaxStackTraceDepth),
5585 stream_result_to(""),
5586 throw_on_failure(false) {}
5590 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5592 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5594 flags.also_run_disabled_tests = also_run_disabled_tests;
5598 // Creates a Flags struct where the gtest_break_on_failure flag has
5600 static Flags BreakOnFailure(bool break_on_failure) {
5602 flags.break_on_failure = break_on_failure;
5606 // Creates a Flags struct where the gtest_catch_exceptions flag has
5608 static Flags CatchExceptions(bool catch_exceptions) {
5610 flags.catch_exceptions = catch_exceptions;
5614 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5616 static Flags DeathTestUseFork(bool death_test_use_fork) {
5618 flags.death_test_use_fork = death_test_use_fork;
5622 // Creates a Flags struct where the gtest_fail_fast flag has
5624 static Flags FailFast(bool fail_fast) {
5626 flags.fail_fast = fail_fast;
5630 // Creates a Flags struct where the gtest_filter flag has the given
5632 static Flags Filter(const char* filter) {
5634 flags.filter = filter;
5638 // Creates a Flags struct where the gtest_list_tests flag has the
5640 static Flags ListTests(bool list_tests) {
5642 flags.list_tests = list_tests;
5646 // Creates a Flags struct where the gtest_output flag has the given
5648 static Flags Output(const char* output) {
5650 flags.output = output;
5654 // Creates a Flags struct where the gtest_brief flag has the given
5656 static Flags Brief(bool brief) {
5658 flags.brief = brief;
5662 // Creates a Flags struct where the gtest_print_time flag has the given
5664 static Flags PrintTime(bool print_time) {
5666 flags.print_time = print_time;
5670 // Creates a Flags struct where the gtest_random_seed flag has the given
5672 static Flags RandomSeed(int32_t random_seed) {
5674 flags.random_seed = random_seed;
5678 // Creates a Flags struct where the gtest_repeat flag has the given
5680 static Flags Repeat(int32_t repeat) {
5682 flags.repeat = repeat;
5686 // Creates a Flags struct where the gtest_shuffle flag has the given
5688 static Flags Shuffle(bool shuffle) {
5690 flags.shuffle = shuffle;
5694 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5696 static Flags StackTraceDepth(int32_t stack_trace_depth) {
5698 flags.stack_trace_depth = stack_trace_depth;
5702 // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5704 static Flags StreamResultTo(const char* stream_result_to) {
5706 flags.stream_result_to = stream_result_to;
5710 // Creates a Flags struct where the gtest_throw_on_failure flag has
5712 static Flags ThrowOnFailure(bool throw_on_failure) {
5714 flags.throw_on_failure = throw_on_failure;
5718 // These fields store the flag values.
5719 bool also_run_disabled_tests;
5720 bool break_on_failure;
5721 bool catch_exceptions;
5722 bool death_test_use_fork;
5729 int32_t random_seed;
5732 int32_t stack_trace_depth;
5733 const char* stream_result_to;
5734 bool throw_on_failure;
5737 // Fixture for testing ParseGoogleTestFlagsOnly().
5738 class ParseFlagsTest : public Test {
5740 // Clears the flags before each test.
5741 void SetUp() override {
5742 GTEST_FLAG(also_run_disabled_tests) = false;
5743 GTEST_FLAG(break_on_failure) = false;
5744 GTEST_FLAG(catch_exceptions) = false;
5745 GTEST_FLAG(death_test_use_fork) = false;
5746 GTEST_FLAG(fail_fast) = false;
5747 GTEST_FLAG(filter) = "";
5748 GTEST_FLAG(list_tests) = false;
5749 GTEST_FLAG(output) = "";
5750 GTEST_FLAG(brief) = false;
5751 GTEST_FLAG(print_time) = true;
5752 GTEST_FLAG(random_seed) = 0;
5753 GTEST_FLAG(repeat) = 1;
5754 GTEST_FLAG(shuffle) = false;
5755 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
5756 GTEST_FLAG(stream_result_to) = "";
5757 GTEST_FLAG(throw_on_failure) = false;
5760 // Asserts that two narrow or wide string arrays are equal.
5761 template <typename CharType>
5762 static void AssertStringArrayEq(int size1, CharType** array1, int size2,
5763 CharType** array2) {
5764 ASSERT_EQ(size1, size2) << " Array sizes different.";
5766 for (int i = 0; i != size1; i++) {
5767 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5771 // Verifies that the flag values match the expected values.
5772 static void CheckFlags(const Flags& expected) {
5773 EXPECT_EQ(expected.also_run_disabled_tests,
5774 GTEST_FLAG(also_run_disabled_tests));
5775 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5776 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
5777 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
5778 EXPECT_EQ(expected.fail_fast, GTEST_FLAG(fail_fast));
5779 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5780 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5781 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
5782 EXPECT_EQ(expected.brief, GTEST_FLAG(brief));
5783 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
5784 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
5785 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
5786 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
5787 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
5788 EXPECT_STREQ(expected.stream_result_to,
5789 GTEST_FLAG(stream_result_to).c_str());
5790 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
5793 // Parses a command line (specified by argc1 and argv1), then
5794 // verifies that the flag values are expected and that the
5795 // recognized flags are removed from the command line.
5796 template <typename CharType>
5797 static void TestParsingFlags(int argc1, const CharType** argv1,
5798 int argc2, const CharType** argv2,
5799 const Flags& expected, bool should_print_help) {
5800 const bool saved_help_flag = ::testing::internal::g_help_flag;
5801 ::testing::internal::g_help_flag = false;
5803 # if GTEST_HAS_STREAM_REDIRECTION
5807 // Parses the command line.
5808 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5810 # if GTEST_HAS_STREAM_REDIRECTION
5811 const std::string captured_stdout = GetCapturedStdout();
5814 // Verifies the flag values.
5815 CheckFlags(expected);
5817 // Verifies that the recognized flags are removed from the command
5819 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5821 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5822 // help message for the flags it recognizes.
5823 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5825 # if GTEST_HAS_STREAM_REDIRECTION
5826 const char* const expected_help_fragment =
5827 "This program contains tests written using";
5828 if (should_print_help) {
5829 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5831 EXPECT_PRED_FORMAT2(IsNotSubstring,
5832 expected_help_fragment, captured_stdout);
5834 # endif // GTEST_HAS_STREAM_REDIRECTION
5836 ::testing::internal::g_help_flag = saved_help_flag;
5839 // This macro wraps TestParsingFlags s.t. the user doesn't need
5840 // to specify the array sizes.
5842 # define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5843 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5844 sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5845 expected, should_print_help)
5848 // Tests parsing an empty command line.
5849 TEST_F(ParseFlagsTest, Empty) {
5850 const char* argv[] = {nullptr};
5852 const char* argv2[] = {nullptr};
5854 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5857 // Tests parsing a command line that has no flag.
5858 TEST_F(ParseFlagsTest, NoFlag) {
5859 const char* argv[] = {"foo.exe", nullptr};
5861 const char* argv2[] = {"foo.exe", nullptr};
5863 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5866 // Tests parsing --gtest_fail_fast.
5867 TEST_F(ParseFlagsTest, FailFast) {
5868 const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
5870 const char* argv2[] = {"foo.exe", nullptr};
5872 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
5875 // Tests parsing a bad --gtest_filter flag.
5876 TEST_F(ParseFlagsTest, FilterBad) {
5877 const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
5879 const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
5881 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
5884 // Tests parsing an empty --gtest_filter flag.
5885 TEST_F(ParseFlagsTest, FilterEmpty) {
5886 const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
5888 const char* argv2[] = {"foo.exe", nullptr};
5890 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5893 // Tests parsing a non-empty --gtest_filter flag.
5894 TEST_F(ParseFlagsTest, FilterNonEmpty) {
5895 const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr};
5897 const char* argv2[] = {"foo.exe", nullptr};
5899 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5902 // Tests parsing --gtest_break_on_failure.
5903 TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {
5904 const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr};
5906 const char* argv2[] = {"foo.exe", nullptr};
5908 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5911 // Tests parsing --gtest_break_on_failure=0.
5912 TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {
5913 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr};
5915 const char* argv2[] = {"foo.exe", nullptr};
5917 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5920 // Tests parsing --gtest_break_on_failure=f.
5921 TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {
5922 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr};
5924 const char* argv2[] = {"foo.exe", nullptr};
5926 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5929 // Tests parsing --gtest_break_on_failure=F.
5930 TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {
5931 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr};
5933 const char* argv2[] = {"foo.exe", nullptr};
5935 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5938 // Tests parsing a --gtest_break_on_failure flag that has a "true"
5940 TEST_F(ParseFlagsTest, BreakOnFailureTrue) {
5941 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr};
5943 const char* argv2[] = {"foo.exe", nullptr};
5945 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5948 // Tests parsing --gtest_catch_exceptions.
5949 TEST_F(ParseFlagsTest, CatchExceptions) {
5950 const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr};
5952 const char* argv2[] = {"foo.exe", nullptr};
5954 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5957 // Tests parsing --gtest_death_test_use_fork.
5958 TEST_F(ParseFlagsTest, DeathTestUseFork) {
5959 const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr};
5961 const char* argv2[] = {"foo.exe", nullptr};
5963 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5966 // Tests having the same flag twice with different values. The
5967 // expected behavior is that the one coming last takes precedence.
5968 TEST_F(ParseFlagsTest, DuplicatedFlags) {
5969 const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b",
5972 const char* argv2[] = {"foo.exe", nullptr};
5974 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5977 // Tests having an unrecognized flag on the command line.
5978 TEST_F(ParseFlagsTest, UnrecognizedFlag) {
5979 const char* argv[] = {"foo.exe", "--gtest_break_on_failure",
5980 "bar", // Unrecognized by Google Test.
5981 "--gtest_filter=b", nullptr};
5983 const char* argv2[] = {"foo.exe", "bar", nullptr};
5986 flags.break_on_failure = true;
5988 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5991 // Tests having a --gtest_list_tests flag
5992 TEST_F(ParseFlagsTest, ListTestsFlag) {
5993 const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr};
5995 const char* argv2[] = {"foo.exe", nullptr};
5997 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
6000 // Tests having a --gtest_list_tests flag with a "true" value
6001 TEST_F(ParseFlagsTest, ListTestsTrue) {
6002 const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr};
6004 const char* argv2[] = {"foo.exe", nullptr};
6006 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
6009 // Tests having a --gtest_list_tests flag with a "false" value
6010 TEST_F(ParseFlagsTest, ListTestsFalse) {
6011 const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr};
6013 const char* argv2[] = {"foo.exe", nullptr};
6015 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6018 // Tests parsing --gtest_list_tests=f.
6019 TEST_F(ParseFlagsTest, ListTestsFalse_f) {
6020 const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr};
6022 const char* argv2[] = {"foo.exe", nullptr};
6024 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6027 // Tests parsing --gtest_list_tests=F.
6028 TEST_F(ParseFlagsTest, ListTestsFalse_F) {
6029 const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr};
6031 const char* argv2[] = {"foo.exe", nullptr};
6033 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6036 // Tests parsing --gtest_output (invalid).
6037 TEST_F(ParseFlagsTest, OutputEmpty) {
6038 const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
6040 const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
6042 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
6045 // Tests parsing --gtest_output=xml
6046 TEST_F(ParseFlagsTest, OutputXml) {
6047 const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
6049 const char* argv2[] = {"foo.exe", nullptr};
6051 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
6054 // Tests parsing --gtest_output=xml:file
6055 TEST_F(ParseFlagsTest, OutputXmlFile) {
6056 const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr};
6058 const char* argv2[] = {"foo.exe", nullptr};
6060 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
6063 // Tests parsing --gtest_output=xml:directory/path/
6064 TEST_F(ParseFlagsTest, OutputXmlDirectory) {
6065 const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/",
6068 const char* argv2[] = {"foo.exe", nullptr};
6070 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6071 Flags::Output("xml:directory/path/"), false);
6074 // Tests having a --gtest_brief flag
6075 TEST_F(ParseFlagsTest, BriefFlag) {
6076 const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
6078 const char* argv2[] = {"foo.exe", nullptr};
6080 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
6083 // Tests having a --gtest_brief flag with a "true" value
6084 TEST_F(ParseFlagsTest, BriefFlagTrue) {
6085 const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
6087 const char* argv2[] = {"foo.exe", nullptr};
6089 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
6092 // Tests having a --gtest_brief flag with a "false" value
6093 TEST_F(ParseFlagsTest, BriefFlagFalse) {
6094 const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
6096 const char* argv2[] = {"foo.exe", nullptr};
6098 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
6101 // Tests having a --gtest_print_time flag
6102 TEST_F(ParseFlagsTest, PrintTimeFlag) {
6103 const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
6105 const char* argv2[] = {"foo.exe", nullptr};
6107 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6110 // Tests having a --gtest_print_time flag with a "true" value
6111 TEST_F(ParseFlagsTest, PrintTimeTrue) {
6112 const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr};
6114 const char* argv2[] = {"foo.exe", nullptr};
6116 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6119 // Tests having a --gtest_print_time flag with a "false" value
6120 TEST_F(ParseFlagsTest, PrintTimeFalse) {
6121 const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr};
6123 const char* argv2[] = {"foo.exe", nullptr};
6125 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6128 // Tests parsing --gtest_print_time=f.
6129 TEST_F(ParseFlagsTest, PrintTimeFalse_f) {
6130 const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr};
6132 const char* argv2[] = {"foo.exe", nullptr};
6134 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6137 // Tests parsing --gtest_print_time=F.
6138 TEST_F(ParseFlagsTest, PrintTimeFalse_F) {
6139 const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr};
6141 const char* argv2[] = {"foo.exe", nullptr};
6143 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6146 // Tests parsing --gtest_random_seed=number
6147 TEST_F(ParseFlagsTest, RandomSeed) {
6148 const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr};
6150 const char* argv2[] = {"foo.exe", nullptr};
6152 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6155 // Tests parsing --gtest_repeat=number
6156 TEST_F(ParseFlagsTest, Repeat) {
6157 const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr};
6159 const char* argv2[] = {"foo.exe", nullptr};
6161 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
6164 // Tests having a --gtest_also_run_disabled_tests flag
6165 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
6166 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
6168 const char* argv2[] = {"foo.exe", nullptr};
6170 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
6174 // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6175 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {
6176 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1",
6179 const char* argv2[] = {"foo.exe", nullptr};
6181 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
6185 // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6186 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {
6187 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0",
6190 const char* argv2[] = {"foo.exe", nullptr};
6192 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false),
6196 // Tests parsing --gtest_shuffle.
6197 TEST_F(ParseFlagsTest, ShuffleWithoutValue) {
6198 const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr};
6200 const char* argv2[] = {"foo.exe", nullptr};
6202 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6205 // Tests parsing --gtest_shuffle=0.
6206 TEST_F(ParseFlagsTest, ShuffleFalse_0) {
6207 const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr};
6209 const char* argv2[] = {"foo.exe", nullptr};
6211 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6214 // Tests parsing a --gtest_shuffle flag that has a "true" definition.
6215 TEST_F(ParseFlagsTest, ShuffleTrue) {
6216 const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr};
6218 const char* argv2[] = {"foo.exe", nullptr};
6220 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6223 // Tests parsing --gtest_stack_trace_depth=number.
6224 TEST_F(ParseFlagsTest, StackTraceDepth) {
6225 const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr};
6227 const char* argv2[] = {"foo.exe", nullptr};
6229 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6232 TEST_F(ParseFlagsTest, StreamResultTo) {
6233 const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234",
6236 const char* argv2[] = {"foo.exe", nullptr};
6238 GTEST_TEST_PARSING_FLAGS_(
6239 argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
6242 // Tests parsing --gtest_throw_on_failure.
6243 TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
6244 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr};
6246 const char* argv2[] = {"foo.exe", nullptr};
6248 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6251 // Tests parsing --gtest_throw_on_failure=0.
6252 TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {
6253 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr};
6255 const char* argv2[] = {"foo.exe", nullptr};
6257 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
6260 // Tests parsing a --gtest_throw_on_failure flag that has a "true"
6262 TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
6263 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr};
6265 const char* argv2[] = {"foo.exe", nullptr};
6267 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6270 # if GTEST_OS_WINDOWS
6271 // Tests parsing wide strings.
6272 TEST_F(ParseFlagsTest, WideStrings) {
6273 const wchar_t* argv[] = {
6275 L"--gtest_filter=Foo*",
6276 L"--gtest_list_tests=1",
6277 L"--gtest_break_on_failure",
6278 L"--non_gtest_flag",
6282 const wchar_t* argv2[] = {
6284 L"--non_gtest_flag",
6288 Flags expected_flags;
6289 expected_flags.break_on_failure = true;
6290 expected_flags.filter = "Foo*";
6291 expected_flags.list_tests = true;
6293 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6295 # endif // GTEST_OS_WINDOWS
6297 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6298 class FlagfileTest : public ParseFlagsTest {
6300 void SetUp() override {
6301 ParseFlagsTest::SetUp();
6303 testdata_path_.Set(internal::FilePath(
6304 testing::TempDir() + internal::GetCurrentExecutableName().string() +
6306 testing::internal::posix::RmDir(testdata_path_.c_str());
6307 EXPECT_TRUE(testdata_path_.CreateFolder());
6310 void TearDown() override {
6311 testing::internal::posix::RmDir(testdata_path_.c_str());
6312 ParseFlagsTest::TearDown();
6315 internal::FilePath CreateFlagfile(const char* contents) {
6316 internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
6317 testdata_path_, internal::FilePath("unique"), "txt"));
6318 FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
6319 fprintf(f, "%s", contents);
6325 internal::FilePath testdata_path_;
6328 // Tests an empty flagfile.
6329 TEST_F(FlagfileTest, Empty) {
6330 internal::FilePath flagfile_path(CreateFlagfile(""));
6331 std::string flagfile_flag =
6332 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6334 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6336 const char* argv2[] = {"foo.exe", nullptr};
6338 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
6341 // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
6342 TEST_F(FlagfileTest, FilterNonEmpty) {
6343 internal::FilePath flagfile_path(CreateFlagfile(
6344 "--" GTEST_FLAG_PREFIX_ "filter=abc"));
6345 std::string flagfile_flag =
6346 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6348 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6350 const char* argv2[] = {"foo.exe", nullptr};
6352 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
6355 // Tests passing several flags via --gtest_flagfile.
6356 TEST_F(FlagfileTest, SeveralFlags) {
6357 internal::FilePath flagfile_path(CreateFlagfile(
6358 "--" GTEST_FLAG_PREFIX_ "filter=abc\n"
6359 "--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
6360 "--" GTEST_FLAG_PREFIX_ "list_tests"));
6361 std::string flagfile_flag =
6362 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6364 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6366 const char* argv2[] = {"foo.exe", nullptr};
6368 Flags expected_flags;
6369 expected_flags.break_on_failure = true;
6370 expected_flags.filter = "abc";
6371 expected_flags.list_tests = true;
6373 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6375 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6377 // Tests current_test_info() in UnitTest.
6378 class CurrentTestInfoTest : public Test {
6380 // Tests that current_test_info() returns NULL before the first test in
6381 // the test case is run.
6382 static void SetUpTestSuite() {
6383 // There should be no tests running at this point.
6384 const TestInfo* test_info =
6385 UnitTest::GetInstance()->current_test_info();
6386 EXPECT_TRUE(test_info == nullptr)
6387 << "There should be no tests running at this point.";
6390 // Tests that current_test_info() returns NULL after the last test in
6391 // the test case has run.
6392 static void TearDownTestSuite() {
6393 const TestInfo* test_info =
6394 UnitTest::GetInstance()->current_test_info();
6395 EXPECT_TRUE(test_info == nullptr)
6396 << "There should be no tests running at this point.";
6400 // Tests that current_test_info() returns TestInfo for currently running
6401 // test by checking the expected test name against the actual one.
6402 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
6403 const TestInfo* test_info =
6404 UnitTest::GetInstance()->current_test_info();
6405 ASSERT_TRUE(nullptr != test_info)
6406 << "There is a test running so we should have a valid TestInfo.";
6407 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6408 << "Expected the name of the currently running test suite.";
6409 EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
6410 << "Expected the name of the currently running test.";
6413 // Tests that current_test_info() returns TestInfo for currently running
6414 // test by checking the expected test name against the actual one. We
6415 // use this test to see that the TestInfo object actually changed from
6416 // the previous invocation.
6417 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
6418 const TestInfo* test_info =
6419 UnitTest::GetInstance()->current_test_info();
6420 ASSERT_TRUE(nullptr != test_info)
6421 << "There is a test running so we should have a valid TestInfo.";
6422 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6423 << "Expected the name of the currently running test suite.";
6424 EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
6425 << "Expected the name of the currently running test.";
6428 } // namespace testing
6431 // These two lines test that we can define tests in a namespace that
6432 // has the name "testing" and is nested in another namespace.
6433 namespace my_namespace {
6436 // Makes sure that TEST knows to use ::testing::Test instead of
6437 // ::my_namespace::testing::Test.
6440 // Makes sure that an assertion knows to use ::testing::Message instead of
6441 // ::my_namespace::testing::Message.
6444 // Makes sure that an assertion knows to use
6445 // ::testing::AssertionResult instead of
6446 // ::my_namespace::testing::AssertionResult.
6447 class AssertionResult {};
6449 // Tests that an assertion that should succeed works as expected.
6450 TEST(NestedTestingNamespaceTest, Success) {
6451 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6454 // Tests that an assertion that should fail works as expected.
6455 TEST(NestedTestingNamespaceTest, Failure) {
6456 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6457 "This failure is expected.");
6460 } // namespace testing
6461 } // namespace my_namespace
6463 // Tests that one can call superclass SetUp and TearDown methods--
6464 // that is, that they are not private.
6465 // No tests are based on this fixture; the test "passes" if it compiles
6467 class ProtectedFixtureMethodsTest : public Test {
6469 void SetUp() override { Test::SetUp(); }
6470 void TearDown() override { Test::TearDown(); }
6473 // StreamingAssertionsTest tests the streaming versions of a representative
6474 // sample of assertions.
6475 TEST(StreamingAssertionsTest, Unconditional) {
6476 SUCCEED() << "expected success";
6477 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6478 "expected failure");
6479 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6480 "expected failure");
6484 // Silences warnings: "Condition is always true", "Unreachable code"
6485 # pragma option push -w-ccc -w-rch
6488 TEST(StreamingAssertionsTest, Truth) {
6489 EXPECT_TRUE(true) << "unexpected failure";
6490 ASSERT_TRUE(true) << "unexpected failure";
6491 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6492 "expected failure");
6493 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6494 "expected failure");
6497 TEST(StreamingAssertionsTest, Truth2) {
6498 EXPECT_FALSE(false) << "unexpected failure";
6499 ASSERT_FALSE(false) << "unexpected failure";
6500 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6501 "expected failure");
6502 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6503 "expected failure");
6507 // Restores warnings after previous "#pragma option push" suppressed them
6511 TEST(StreamingAssertionsTest, IntegerEquals) {
6512 EXPECT_EQ(1, 1) << "unexpected failure";
6513 ASSERT_EQ(1, 1) << "unexpected failure";
6514 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6515 "expected failure");
6516 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6517 "expected failure");
6520 TEST(StreamingAssertionsTest, IntegerLessThan) {
6521 EXPECT_LT(1, 2) << "unexpected failure";
6522 ASSERT_LT(1, 2) << "unexpected failure";
6523 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6524 "expected failure");
6525 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6526 "expected failure");
6529 TEST(StreamingAssertionsTest, StringsEqual) {
6530 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6531 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6532 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6533 "expected failure");
6534 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6535 "expected failure");
6538 TEST(StreamingAssertionsTest, StringsNotEqual) {
6539 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6540 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6541 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6542 "expected failure");
6543 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6544 "expected failure");
6547 TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6548 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6549 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6550 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6551 "expected failure");
6552 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6553 "expected failure");
6556 TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6557 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6558 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6559 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6560 "expected failure");
6561 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6562 "expected failure");
6565 TEST(StreamingAssertionsTest, FloatingPointEquals) {
6566 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6567 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6568 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6569 "expected failure");
6570 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6571 "expected failure");
6574 #if GTEST_HAS_EXCEPTIONS
6576 TEST(StreamingAssertionsTest, Throw) {
6577 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6578 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6579 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6580 "expected failure", "expected failure");
6581 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6582 "expected failure", "expected failure");
6585 TEST(StreamingAssertionsTest, NoThrow) {
6586 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6587 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6588 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6589 "expected failure", "expected failure");
6590 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6591 "expected failure", "expected failure");
6594 TEST(StreamingAssertionsTest, AnyThrow) {
6595 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6596 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6597 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
6598 "expected failure", "expected failure");
6599 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
6600 "expected failure", "expected failure");
6603 #endif // GTEST_HAS_EXCEPTIONS
6605 // Tests that Google Test correctly decides whether to use colors in the output.
6607 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6608 GTEST_FLAG(color) = "yes";
6610 SetEnv("TERM", "xterm"); // TERM supports colors.
6611 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6612 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6614 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6615 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6616 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6619 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6620 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6622 GTEST_FLAG(color) = "True";
6623 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6625 GTEST_FLAG(color) = "t";
6626 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6628 GTEST_FLAG(color) = "1";
6629 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6632 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6633 GTEST_FLAG(color) = "no";
6635 SetEnv("TERM", "xterm"); // TERM supports colors.
6636 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6637 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6639 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6640 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6641 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6644 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6645 SetEnv("TERM", "xterm"); // TERM supports colors.
6647 GTEST_FLAG(color) = "F";
6648 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6650 GTEST_FLAG(color) = "0";
6651 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6653 GTEST_FLAG(color) = "unknown";
6654 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6657 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6658 GTEST_FLAG(color) = "auto";
6660 SetEnv("TERM", "xterm"); // TERM supports colors.
6661 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6662 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6665 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6666 GTEST_FLAG(color) = "auto";
6668 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
6669 // On Windows, we ignore the TERM variable as it's usually not set.
6671 SetEnv("TERM", "dumb");
6672 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6675 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6677 SetEnv("TERM", "xterm");
6678 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6680 // On non-Windows platforms, we rely on TERM to determine if the
6681 // terminal supports colors.
6683 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6684 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6686 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6687 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6689 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6690 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6692 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6693 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6695 SetEnv("TERM", "xterm"); // TERM supports colors.
6696 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6698 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6699 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6701 SetEnv("TERM", "xterm-256color"); // TERM supports colors.
6702 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6704 SetEnv("TERM", "screen"); // TERM supports colors.
6705 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6707 SetEnv("TERM", "screen-256color"); // TERM supports colors.
6708 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6710 SetEnv("TERM", "tmux"); // TERM supports colors.
6711 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6713 SetEnv("TERM", "tmux-256color"); // TERM supports colors.
6714 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6716 SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
6717 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6719 SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
6720 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6722 SetEnv("TERM", "linux"); // TERM supports colors.
6723 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6725 SetEnv("TERM", "cygwin"); // TERM supports colors.
6726 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6727 #endif // GTEST_OS_WINDOWS
6730 // Verifies that StaticAssertTypeEq works in a namespace scope.
6732 static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6733 static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6734 StaticAssertTypeEq<const int, const int>();
6736 // Verifies that StaticAssertTypeEq works in a class.
6738 template <typename T>
6739 class StaticAssertTypeEqTestHelper {
6741 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6744 TEST(StaticAssertTypeEqTest, WorksInClass) {
6745 StaticAssertTypeEqTestHelper<bool>();
6748 // Verifies that StaticAssertTypeEq works inside a function.
6750 typedef int IntAlias;
6752 TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6753 StaticAssertTypeEq<int, IntAlias>();
6754 StaticAssertTypeEq<int*, IntAlias*>();
6757 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6758 EXPECT_FALSE(HasNonfatalFailure());
6761 static void FailFatally() { FAIL(); }
6763 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6765 const bool has_nonfatal_failure = HasNonfatalFailure();
6766 ClearCurrentTestPartResults();
6767 EXPECT_FALSE(has_nonfatal_failure);
6770 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6772 const bool has_nonfatal_failure = HasNonfatalFailure();
6773 ClearCurrentTestPartResults();
6774 EXPECT_TRUE(has_nonfatal_failure);
6777 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6780 const bool has_nonfatal_failure = HasNonfatalFailure();
6781 ClearCurrentTestPartResults();
6782 EXPECT_TRUE(has_nonfatal_failure);
6785 // A wrapper for calling HasNonfatalFailure outside of a test body.
6786 static bool HasNonfatalFailureHelper() {
6787 return testing::Test::HasNonfatalFailure();
6790 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6791 EXPECT_FALSE(HasNonfatalFailureHelper());
6794 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6796 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6797 ClearCurrentTestPartResults();
6798 EXPECT_TRUE(has_nonfatal_failure);
6801 TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6802 EXPECT_FALSE(HasFailure());
6805 TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6807 const bool has_failure = HasFailure();
6808 ClearCurrentTestPartResults();
6809 EXPECT_TRUE(has_failure);
6812 TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6814 const bool has_failure = HasFailure();
6815 ClearCurrentTestPartResults();
6816 EXPECT_TRUE(has_failure);
6819 TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6822 const bool has_failure = HasFailure();
6823 ClearCurrentTestPartResults();
6824 EXPECT_TRUE(has_failure);
6827 // A wrapper for calling HasFailure outside of a test body.
6828 static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6830 TEST(HasFailureTest, WorksOutsideOfTestBody) {
6831 EXPECT_FALSE(HasFailureHelper());
6834 TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6836 const bool has_failure = HasFailureHelper();
6837 ClearCurrentTestPartResults();
6838 EXPECT_TRUE(has_failure);
6841 class TestListener : public EmptyTestEventListener {
6843 TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
6844 TestListener(int* on_start_counter, bool* is_destroyed)
6845 : on_start_counter_(on_start_counter),
6846 is_destroyed_(is_destroyed) {}
6848 ~TestListener() override {
6850 *is_destroyed_ = true;
6854 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6855 if (on_start_counter_ != nullptr) (*on_start_counter_)++;
6859 int* on_start_counter_;
6860 bool* is_destroyed_;
6863 // Tests the constructor.
6864 TEST(TestEventListenersTest, ConstructionWorks) {
6865 TestEventListeners listeners;
6867 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr);
6868 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
6869 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
6872 // Tests that the TestEventListeners destructor deletes all the listeners it
6874 TEST(TestEventListenersTest, DestructionWorks) {
6875 bool default_result_printer_is_destroyed = false;
6876 bool default_xml_printer_is_destroyed = false;
6877 bool extra_listener_is_destroyed = false;
6878 TestListener* default_result_printer =
6879 new TestListener(nullptr, &default_result_printer_is_destroyed);
6880 TestListener* default_xml_printer =
6881 new TestListener(nullptr, &default_xml_printer_is_destroyed);
6882 TestListener* extra_listener =
6883 new TestListener(nullptr, &extra_listener_is_destroyed);
6886 TestEventListeners listeners;
6887 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
6888 default_result_printer);
6889 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
6890 default_xml_printer);
6891 listeners.Append(extra_listener);
6893 EXPECT_TRUE(default_result_printer_is_destroyed);
6894 EXPECT_TRUE(default_xml_printer_is_destroyed);
6895 EXPECT_TRUE(extra_listener_is_destroyed);
6898 // Tests that a listener Append'ed to a TestEventListeners list starts
6899 // receiving events.
6900 TEST(TestEventListenersTest, Append) {
6901 int on_start_counter = 0;
6902 bool is_destroyed = false;
6903 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6905 TestEventListeners listeners;
6906 listeners.Append(listener);
6907 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6908 *UnitTest::GetInstance());
6909 EXPECT_EQ(1, on_start_counter);
6911 EXPECT_TRUE(is_destroyed);
6914 // Tests that listeners receive events in the order they were appended to
6915 // the list, except for *End requests, which must be received in the reverse
6917 class SequenceTestingListener : public EmptyTestEventListener {
6919 SequenceTestingListener(std::vector<std::string>* vector, const char* id)
6920 : vector_(vector), id_(id) {}
6923 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6924 vector_->push_back(GetEventDescription("OnTestProgramStart"));
6927 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {
6928 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
6931 void OnTestIterationStart(const UnitTest& /*unit_test*/,
6932 int /*iteration*/) override {
6933 vector_->push_back(GetEventDescription("OnTestIterationStart"));
6936 void OnTestIterationEnd(const UnitTest& /*unit_test*/,
6937 int /*iteration*/) override {
6938 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
6942 std::string GetEventDescription(const char* method) {
6944 message << id_ << "." << method;
6945 return message.GetString();
6948 std::vector<std::string>* vector_;
6949 const char* const id_;
6951 GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
6954 TEST(EventListenerTest, AppendKeepsOrder) {
6955 std::vector<std::string> vec;
6956 TestEventListeners listeners;
6957 listeners.Append(new SequenceTestingListener(&vec, "1st"));
6958 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
6959 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
6961 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6962 *UnitTest::GetInstance());
6963 ASSERT_EQ(3U, vec.size());
6964 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
6965 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
6966 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
6969 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
6970 *UnitTest::GetInstance());
6971 ASSERT_EQ(3U, vec.size());
6972 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
6973 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
6974 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
6977 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
6978 *UnitTest::GetInstance(), 0);
6979 ASSERT_EQ(3U, vec.size());
6980 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
6981 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
6982 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
6985 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
6986 *UnitTest::GetInstance(), 0);
6987 ASSERT_EQ(3U, vec.size());
6988 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
6989 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
6990 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
6993 // Tests that a listener removed from a TestEventListeners list stops receiving
6994 // events and is not deleted when the list is destroyed.
6995 TEST(TestEventListenersTest, Release) {
6996 int on_start_counter = 0;
6997 bool is_destroyed = false;
6998 // Although Append passes the ownership of this object to the list,
6999 // the following calls release it, and we need to delete it before the
7001 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7003 TestEventListeners listeners;
7004 listeners.Append(listener);
7005 EXPECT_EQ(listener, listeners.Release(listener));
7006 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7007 *UnitTest::GetInstance());
7008 EXPECT_TRUE(listeners.Release(listener) == nullptr);
7010 EXPECT_EQ(0, on_start_counter);
7011 EXPECT_FALSE(is_destroyed);
7015 // Tests that no events are forwarded when event forwarding is disabled.
7016 TEST(EventListenerTest, SuppressEventForwarding) {
7017 int on_start_counter = 0;
7018 TestListener* listener = new TestListener(&on_start_counter, nullptr);
7020 TestEventListeners listeners;
7021 listeners.Append(listener);
7022 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7023 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
7024 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7025 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7026 *UnitTest::GetInstance());
7027 EXPECT_EQ(0, on_start_counter);
7030 // Tests that events generated by Google Test are not forwarded in
7031 // death test subprocesses.
7032 TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
7033 EXPECT_DEATH_IF_SUPPORTED({
7034 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
7035 *GetUnitTestImpl()->listeners())) << "expected failure";},
7036 "expected failure");
7039 // Tests that a listener installed via SetDefaultResultPrinter() starts
7040 // receiving events and is returned via default_result_printer() and that
7041 // the previous default_result_printer is removed from the list and deleted.
7042 TEST(EventListenerTest, default_result_printer) {
7043 int on_start_counter = 0;
7044 bool is_destroyed = false;
7045 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7047 TestEventListeners listeners;
7048 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7050 EXPECT_EQ(listener, listeners.default_result_printer());
7052 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7053 *UnitTest::GetInstance());
7055 EXPECT_EQ(1, on_start_counter);
7057 // Replacing default_result_printer with something else should remove it
7058 // from the list and destroy it.
7059 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr);
7061 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7062 EXPECT_TRUE(is_destroyed);
7064 // After broadcasting an event the counter is still the same, indicating
7065 // the listener is not in the list anymore.
7066 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7067 *UnitTest::GetInstance());
7068 EXPECT_EQ(1, on_start_counter);
7071 // Tests that the default_result_printer listener stops receiving events
7072 // when removed via Release and that is not owned by the list anymore.
7073 TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
7074 int on_start_counter = 0;
7075 bool is_destroyed = false;
7076 // Although Append passes the ownership of this object to the list,
7077 // the following calls release it, and we need to delete it before the
7079 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7081 TestEventListeners listeners;
7082 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7084 EXPECT_EQ(listener, listeners.Release(listener));
7085 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7086 EXPECT_FALSE(is_destroyed);
7088 // Broadcasting events now should not affect default_result_printer.
7089 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7090 *UnitTest::GetInstance());
7091 EXPECT_EQ(0, on_start_counter);
7093 // Destroying the list should not affect the listener now, too.
7094 EXPECT_FALSE(is_destroyed);
7098 // Tests that a listener installed via SetDefaultXmlGenerator() starts
7099 // receiving events and is returned via default_xml_generator() and that
7100 // the previous default_xml_generator is removed from the list and deleted.
7101 TEST(EventListenerTest, default_xml_generator) {
7102 int on_start_counter = 0;
7103 bool is_destroyed = false;
7104 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7106 TestEventListeners listeners;
7107 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7109 EXPECT_EQ(listener, listeners.default_xml_generator());
7111 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7112 *UnitTest::GetInstance());
7114 EXPECT_EQ(1, on_start_counter);
7116 // Replacing default_xml_generator with something else should remove it
7117 // from the list and destroy it.
7118 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr);
7120 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7121 EXPECT_TRUE(is_destroyed);
7123 // After broadcasting an event the counter is still the same, indicating
7124 // the listener is not in the list anymore.
7125 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7126 *UnitTest::GetInstance());
7127 EXPECT_EQ(1, on_start_counter);
7130 // Tests that the default_xml_generator listener stops receiving events
7131 // when removed via Release and that is not owned by the list anymore.
7132 TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
7133 int on_start_counter = 0;
7134 bool is_destroyed = false;
7135 // Although Append passes the ownership of this object to the list,
7136 // the following calls release it, and we need to delete it before the
7138 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7140 TestEventListeners listeners;
7141 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7143 EXPECT_EQ(listener, listeners.Release(listener));
7144 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7145 EXPECT_FALSE(is_destroyed);
7147 // Broadcasting events now should not affect default_xml_generator.
7148 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7149 *UnitTest::GetInstance());
7150 EXPECT_EQ(0, on_start_counter);
7152 // Destroying the list should not affect the listener now, too.
7153 EXPECT_FALSE(is_destroyed);
7157 // Sanity tests to ensure that the alternative, verbose spellings of
7158 // some of the macros work. We don't test them thoroughly as that
7159 // would be quite involved. Since their implementations are
7160 // straightforward, and they are rarely used, we'll just rely on the
7161 // users to tell us when they are broken.
7162 GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
7163 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
7165 // GTEST_FAIL is the same as FAIL.
7166 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
7167 "An expected failure");
7169 // GTEST_ASSERT_XY is the same as ASSERT_XY.
7171 GTEST_ASSERT_EQ(0, 0);
7172 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
7173 "An expected failure");
7174 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
7175 "An expected failure");
7177 GTEST_ASSERT_NE(0, 1);
7178 GTEST_ASSERT_NE(1, 0);
7179 EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
7180 "An expected failure");
7182 GTEST_ASSERT_LE(0, 0);
7183 GTEST_ASSERT_LE(0, 1);
7184 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
7185 "An expected failure");
7187 GTEST_ASSERT_LT(0, 1);
7188 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
7189 "An expected failure");
7190 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
7191 "An expected failure");
7193 GTEST_ASSERT_GE(0, 0);
7194 GTEST_ASSERT_GE(1, 0);
7195 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
7196 "An expected failure");
7198 GTEST_ASSERT_GT(1, 0);
7199 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
7200 "An expected failure");
7201 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
7202 "An expected failure");
7205 // Tests for internal utilities necessary for implementation of the universal
7208 class ConversionHelperBase {};
7209 class ConversionHelperDerived : public ConversionHelperBase {};
7211 struct HasDebugStringMethods {
7212 std::string DebugString() const { return ""; }
7213 std::string ShortDebugString() const { return ""; }
7216 struct InheritsDebugStringMethods : public HasDebugStringMethods {};
7218 struct WrongTypeDebugStringMethod {
7219 std::string DebugString() const { return ""; }
7220 int ShortDebugString() const { return 1; }
7223 struct NotConstDebugStringMethod {
7224 std::string DebugString() { return ""; }
7225 std::string ShortDebugString() const { return ""; }
7228 struct MissingDebugStringMethod {
7229 std::string DebugString() { return ""; }
7232 struct IncompleteType;
7234 // Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
7236 TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
7237 GTEST_COMPILE_ASSERT_(
7238 HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
7240 GTEST_COMPILE_ASSERT_(
7241 HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
7243 GTEST_COMPILE_ASSERT_(HasDebugStringAndShortDebugString<
7244 const InheritsDebugStringMethods>::value,
7246 GTEST_COMPILE_ASSERT_(
7247 !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
7249 GTEST_COMPILE_ASSERT_(
7250 !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
7252 GTEST_COMPILE_ASSERT_(
7253 !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
7255 GTEST_COMPILE_ASSERT_(
7256 !HasDebugStringAndShortDebugString<IncompleteType>::value, const_false);
7257 GTEST_COMPILE_ASSERT_(!HasDebugStringAndShortDebugString<int>::value,
7261 // Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
7263 TEST(HasDebugStringAndShortDebugStringTest,
7264 ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
7266 HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
7269 // Tests that HasDebugStringAndShortDebugString<T>::value is false when T
7270 // doesn't have needed methods.
7271 TEST(HasDebugStringAndShortDebugStringTest,
7272 ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7273 EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);
7275 HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);
7278 // Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7280 template <typename T1, typename T2>
7281 void TestGTestRemoveReferenceAndConst() {
7282 static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value,
7283 "GTEST_REMOVE_REFERENCE_AND_CONST_ failed.");
7286 TEST(RemoveReferenceToConstTest, Works) {
7287 TestGTestRemoveReferenceAndConst<int, int>();
7288 TestGTestRemoveReferenceAndConst<double, double&>();
7289 TestGTestRemoveReferenceAndConst<char, const char>();
7290 TestGTestRemoveReferenceAndConst<char, const char&>();
7291 TestGTestRemoveReferenceAndConst<const char*, const char*>();
7294 // Tests GTEST_REFERENCE_TO_CONST_.
7296 template <typename T1, typename T2>
7297 void TestGTestReferenceToConst() {
7298 static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value,
7299 "GTEST_REFERENCE_TO_CONST_ failed.");
7302 TEST(GTestReferenceToConstTest, Works) {
7303 TestGTestReferenceToConst<const char&, char>();
7304 TestGTestReferenceToConst<const int&, const int>();
7305 TestGTestReferenceToConst<const double&, double>();
7306 TestGTestReferenceToConst<const std::string&, const std::string&>();
7310 // Tests IsContainerTest.
7312 class NonContainer {};
7314 TEST(IsContainerTestTest, WorksForNonContainer) {
7315 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7316 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7317 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7320 TEST(IsContainerTestTest, WorksForContainer) {
7321 EXPECT_EQ(sizeof(IsContainer),
7322 sizeof(IsContainerTest<std::vector<bool> >(0)));
7323 EXPECT_EQ(sizeof(IsContainer),
7324 sizeof(IsContainerTest<std::map<int, double> >(0)));
7327 struct ConstOnlyContainerWithPointerIterator {
7328 using const_iterator = int*;
7329 const_iterator begin() const;
7330 const_iterator end() const;
7333 struct ConstOnlyContainerWithClassIterator {
7334 struct const_iterator {
7335 const int& operator*() const;
7336 const_iterator& operator++(/* pre-increment */);
7338 const_iterator begin() const;
7339 const_iterator end() const;
7342 TEST(IsContainerTestTest, ConstOnlyContainer) {
7343 EXPECT_EQ(sizeof(IsContainer),
7344 sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
7345 EXPECT_EQ(sizeof(IsContainer),
7346 sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
7349 // Tests IsHashTable.
7351 typedef void hasher;
7353 struct NotReallyAHashTable {
7354 typedef void hasher;
7355 typedef void reverse_iterator;
7357 TEST(IsHashTable, Basic) {
7358 EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value);
7359 EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value);
7360 EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value);
7361 EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value);
7366 TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7367 EXPECT_TRUE(ArrayEq(5, 5L));
7368 EXPECT_FALSE(ArrayEq('a', 0));
7371 TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7372 // Note that a and b are distinct but compatible types.
7373 const int a[] = { 0, 1 };
7374 long b[] = { 0, 1 };
7375 EXPECT_TRUE(ArrayEq(a, b));
7376 EXPECT_TRUE(ArrayEq(a, 2, b));
7379 EXPECT_FALSE(ArrayEq(a, b));
7380 EXPECT_FALSE(ArrayEq(a, 1, b));
7383 TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7384 const char a[][3] = { "hi", "lo" };
7385 const char b[][3] = { "hi", "lo" };
7386 const char c[][3] = { "hi", "li" };
7388 EXPECT_TRUE(ArrayEq(a, b));
7389 EXPECT_TRUE(ArrayEq(a, 2, b));
7391 EXPECT_FALSE(ArrayEq(a, c));
7392 EXPECT_FALSE(ArrayEq(a, 2, c));
7395 // Tests ArrayAwareFind().
7397 TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7398 const char a[] = "hello";
7399 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7400 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7403 TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7404 int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
7405 const int b[2] = { 2, 3 };
7406 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7408 const int c[2] = { 6, 7 };
7409 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7412 // Tests CopyArray().
7414 TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7420 TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7421 const char a[3] = "hi";
7423 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7425 EXPECT_TRUE(ArrayEq(a, b));
7430 EXPECT_TRUE(ArrayEq(a, c));
7433 TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7434 const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
7436 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7438 EXPECT_TRUE(ArrayEq(a, b));
7443 EXPECT_TRUE(ArrayEq(a, c));
7446 // Tests NativeArray.
7448 TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7449 const int a[3] = { 0, 1, 2 };
7450 NativeArray<int> na(a, 3, RelationToSourceReference());
7451 EXPECT_EQ(3U, na.size());
7452 EXPECT_EQ(a, na.begin());
7455 TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7456 typedef int Array[2];
7457 Array* a = new Array[1];
7460 NativeArray<int> na(*a, 2, RelationToSourceCopy());
7461 EXPECT_NE(*a, na.begin());
7463 EXPECT_EQ(0, na.begin()[0]);
7464 EXPECT_EQ(1, na.begin()[1]);
7466 // We rely on the heap checker to verify that na deletes the copy of
7470 TEST(NativeArrayTest, TypeMembersAreCorrect) {
7471 StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7472 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7474 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7475 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7478 TEST(NativeArrayTest, MethodsWork) {
7479 const int a[3] = { 0, 1, 2 };
7480 NativeArray<int> na(a, 3, RelationToSourceCopy());
7481 ASSERT_EQ(3U, na.size());
7482 EXPECT_EQ(3, na.end() - na.begin());
7484 NativeArray<int>::const_iterator it = na.begin();
7491 EXPECT_EQ(na.end(), it);
7493 EXPECT_TRUE(na == na);
7495 NativeArray<int> na2(a, 3, RelationToSourceReference());
7496 EXPECT_TRUE(na == na2);
7498 const int b1[3] = { 0, 1, 1 };
7499 const int b2[4] = { 0, 1, 2, 3 };
7500 EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
7501 EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
7504 TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7505 const char a[2][3] = { "hi", "lo" };
7506 NativeArray<char[3]> na(a, 2, RelationToSourceReference());
7507 ASSERT_EQ(2U, na.size());
7508 EXPECT_EQ(a, na.begin());
7512 TEST(IndexSequence, MakeIndexSequence) {
7513 using testing::internal::IndexSequence;
7514 using testing::internal::MakeIndexSequence;
7516 (std::is_same<IndexSequence<>, MakeIndexSequence<0>::type>::value));
7518 (std::is_same<IndexSequence<0>, MakeIndexSequence<1>::type>::value));
7520 (std::is_same<IndexSequence<0, 1>, MakeIndexSequence<2>::type>::value));
7522 std::is_same<IndexSequence<0, 1, 2>, MakeIndexSequence<3>::type>::value));
7524 (std::is_base_of<IndexSequence<0, 1, 2>, MakeIndexSequence<3>>::value));
7528 TEST(ElemFromList, Basic) {
7529 using testing::internal::ElemFromList;
7531 (std::is_same<int, ElemFromList<0, int, double, char>::type>::value));
7533 (std::is_same<double, ElemFromList<1, int, double, char>::type>::value));
7535 (std::is_same<char, ElemFromList<2, int, double, char>::type>::value));
7537 std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int,
7538 char, int, int, int, int>::type>::value));
7542 TEST(FlatTuple, Basic) {
7543 using testing::internal::FlatTuple;
7545 FlatTuple<int, double, const char*> tuple = {};
7546 EXPECT_EQ(0, tuple.Get<0>());
7547 EXPECT_EQ(0.0, tuple.Get<1>());
7548 EXPECT_EQ(nullptr, tuple.Get<2>());
7550 tuple = FlatTuple<int, double, const char*>(
7551 testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo");
7552 EXPECT_EQ(7, tuple.Get<0>());
7553 EXPECT_EQ(3.2, tuple.Get<1>());
7554 EXPECT_EQ(std::string("Foo"), tuple.Get<2>());
7556 tuple.Get<1>() = 5.1;
7557 EXPECT_EQ(5.1, tuple.Get<1>());
7561 std::string AddIntToString(int i, const std::string& s) {
7562 return s + std::to_string(i);
7566 TEST(FlatTuple, Apply) {
7567 using testing::internal::FlatTuple;
7569 FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},
7573 EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
7574 return i == static_cast<int>(s.size());
7578 EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
7580 // Mutating operations.
7581 tuple.Apply([](int& i, std::string& s) {
7585 EXPECT_EQ(tuple.Get<0>(), 6);
7586 EXPECT_EQ(tuple.Get<1>(), "HelloHello");
7589 struct ConstructionCounting {
7590 ConstructionCounting() { ++default_ctor_calls; }
7591 ~ConstructionCounting() { ++dtor_calls; }
7592 ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }
7593 ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }
7594 ConstructionCounting& operator=(const ConstructionCounting&) {
7595 ++copy_assignment_calls;
7598 ConstructionCounting& operator=(ConstructionCounting&&) noexcept {
7599 ++move_assignment_calls;
7603 static void Reset() {
7604 default_ctor_calls = 0;
7606 copy_ctor_calls = 0;
7607 move_ctor_calls = 0;
7608 copy_assignment_calls = 0;
7609 move_assignment_calls = 0;
7612 static int default_ctor_calls;
7613 static int dtor_calls;
7614 static int copy_ctor_calls;
7615 static int move_ctor_calls;
7616 static int copy_assignment_calls;
7617 static int move_assignment_calls;
7620 int ConstructionCounting::default_ctor_calls = 0;
7621 int ConstructionCounting::dtor_calls = 0;
7622 int ConstructionCounting::copy_ctor_calls = 0;
7623 int ConstructionCounting::move_ctor_calls = 0;
7624 int ConstructionCounting::copy_assignment_calls = 0;
7625 int ConstructionCounting::move_assignment_calls = 0;
7627 TEST(FlatTuple, ConstructorCalls) {
7628 using testing::internal::FlatTuple;
7630 // Default construction.
7631 ConstructionCounting::Reset();
7632 { FlatTuple<ConstructionCounting> tuple; }
7633 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7634 EXPECT_EQ(ConstructionCounting::dtor_calls, 1);
7635 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7636 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7637 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7638 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7640 // Copy construction.
7641 ConstructionCounting::Reset();
7643 ConstructionCounting elem;
7644 FlatTuple<ConstructionCounting> tuple{
7645 testing::internal::FlatTupleConstructTag{}, elem};
7647 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7648 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7649 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);
7650 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7651 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7652 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7654 // Move construction.
7655 ConstructionCounting::Reset();
7657 FlatTuple<ConstructionCounting> tuple{
7658 testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}};
7660 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7661 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7662 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7663 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);
7664 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7665 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7668 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7670 ConstructionCounting::Reset();
7672 FlatTuple<ConstructionCounting> tuple;
7673 ConstructionCounting elem;
7674 tuple.Get<0>() = elem;
7676 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
7677 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7678 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7679 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7680 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);
7681 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7684 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7686 ConstructionCounting::Reset();
7688 FlatTuple<ConstructionCounting> tuple;
7689 tuple.Get<0>() = ConstructionCounting{};
7691 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
7692 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7693 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7694 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7695 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7696 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);
7698 ConstructionCounting::Reset();
7701 TEST(FlatTuple, ManyTypes) {
7702 using testing::internal::FlatTuple;
7704 // Instantiate FlatTuple with 257 ints.
7705 // Tests show that we can do it with thousands of elements, but very long
7706 // compile times makes it unusuitable for this test.
7707 #define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int,
7708 #define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8
7709 #define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16
7710 #define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32
7711 #define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64
7712 #define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128
7714 // Let's make sure that we can have a very long list of types without blowing
7715 // up the template instantiation depth.
7716 FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple;
7719 tuple.Get<99>() = 17;
7720 tuple.Get<256>() = 1000;
7721 EXPECT_EQ(7, tuple.Get<0>());
7722 EXPECT_EQ(17, tuple.Get<99>());
7723 EXPECT_EQ(1000, tuple.Get<256>());
7726 // Tests SkipPrefix().
7728 TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7729 const char* const str = "hello";
7731 const char* p = str;
7732 EXPECT_TRUE(SkipPrefix("", &p));
7736 EXPECT_TRUE(SkipPrefix("hell", &p));
7737 EXPECT_EQ(str + 4, p);
7740 TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7741 const char* const str = "world";
7743 const char* p = str;
7744 EXPECT_FALSE(SkipPrefix("W", &p));
7748 EXPECT_FALSE(SkipPrefix("world!", &p));
7752 // Tests ad_hoc_test_result().
7753 TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
7754 const testing::TestResult& test_result =
7755 testing::UnitTest::GetInstance()->ad_hoc_test_result();
7756 EXPECT_FALSE(test_result.Failed());
7759 class DynamicUnitTestFixture : public testing::Test {};
7761 class DynamicTest : public DynamicUnitTestFixture {
7762 void TestBody() override { EXPECT_TRUE(true); }
7765 auto* dynamic_test = testing::RegisterTest(
7766 "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__,
7767 __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });
7769 TEST(RegisterTest, WasRegistered) {
7770 auto* unittest = testing::UnitTest::GetInstance();
7771 for (int i = 0; i < unittest->total_test_suite_count(); ++i) {
7772 auto* tests = unittest->GetTestSuite(i);
7773 if (tests->name() != std::string("DynamicUnitTestFixture")) continue;
7774 for (int j = 0; j < tests->total_test_count(); ++j) {
7775 if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue;
7777 EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE");
7778 EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE");
7783 FAIL() << "Didn't find the test!";