cMHN 1.2
C++ library for learning MHNs with pRC
Loading...
Searching...
No Matches
gtest_unittest.cc
Go to the documentation of this file.
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
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
13// distribution.
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.
17//
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.
29
30//
31// Tests for Google Test itself. This verifies that the basic constructs of
32// Google Test work.
33
34#include "gtest/gtest.h"
35
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.
39TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
40 bool dummy =
41 GTEST_FLAG_GET(also_run_disabled_tests) ||
42 GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) ||
43 GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) ||
44 GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) ||
45 GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) ||
46 GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) ||
47 GTEST_FLAG_GET(repeat) > 0 ||
48 GTEST_FLAG_GET(recreate_environments_when_repeating) ||
49 GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) ||
50 GTEST_FLAG_GET(stack_trace_depth) > 0 ||
51 GTEST_FLAG_GET(stream_result_to) != "unknown" ||
52 GTEST_FLAG_GET(throw_on_failure);
53 EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
54}
55
56#include <limits.h> // For INT_MAX.
57#include <stdlib.h>
58#include <string.h>
59#include <time.h>
60
61#include <cstdint>
62#include <map>
63#include <memory>
64#include <ostream>
65#include <set>
66#include <stdexcept>
67#include <string>
68#include <type_traits>
69#include <unordered_set>
70#include <utility>
71#include <vector>
72
73#include "gtest/gtest-spi.h"
75
77 // The inner enable_if is to ensure invoking is_constructible doesn't fail.
78 // The outer enable_if is to ensure the overload resolution doesn't encounter
79 // an ambiguity.
80 template <
81 class T,
82 std::enable_if_t<
83 false, std::enable_if_t<std::is_constructible<T>::value, int>> = 0>
84 operator T() const; // NOLINT(google-explicit-constructor)
85};
87static_assert(sizeof(decltype(std::declval<ConvertibleGlobalType&>()
88 << 1)(*)()) > 0,
89 "error in operator<< overload resolution");
90
91namespace testing {
92namespace internal {
93
94#if GTEST_CAN_STREAM_RESULTS_
95
96class StreamingListenerTest : public Test {
97 public:
98 class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
99 public:
100 // Sends a string to the socket.
101 void Send(const std::string& message) override { output_ += message; }
102
103 std::string output_;
104 };
105
106 StreamingListenerTest()
107 : fake_sock_writer_(new FakeSocketWriter),
108 streamer_(fake_sock_writer_),
109 test_info_obj_("FooTest", "Bar", nullptr, nullptr,
110 CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {}
111
112 protected:
113 std::string* output() { return &(fake_sock_writer_->output_); }
114
115 FakeSocketWriter* const fake_sock_writer_;
116 StreamingListener streamer_;
117 UnitTest unit_test_;
118 TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test.
119};
120
121TEST_F(StreamingListenerTest, OnTestProgramEnd) {
122 *output() = "";
123 streamer_.OnTestProgramEnd(unit_test_);
124 EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
125}
126
127TEST_F(StreamingListenerTest, OnTestIterationEnd) {
128 *output() = "";
129 streamer_.OnTestIterationEnd(unit_test_, 42);
130 EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
131}
132
133TEST_F(StreamingListenerTest, OnTestSuiteStart) {
134 *output() = "";
135 streamer_.OnTestSuiteStart(TestSuite("FooTest", "Bar", nullptr, nullptr));
136 EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
137}
138
139TEST_F(StreamingListenerTest, OnTestSuiteEnd) {
140 *output() = "";
141 streamer_.OnTestSuiteEnd(TestSuite("FooTest", "Bar", nullptr, nullptr));
142 EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
143}
144
145TEST_F(StreamingListenerTest, OnTestStart) {
146 *output() = "";
147 streamer_.OnTestStart(test_info_obj_);
148 EXPECT_EQ("event=TestStart&name=Bar\n", *output());
149}
150
151TEST_F(StreamingListenerTest, OnTestEnd) {
152 *output() = "";
153 streamer_.OnTestEnd(test_info_obj_);
154 EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
155}
156
157TEST_F(StreamingListenerTest, OnTestPartResult) {
158 *output() = "";
159 streamer_.OnTestPartResult(TestPartResult(TestPartResult::kFatalFailure,
160 "foo.cc", 42, "failed=\n&%"));
161
162 // Meta characters in the failure message should be properly escaped.
163 EXPECT_EQ(
164 "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
165 *output());
166}
167
168#endif // GTEST_CAN_STREAM_RESULTS_
169
170// Provides access to otherwise private parts of the TestEventListeners class
171// that are needed to test it.
173 public:
175 return listeners->repeater();
176 }
177
179 TestEventListener* listener) {
180 listeners->SetDefaultResultPrinter(listener);
181 }
183 TestEventListener* listener) {
184 listeners->SetDefaultXmlGenerator(listener);
185 }
186
187 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
188 return listeners.EventForwardingEnabled();
189 }
190
192 listeners->SuppressEventForwarding(true);
193 }
194};
195
197 protected:
199
200 // Forwards to UnitTest::RecordProperty() to bypass access controls.
201 void UnitTestRecordProperty(const char* key, const std::string& value) {
202 unit_test_.RecordProperty(key, value);
203 }
204
206};
207
208} // namespace internal
209} // namespace testing
210
212using testing::AssertionResult;
217using testing::FloatLE;
221using testing::Message;
222using testing::ScopedFakeTestPartResultReporter;
224using testing::Test;
227using testing::TestPartResult;
228using testing::TestPartResultArray;
279
280#if GTEST_HAS_STREAM_REDIRECTION
283#endif
284
285#ifdef GTEST_IS_THREADSAFE
286using testing::internal::ThreadWithParam;
287#endif
288
289class TestingVector : public std::vector<int> {};
290
291::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) {
292 os << "{ ";
293 for (size_t i = 0; i < vector.size(); i++) {
294 os << vector[i] << " ";
295 }
296 os << "}";
297 return os;
298}
299
300// This line tests that we can define tests in an unnamed namespace.
301namespace {
302
303TEST(GetRandomSeedFromFlagTest, HandlesZero) {
304 const int seed = GetRandomSeedFromFlag(0);
305 EXPECT_LE(1, seed);
306 EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
307}
308
309TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
310 EXPECT_EQ(1, GetRandomSeedFromFlag(1));
311 EXPECT_EQ(2, GetRandomSeedFromFlag(2));
312 EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
313 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
314 GetRandomSeedFromFlag(kMaxRandomSeed));
315}
316
317TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
318 const int seed1 = GetRandomSeedFromFlag(-1);
319 EXPECT_LE(1, seed1);
320 EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
321
322 const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
323 EXPECT_LE(1, seed2);
324 EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
325}
326
327TEST(GetNextRandomSeedTest, WorksForValidInput) {
328 EXPECT_EQ(2, GetNextRandomSeed(1));
329 EXPECT_EQ(3, GetNextRandomSeed(2));
330 EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
331 GetNextRandomSeed(kMaxRandomSeed - 1));
332 EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
333
334 // We deliberately don't test GetNextRandomSeed() with invalid
335 // inputs, as that requires death tests, which are expensive. This
336 // is fine as GetNextRandomSeed() is internal and has a
337 // straightforward definition.
338}
339
340static void ClearCurrentTestPartResults() {
342 GetUnitTestImpl()->current_test_result());
343}
344
345// Tests GetTypeId.
346
347TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
348 EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
349 EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
350}
351
352class SubClassOfTest : public Test {};
353class AnotherSubClassOfTest : public Test {};
354
355TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
356 EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
357 EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
358 EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
359 EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
360 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
361 EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
362}
363
364// Verifies that GetTestTypeId() returns the same value, no matter it
365// is called from inside Google Test or outside of it.
366TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
367 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
368}
369
370// Tests CanonicalizeForStdLibVersioning.
371
372using ::testing::internal::CanonicalizeForStdLibVersioning;
373
374TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) {
375 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind"));
376 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_"));
377 EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo"));
378 EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x"));
379 EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x"));
380 EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x"));
381}
382
383TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
384 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind"));
385 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_"));
386
387 EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind"));
388 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_"));
389
390 EXPECT_EQ("std::bind",
391 CanonicalizeForStdLibVersioning("std::__google::bind"));
392 EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_"));
393}
394
395// Tests FormatTimeInMillisAsSeconds().
396
397TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
398 EXPECT_EQ("0.", FormatTimeInMillisAsSeconds(0));
399}
400
401TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
402 EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
403 EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
404 EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
405 EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
406 EXPECT_EQ("3.", FormatTimeInMillisAsSeconds(3000));
407 EXPECT_EQ("10.", FormatTimeInMillisAsSeconds(10000));
408 EXPECT_EQ("100.", FormatTimeInMillisAsSeconds(100000));
409 EXPECT_EQ("123.456", FormatTimeInMillisAsSeconds(123456));
410 EXPECT_EQ("1234567.89", FormatTimeInMillisAsSeconds(1234567890));
411}
412
413TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
414 EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
415 EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
416 EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
417 EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
418 EXPECT_EQ("-3.", FormatTimeInMillisAsSeconds(-3000));
419 EXPECT_EQ("-10.", FormatTimeInMillisAsSeconds(-10000));
420 EXPECT_EQ("-100.", FormatTimeInMillisAsSeconds(-100000));
421 EXPECT_EQ("-123.456", FormatTimeInMillisAsSeconds(-123456));
422 EXPECT_EQ("-1234567.89", FormatTimeInMillisAsSeconds(-1234567890));
423}
424
425// Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
426// for particular dates below was verified in Python using
427// datetime.datetime.fromutctimestamp(<timestamp>/1000).
428
429// FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
430// have to set up a particular timezone to obtain predictable results.
431class FormatEpochTimeInMillisAsIso8601Test : public Test {
432 public:
433 // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
434 // 32 bits, even when 64-bit integer types are available. We have to
435 // force the constants to have a 64-bit type here.
436 static const TimeInMillis kMillisPerSec = 1000;
437
438 private:
439 void SetUp() override {
440 saved_tz_.reset();
441
442 GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv: deprecated */)
443 if (const char* tz = getenv("TZ")) {
444 saved_tz_ = std::make_unique<std::string>(tz);
445 }
447
448 // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
449 // cannot use the local time zone because the function's output depends
450 // on the time zone.
451 SetTimeZone("UTC+00");
452 }
453
454 void TearDown() override {
455 SetTimeZone(saved_tz_ != nullptr ? saved_tz_->c_str() : nullptr);
456 saved_tz_.reset();
457 }
458
459 static void SetTimeZone(const char* time_zone) {
460 // tzset() distinguishes between the TZ variable being present and empty
461 // and not being present, so we have to consider the case of time_zone
462 // being NULL.
463#if defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW)
464 // ...Unless it's MSVC, whose standard library's _putenv doesn't
465 // distinguish between an empty and a missing variable.
466 const std::string env_var =
467 std::string("TZ=") + (time_zone ? time_zone : "");
468 _putenv(env_var.c_str());
469 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
470 tzset();
472#else
473#if defined(GTEST_OS_LINUX_ANDROID) && __ANDROID_API__ < 21
474 // Work around KitKat bug in tzset by setting "UTC" before setting "UTC+00".
475 // See https://github.com/android/ndk/issues/1604.
476 setenv("TZ", "UTC", 1);
477 tzset();
478#endif
479 if (time_zone) {
480 setenv(("TZ"), time_zone, 1);
481 } else {
482 unsetenv("TZ");
483 }
484 tzset();
485#endif
486 }
487
488 std::unique_ptr<std::string> saved_tz_; // Empty and null are different here
489};
490
491const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
492
493TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
494 EXPECT_EQ("2011-10-31T18:52:42.000",
495 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
496}
497
498TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
499 EXPECT_EQ("2011-10-31T18:52:42.234",
500 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
501}
502
503TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
504 EXPECT_EQ("2011-09-03T05:07:02.000",
505 FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
506}
507
508TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
509 EXPECT_EQ("2011-09-28T17:08:22.000",
510 FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
511}
512
513TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
514 EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
515}
516
517#ifdef __BORLANDC__
518// Silences warnings: "Condition is always true", "Unreachable code"
519#pragma option push -w-ccc -w-rch
520#endif
521
522// Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal
523// when the RHS is a pointer type.
524TEST(NullLiteralTest, LHSAllowsNullLiterals) {
525 EXPECT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
526 ASSERT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
527 EXPECT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
528 ASSERT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
529 EXPECT_EQ(nullptr, static_cast<void*>(nullptr));
530 ASSERT_EQ(nullptr, static_cast<void*>(nullptr));
531
532 const int* const p = nullptr;
533 EXPECT_EQ(0, p); // NOLINT
534 ASSERT_EQ(0, p); // NOLINT
535 EXPECT_EQ(NULL, p); // NOLINT
536 ASSERT_EQ(NULL, p); // NOLINT
537 EXPECT_EQ(nullptr, p);
538 ASSERT_EQ(nullptr, p);
539}
540
541struct ConvertToAll {
542 template <typename T>
543 operator T() const { // NOLINT
544 return T();
545 }
546};
547
548struct ConvertToPointer {
549 template <class T>
550 operator T*() const { // NOLINT
551 return nullptr;
552 }
553};
554
555struct ConvertToAllButNoPointers {
556 template <typename T,
557 typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0>
558 operator T() const { // NOLINT
559 return T();
560 }
561};
562
563struct MyType {};
564inline bool operator==(MyType const&, MyType const&) { return true; }
565
566TEST(NullLiteralTest, ImplicitConversion) {
567 EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr));
568#if !defined(__GNUC__) || defined(__clang__)
569 // Disabled due to GCC bug gcc.gnu.org/PR89580
570 EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr));
571#endif
572 EXPECT_EQ(ConvertToAll{}, MyType{});
573 EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{});
574}
575
576#ifdef __clang__
577#pragma clang diagnostic push
578#if __has_warning("-Wzero-as-null-pointer-constant")
579#pragma clang diagnostic error "-Wzero-as-null-pointer-constant"
580#endif
581#endif
582
583TEST(NullLiteralTest, NoConversionNoWarning) {
584 // Test that gtests detection and handling of null pointer constants
585 // doesn't trigger a warning when '0' isn't actually used as null.
586 EXPECT_EQ(0, 0);
587 ASSERT_EQ(0, 0);
588}
589
590#ifdef __clang__
591#pragma clang diagnostic pop
592#endif
593
594#ifdef __BORLANDC__
595// Restores warnings after previous "#pragma option push" suppressed them.
596#pragma option pop
597#endif
598
599//
600// Tests CodePointToUtf8().
601
602// Tests that the NUL character L'\0' is encoded correctly.
603TEST(CodePointToUtf8Test, CanEncodeNul) {
604 EXPECT_EQ("", CodePointToUtf8(L'\0'));
605}
606
607// Tests that ASCII characters are encoded correctly.
608TEST(CodePointToUtf8Test, CanEncodeAscii) {
609 EXPECT_EQ("a", CodePointToUtf8(L'a'));
610 EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
611 EXPECT_EQ("&", CodePointToUtf8(L'&'));
612 EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
613}
614
615// Tests that Unicode code-points that have 8 to 11 bits are encoded
616// as 110xxxxx 10xxxxxx.
617TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
618 // 000 1101 0011 => 110-00011 10-010011
619 EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
620
621 // 101 0111 0110 => 110-10101 10-110110
622 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
623 // in wide strings and wide chars. In order to accommodate them, we have to
624 // introduce such character constants as integers.
625 EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576)));
626}
627
628// Tests that Unicode code-points that have 12 to 16 bits are encoded
629// as 1110xxxx 10xxxxxx 10xxxxxx.
630TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
631 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
632 EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
633
634 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
635 EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
636}
637
638#if !GTEST_WIDE_STRING_USES_UTF16_
639// Tests in this group require a wchar_t to hold > 16 bits, and thus
640// are skipped on Windows, and Cygwin, where a wchar_t is
641// 16-bit wide. This code may not compile on those systems.
642
643// Tests that Unicode code-points that have 17 to 21 bits are encoded
644// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
645TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
646 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
647 EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
648
649 // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
650 EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
651
652 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
653 EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
654}
655
656// Tests that encoding an invalid code-point generates the expected result.
657TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
658 EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
659}
660
661#endif // !GTEST_WIDE_STRING_USES_UTF16_
662
663// Tests WideStringToUtf8().
664
665// Tests that the NUL character L'\0' is encoded correctly.
666TEST(WideStringToUtf8Test, CanEncodeNul) {
667 EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
668 EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
669}
670
671// Tests that ASCII strings are encoded correctly.
672TEST(WideStringToUtf8Test, CanEncodeAscii) {
673 EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
674 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
675 EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
676 EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
677}
678
679// Tests that Unicode code-points that have 8 to 11 bits are encoded
680// as 110xxxxx 10xxxxxx.
681TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
682 // 000 1101 0011 => 110-00011 10-010011
683 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
684 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
685
686 // 101 0111 0110 => 110-10101 10-110110
687 const wchar_t s[] = {0x576, '\0'};
688 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
689 EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
690}
691
692// Tests that Unicode code-points that have 12 to 16 bits are encoded
693// as 1110xxxx 10xxxxxx 10xxxxxx.
694TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
695 // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
696 const wchar_t s1[] = {0x8D3, '\0'};
697 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
698 EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
699
700 // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
701 const wchar_t s2[] = {0xC74D, '\0'};
702 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
703 EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
704}
705
706// Tests that the conversion stops when the function encounters \0 character.
707TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
708 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
709}
710
711// Tests that the conversion stops when the function reaches the limit
712// specified by the 'length' parameter.
713TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
714 EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
715}
716
717#if !GTEST_WIDE_STRING_USES_UTF16_
718// Tests that Unicode code-points that have 17 to 21 bits are encoded
719// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
720// on the systems using UTF-16 encoding.
721TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
722 // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
723 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
724 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
725
726 // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
727 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
728 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
729}
730
731// Tests that encoding an invalid code-point generates the expected result.
732TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
733 EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
734 WideStringToUtf8(L"\xABCDFF", -1).c_str());
735}
736#else // !GTEST_WIDE_STRING_USES_UTF16_
737// Tests that surrogate pairs are encoded correctly on the systems using
738// UTF-16 encoding in the wide strings.
739TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
740 const wchar_t s[] = {0xD801, 0xDC00, '\0'};
741 EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
742}
743
744// Tests that encoding an invalid UTF-16 surrogate pair
745// generates the expected result.
746TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
747 // Leading surrogate is at the end of the string.
748 const wchar_t s1[] = {0xD800, '\0'};
749 EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
750 // Leading surrogate is not followed by the trailing surrogate.
751 const wchar_t s2[] = {0xD800, 'M', '\0'};
752 EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
753 // Trailing surrogate appearas without a leading surrogate.
754 const wchar_t s3[] = {0xDC00, 'P', 'Q', 'R', '\0'};
755 EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
756}
757#endif // !GTEST_WIDE_STRING_USES_UTF16_
758
759// Tests that codepoint concatenation works correctly.
760#if !GTEST_WIDE_STRING_USES_UTF16_
761TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
762 const wchar_t s[] = {0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
764 "\xF4\x88\x98\xB4"
765 "\xEC\x9D\x8D"
766 "\n"
767 "\xD5\xB6"
768 "\xE0\xA3\x93"
769 "\xF4\x88\x98\xB4",
770 WideStringToUtf8(s, -1).c_str());
771}
772#else
773TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
774 const wchar_t s[] = {0xC74D, '\n', 0x576, 0x8D3, '\0'};
776 "\xEC\x9D\x8D"
777 "\n"
778 "\xD5\xB6"
779 "\xE0\xA3\x93",
780 WideStringToUtf8(s, -1).c_str());
781}
782#endif // !GTEST_WIDE_STRING_USES_UTF16_
783
784// Tests the Random class.
785
786TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
787 testing::internal::Random random(42);
788 EXPECT_DEATH_IF_SUPPORTED(random.Generate(0),
789 "Cannot generate a number in the range \\[0, 0\\)");
791 random.Generate(testing::internal::Random::kMaxRange + 1),
792 "Generation of a number in \\[0, 2147483649\\) was requested, "
793 "but this can only generate numbers in \\[0, 2147483648\\)");
794}
795
796TEST(RandomTest, GeneratesNumbersWithinRange) {
797 constexpr uint32_t kRange = 10000;
798 testing::internal::Random random(12345);
799 for (int i = 0; i < 10; i++) {
800 EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
801 }
802
804 for (int i = 0; i < 10; i++) {
805 EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
806 }
807}
808
809TEST(RandomTest, RepeatsWhenReseeded) {
810 constexpr int kSeed = 123;
811 constexpr int kArraySize = 10;
812 constexpr uint32_t kRange = 10000;
813 uint32_t values[kArraySize];
814
815 testing::internal::Random random(kSeed);
816 for (int i = 0; i < kArraySize; i++) {
817 values[i] = random.Generate(kRange);
818 }
819
820 random.Reseed(kSeed);
821 for (int i = 0; i < kArraySize; i++) {
822 EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
823 }
824}
825
826// Tests STL container utilities.
827
828// Tests CountIf().
829
830static bool IsPositive(int n) { return n > 0; }
831
832TEST(ContainerUtilityTest, CountIf) {
833 std::vector<int> v;
834 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
835
836 v.push_back(-1);
837 v.push_back(0);
838 EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
839
840 v.push_back(2);
841 v.push_back(-10);
842 v.push_back(10);
843 EXPECT_EQ(2, CountIf(v, IsPositive));
844}
845
846// Tests ForEach().
847
848static int g_sum = 0;
849static void Accumulate(int n) { g_sum += n; }
850
851TEST(ContainerUtilityTest, ForEach) {
852 std::vector<int> v;
853 g_sum = 0;
854 ForEach(v, Accumulate);
855 EXPECT_EQ(0, g_sum); // Works for an empty container;
856
857 g_sum = 0;
858 v.push_back(1);
859 ForEach(v, Accumulate);
860 EXPECT_EQ(1, g_sum); // Works for a container with one element.
861
862 g_sum = 0;
863 v.push_back(20);
864 v.push_back(300);
865 ForEach(v, Accumulate);
866 EXPECT_EQ(321, g_sum);
867}
868
869// Tests GetElementOr().
870TEST(ContainerUtilityTest, GetElementOr) {
871 std::vector<char> a;
872 EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
873
874 a.push_back('a');
875 a.push_back('b');
876 EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
877 EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
878 EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
879 EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
880}
881
882TEST(ContainerUtilityDeathTest, ShuffleRange) {
883 std::vector<int> a;
884 a.push_back(0);
885 a.push_back(1);
886 a.push_back(2);
888
890 ShuffleRange(&random, -1, 1, &a),
891 "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
893 ShuffleRange(&random, 4, 4, &a),
894 "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
896 ShuffleRange(&random, 3, 2, &a),
897 "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
899 ShuffleRange(&random, 3, 4, &a),
900 "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
901}
902
903class VectorShuffleTest : public Test {
904 protected:
905 static const size_t kVectorSize = 20;
906
907 VectorShuffleTest() : random_(1) {
908 for (int i = 0; i < static_cast<int>(kVectorSize); i++) {
909 vector_.push_back(i);
910 }
911 }
912
913 static bool VectorIsCorrupt(const TestingVector& vector) {
914 if (kVectorSize != vector.size()) {
915 return true;
916 }
917
918 bool found_in_vector[kVectorSize] = {false};
919 for (size_t i = 0; i < vector.size(); i++) {
920 const int e = vector[i];
921 if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {
922 return true;
923 }
924 found_in_vector[e] = true;
925 }
926
927 // Vector size is correct, elements' range is correct, no
928 // duplicate elements. Therefore no corruption has occurred.
929 return false;
930 }
931
932 static bool VectorIsNotCorrupt(const TestingVector& vector) {
933 return !VectorIsCorrupt(vector);
934 }
935
936 static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
937 for (int i = begin; i < end; i++) {
938 if (i != vector[static_cast<size_t>(i)]) {
939 return true;
940 }
941 }
942 return false;
943 }
944
945 static bool RangeIsUnshuffled(const TestingVector& vector, int begin,
946 int end) {
947 return !RangeIsShuffled(vector, begin, end);
948 }
949
950 static bool VectorIsShuffled(const TestingVector& vector) {
951 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
952 }
953
954 static bool VectorIsUnshuffled(const TestingVector& vector) {
955 return !VectorIsShuffled(vector);
956 }
957
959 TestingVector vector_;
960}; // class VectorShuffleTest
961
962const size_t VectorShuffleTest::kVectorSize;
963
964TEST_F(VectorShuffleTest, HandlesEmptyRange) {
965 // Tests an empty range at the beginning...
966 ShuffleRange(&random_, 0, 0, &vector_);
967 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
968 ASSERT_PRED1(VectorIsUnshuffled, vector_);
969
970 // ...in the middle...
971 ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2, &vector_);
972 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
973 ASSERT_PRED1(VectorIsUnshuffled, vector_);
974
975 // ...at the end...
976 ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
977 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
978 ASSERT_PRED1(VectorIsUnshuffled, vector_);
979
980 // ...and past the end.
981 ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
982 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
983 ASSERT_PRED1(VectorIsUnshuffled, vector_);
984}
985
986TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
987 // Tests a size one range at the beginning...
988 ShuffleRange(&random_, 0, 1, &vector_);
989 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
990 ASSERT_PRED1(VectorIsUnshuffled, vector_);
991
992 // ...in the middle...
993 ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2 + 1, &vector_);
994 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
995 ASSERT_PRED1(VectorIsUnshuffled, vector_);
996
997 // ...and at the end.
998 ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
999 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1000 ASSERT_PRED1(VectorIsUnshuffled, vector_);
1001}
1002
1003// Because we use our own random number generator and a fixed seed,
1004// we can guarantee that the following "random" tests will succeed.
1005
1006TEST_F(VectorShuffleTest, ShufflesEntireVector) {
1007 Shuffle(&random_, &vector_);
1008 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1009 EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
1010
1011 // Tests the first and last elements in particular to ensure that
1012 // there are no off-by-one problems in our shuffle algorithm.
1013 EXPECT_NE(0, vector_[0]);
1014 EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);
1015}
1016
1017TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
1018 const int kRangeSize = kVectorSize / 2;
1019
1020 ShuffleRange(&random_, 0, kRangeSize, &vector_);
1021
1022 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1023 EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
1024 EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize,
1025 static_cast<int>(kVectorSize));
1026}
1027
1028TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
1029 const int kRangeSize = kVectorSize / 2;
1030 ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
1031
1032 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1033 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1034 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize,
1035 static_cast<int>(kVectorSize));
1036}
1037
1038TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
1039 const int kRangeSize = static_cast<int>(kVectorSize) / 3;
1040 ShuffleRange(&random_, kRangeSize, 2 * kRangeSize, &vector_);
1041
1042 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1043 EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
1044 EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2 * kRangeSize);
1045 EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,
1046 static_cast<int>(kVectorSize));
1047}
1048
1049TEST_F(VectorShuffleTest, ShufflesRepeatably) {
1050 TestingVector vector2;
1051 for (size_t i = 0; i < kVectorSize; i++) {
1052 vector2.push_back(static_cast<int>(i));
1053 }
1054
1055 random_.Reseed(1234);
1056 Shuffle(&random_, &vector_);
1057 random_.Reseed(1234);
1058 Shuffle(&random_, &vector2);
1059
1060 ASSERT_PRED1(VectorIsNotCorrupt, vector_);
1061 ASSERT_PRED1(VectorIsNotCorrupt, vector2);
1062
1063 for (size_t i = 0; i < kVectorSize; i++) {
1064 EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
1065 }
1066}
1067
1068// Tests the size of the AssertHelper class.
1069
1070TEST(AssertHelperTest, AssertHelperIsSmall) {
1071 // To avoid breaking clients that use lots of assertions in one
1072 // function, we cannot grow the size of AssertHelper.
1073 EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
1074}
1075
1076// Tests String::EndsWithCaseInsensitive().
1077TEST(StringTest, EndsWithCaseInsensitive) {
1078 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
1079 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
1080 EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
1081 EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
1082
1083 EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
1084 EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
1085 EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
1086}
1087
1088// C++Builder's preprocessor is buggy; it fails to expand macros that
1089// appear in macro parameters after wide char literals. Provide an alias
1090// for NULL as a workaround.
1091static const wchar_t* const kNull = nullptr;
1092
1093// Tests String::CaseInsensitiveWideCStringEquals
1094TEST(StringTest, CaseInsensitiveWideCStringEquals) {
1095 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr));
1096 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
1097 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
1098 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
1099 EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
1100 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
1101 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
1102 EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
1103}
1104
1105#ifdef GTEST_OS_WINDOWS
1106
1107// Tests String::ShowWideCString().
1108TEST(StringTest, ShowWideCString) {
1109 EXPECT_STREQ("(null)", String::ShowWideCString(NULL).c_str());
1110 EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
1111 EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
1112}
1113
1114#ifdef GTEST_OS_WINDOWS_MOBILE
1115TEST(StringTest, AnsiAndUtf16Null) {
1116 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1117 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1118}
1119
1120TEST(StringTest, AnsiAndUtf16ConvertBasic) {
1121 const char* ansi = String::Utf16ToAnsi(L"str");
1122 EXPECT_STREQ("str", ansi);
1123 delete[] ansi;
1124 const WCHAR* utf16 = String::AnsiToUtf16("str");
1125 EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
1126 delete[] utf16;
1127}
1128
1129TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
1130 const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
1131 EXPECT_STREQ(".:\\ \"*?", ansi);
1132 delete[] ansi;
1133 const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
1134 EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
1135 delete[] utf16;
1136}
1137#endif // GTEST_OS_WINDOWS_MOBILE
1138
1139#endif // GTEST_OS_WINDOWS
1140
1141// Tests TestProperty construction.
1142TEST(TestPropertyTest, StringValue) {
1143 TestProperty property("key", "1");
1144 EXPECT_STREQ("key", property.key());
1145 EXPECT_STREQ("1", property.value());
1146}
1147
1148// Tests TestProperty replacing a value.
1149TEST(TestPropertyTest, ReplaceStringValue) {
1150 TestProperty property("key", "1");
1151 EXPECT_STREQ("1", property.value());
1152 property.SetValue("2");
1153 EXPECT_STREQ("2", property.value());
1154}
1155
1156// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
1157// functions (i.e. their definitions cannot be inlined at the call
1158// sites), or C++Builder won't compile the code.
1159static void AddFatalFailure() { FAIL() << "Expected fatal failure."; }
1160
1161static void AddNonfatalFailure() {
1162 ADD_FAILURE() << "Expected non-fatal failure.";
1163}
1164
1165class ScopedFakeTestPartResultReporterTest : public Test {
1166 public: // Must be public and not protected due to a bug in g++ 3.4.2.
1167 enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
1168 static void AddFailure(FailureMode failure) {
1169 if (failure == FATAL_FAILURE) {
1170 AddFatalFailure();
1171 } else {
1172 AddNonfatalFailure();
1173 }
1174 }
1175};
1176
1177// Tests that ScopedFakeTestPartResultReporter intercepts test
1178// failures.
1179TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
1180 TestPartResultArray results;
1181 {
1182 ScopedFakeTestPartResultReporter reporter(
1183 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1184 &results);
1185 AddFailure(NONFATAL_FAILURE);
1186 AddFailure(FATAL_FAILURE);
1187 }
1188
1189 EXPECT_EQ(2, results.size());
1190 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1191 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1192}
1193
1194TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
1195 TestPartResultArray results;
1196 {
1197 // Tests, that the deprecated constructor still works.
1198 ScopedFakeTestPartResultReporter reporter(&results);
1199 AddFailure(NONFATAL_FAILURE);
1200 }
1201 EXPECT_EQ(1, results.size());
1202}
1203
1204#ifdef GTEST_IS_THREADSAFE
1205
1206class ScopedFakeTestPartResultReporterWithThreadsTest
1207 : public ScopedFakeTestPartResultReporterTest {
1208 protected:
1209 static void AddFailureInOtherThread(FailureMode failure) {
1210 ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
1211 thread.Join();
1212 }
1213};
1214
1215TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
1216 InterceptsTestFailuresInAllThreads) {
1217 TestPartResultArray results;
1218 {
1219 ScopedFakeTestPartResultReporter reporter(
1220 ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
1221 AddFailure(NONFATAL_FAILURE);
1222 AddFailure(FATAL_FAILURE);
1223 AddFailureInOtherThread(NONFATAL_FAILURE);
1224 AddFailureInOtherThread(FATAL_FAILURE);
1225 }
1226
1227 EXPECT_EQ(4, results.size());
1228 EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
1229 EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
1230 EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
1231 EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
1232}
1233
1234#endif // GTEST_IS_THREADSAFE
1235
1236// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
1237// work even if the failure is generated in a called function rather than
1238// the current context.
1239
1240typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
1241
1242TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1243 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
1244}
1245
1246TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1247 EXPECT_FATAL_FAILURE(AddFatalFailure(),
1248 ::std::string("Expected fatal failure."));
1249}
1250
1251TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
1252 // We have another test below to verify that the macro catches fatal
1253 // failures generated on another thread.
1254 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
1255 "Expected fatal failure.");
1256}
1257
1258#ifdef __BORLANDC__
1259// Silences warnings: "Condition is always true"
1260#pragma option push -w-ccc
1261#endif
1262
1263// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
1264// function even when the statement in it contains ASSERT_*.
1265
1266int NonVoidFunction() {
1269 return 0;
1270}
1271
1272TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
1273 NonVoidFunction();
1274}
1275
1276// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
1277// current function even though 'statement' generates a fatal failure.
1278
1279void DoesNotAbortHelper(bool* aborted) {
1282
1283 *aborted = false;
1284}
1285
1286#ifdef __BORLANDC__
1287// Restores warnings after previous "#pragma option push" suppressed them.
1288#pragma option pop
1289#endif
1290
1291TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
1292 bool aborted = true;
1293 DoesNotAbortHelper(&aborted);
1294 EXPECT_FALSE(aborted);
1295}
1296
1297// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
1298// statement that contains a macro which expands to code containing an
1299// unprotected comma.
1300
1301static int global_var = 0;
1302#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
1303
1304TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1305#ifndef __BORLANDC__
1306 // ICE's in C++Builder.
1308 {
1310 AddFatalFailure();
1311 },
1312 "");
1313#endif
1314
1316 {
1318 AddFatalFailure();
1319 },
1320 "");
1321}
1322
1323// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
1324
1325typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
1326
1327TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1328 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), "Expected non-fatal failure.");
1329}
1330
1331TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1332 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1333 ::std::string("Expected non-fatal failure."));
1334}
1335
1336TEST_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.");
1341}
1342
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.
1346TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
1348 {
1350 AddNonfatalFailure();
1351 },
1352 "");
1353
1355 {
1357 AddNonfatalFailure();
1358 },
1359 "");
1360}
1361
1362#ifdef GTEST_IS_THREADSAFE
1363
1364typedef ScopedFakeTestPartResultReporterWithThreadsTest
1365 ExpectFailureWithThreadsTest;
1366
1367TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1368 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1369 "Expected fatal failure.");
1370}
1371
1372TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
1374 AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
1375}
1376
1377#endif // GTEST_IS_THREADSAFE
1378
1379// Tests the TestProperty class.
1380
1381TEST(TestPropertyTest, ConstructorWorks) {
1382 const TestProperty property("key", "value");
1383 EXPECT_STREQ("key", property.key());
1384 EXPECT_STREQ("value", property.value());
1385}
1386
1387TEST(TestPropertyTest, SetValue) {
1388 TestProperty property("key", "value_1");
1389 EXPECT_STREQ("key", property.key());
1390 property.SetValue("value_2");
1391 EXPECT_STREQ("key", property.key());
1392 EXPECT_STREQ("value_2", property.value());
1393}
1394
1395// Tests the TestResult class
1396
1397// The test fixture for testing TestResult.
1398class TestResultTest : public Test {
1399 protected:
1400 typedef std::vector<TestPartResult> TPRVector;
1401
1402 // We make use of 2 TestPartResult objects,
1403 TestPartResult *pr1, *pr2;
1404
1405 // ... and 3 TestResult objects.
1406 TestResult *r0, *r1, *r2;
1407
1408 void SetUp() override {
1409 // pr1 is for success.
1410 pr1 = new TestPartResult(TestPartResult::kSuccess, "foo/bar.cc", 10,
1411 "Success!");
1412
1413 // pr2 is for fatal failure.
1414 pr2 = new TestPartResult(TestPartResult::kFatalFailure, "foo/bar.cc",
1415 -1, // This line number means "unknown"
1416 "Failure!");
1417
1418 // Creates the TestResult objects.
1419 r0 = new TestResult();
1420 r1 = new TestResult();
1421 r2 = new TestResult();
1422
1423 // In order to test TestResult, we need to modify its internal
1424 // state, in particular the TestPartResult vector it holds.
1425 // test_part_results() returns a const reference to this vector.
1426 // We cast it to a non-const object s.t. it can be modified
1427 TPRVector* results1 =
1428 const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r1));
1429 TPRVector* results2 =
1430 const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r2));
1431
1432 // r0 is an empty TestResult.
1433
1434 // r1 contains a single SUCCESS TestPartResult.
1435 results1->push_back(*pr1);
1436
1437 // r2 contains a SUCCESS, and a FAILURE.
1438 results2->push_back(*pr1);
1439 results2->push_back(*pr2);
1440 }
1441
1442 void TearDown() override {
1443 delete pr1;
1444 delete pr2;
1445
1446 delete r0;
1447 delete r1;
1448 delete r2;
1449 }
1450
1451 // Helper that compares two TestPartResults.
1452 static void CompareTestPartResult(const TestPartResult& expected,
1453 const TestPartResult& actual) {
1454 EXPECT_EQ(expected.type(), actual.type());
1455 EXPECT_STREQ(expected.file_name(), actual.file_name());
1456 EXPECT_EQ(expected.line_number(), actual.line_number());
1457 EXPECT_STREQ(expected.summary(), actual.summary());
1458 EXPECT_STREQ(expected.message(), actual.message());
1459 EXPECT_EQ(expected.passed(), actual.passed());
1460 EXPECT_EQ(expected.failed(), actual.failed());
1461 EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
1462 EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
1463 }
1464};
1465
1466// Tests TestResult::total_part_count().
1467TEST_F(TestResultTest, total_part_count) {
1468 ASSERT_EQ(0, r0->total_part_count());
1469 ASSERT_EQ(1, r1->total_part_count());
1470 ASSERT_EQ(2, r2->total_part_count());
1471}
1472
1473// Tests TestResult::Passed().
1474TEST_F(TestResultTest, Passed) {
1475 ASSERT_TRUE(r0->Passed());
1476 ASSERT_TRUE(r1->Passed());
1477 ASSERT_FALSE(r2->Passed());
1478}
1479
1480// Tests TestResult::Failed().
1481TEST_F(TestResultTest, Failed) {
1482 ASSERT_FALSE(r0->Failed());
1483 ASSERT_FALSE(r1->Failed());
1484 ASSERT_TRUE(r2->Failed());
1485}
1486
1487// Tests TestResult::GetTestPartResult().
1488
1489typedef TestResultTest TestResultDeathTest;
1490
1491TEST_F(TestResultDeathTest, GetTestPartResult) {
1492 CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
1493 CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
1496}
1497
1498// Tests TestResult has no properties when none are added.
1499TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
1500 TestResult test_result;
1501 ASSERT_EQ(0, test_result.test_property_count());
1502}
1503
1504// Tests TestResult has the expected property when added.
1505TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
1506 TestResult test_result;
1507 TestProperty property("key_1", "1");
1508 TestResultAccessor::RecordProperty(&test_result, "testcase", property);
1509 ASSERT_EQ(1, test_result.test_property_count());
1510 const TestProperty& actual_property = test_result.GetTestProperty(0);
1511 EXPECT_STREQ("key_1", actual_property.key());
1512 EXPECT_STREQ("1", actual_property.value());
1513}
1514
1515// Tests TestResult has multiple properties when added.
1516TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
1517 TestResult test_result;
1518 TestProperty property_1("key_1", "1");
1519 TestProperty property_2("key_2", "2");
1520 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1521 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1522 ASSERT_EQ(2, test_result.test_property_count());
1523 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1524 EXPECT_STREQ("key_1", actual_property_1.key());
1525 EXPECT_STREQ("1", actual_property_1.value());
1526
1527 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1528 EXPECT_STREQ("key_2", actual_property_2.key());
1529 EXPECT_STREQ("2", actual_property_2.value());
1530}
1531
1532// Tests TestResult::RecordProperty() overrides values for duplicate keys.
1533TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
1534 TestResult test_result;
1535 TestProperty property_1_1("key_1", "1");
1536 TestProperty property_2_1("key_2", "2");
1537 TestProperty property_1_2("key_1", "12");
1538 TestProperty property_2_2("key_2", "22");
1539 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
1540 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
1541 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
1542 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
1543
1544 ASSERT_EQ(2, test_result.test_property_count());
1545 const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
1546 EXPECT_STREQ("key_1", actual_property_1.key());
1547 EXPECT_STREQ("12", actual_property_1.value());
1548
1549 const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
1550 EXPECT_STREQ("key_2", actual_property_2.key());
1551 EXPECT_STREQ("22", actual_property_2.value());
1552}
1553
1554// Tests TestResult::GetTestProperty().
1555TEST(TestResultPropertyTest, GetTestProperty) {
1556 TestResult test_result;
1557 TestProperty property_1("key_1", "1");
1558 TestProperty property_2("key_2", "2");
1559 TestProperty property_3("key_3", "3");
1560 TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
1561 TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
1562 TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
1563
1564 const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
1565 const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
1566 const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
1567
1568 EXPECT_STREQ("key_1", fetched_property_1.key());
1569 EXPECT_STREQ("1", fetched_property_1.value());
1570
1571 EXPECT_STREQ("key_2", fetched_property_2.key());
1572 EXPECT_STREQ("2", fetched_property_2.value());
1573
1574 EXPECT_STREQ("key_3", fetched_property_3.key());
1575 EXPECT_STREQ("3", fetched_property_3.value());
1576
1577 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
1578 EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
1579}
1580
1581// Tests the Test class.
1582//
1583// It's difficult to test every public method of this class (we are
1584// already stretching the limit of Google Test by using it to test itself!).
1585// Fortunately, we don't have to do that, as we are already testing
1586// the functionalities of the Test class extensively by using Google Test
1587// alone.
1588//
1589// Therefore, this section only contains one test.
1590
1591// Tests that GTestFlagSaver works on Windows and Mac.
1592
1593class GTestFlagSaverTest : public Test {
1594 protected:
1595 // Saves the Google Test flags such that we can restore them later, and
1596 // then sets them to their default values. This will be called
1597 // before the first test in this test case is run.
1598 static void SetUpTestSuite() {
1599 saver_ = new GTestFlagSaver;
1600
1601 GTEST_FLAG_SET(also_run_disabled_tests, false);
1602 GTEST_FLAG_SET(break_on_failure, false);
1603 GTEST_FLAG_SET(catch_exceptions, false);
1604 GTEST_FLAG_SET(death_test_use_fork, false);
1605 GTEST_FLAG_SET(color, "auto");
1606 GTEST_FLAG_SET(fail_fast, false);
1607 GTEST_FLAG_SET(filter, "");
1608 GTEST_FLAG_SET(list_tests, false);
1609 GTEST_FLAG_SET(output, "");
1610 GTEST_FLAG_SET(brief, false);
1611 GTEST_FLAG_SET(print_time, true);
1612 GTEST_FLAG_SET(random_seed, 0);
1613 GTEST_FLAG_SET(repeat, 1);
1614 GTEST_FLAG_SET(recreate_environments_when_repeating, true);
1615 GTEST_FLAG_SET(shuffle, false);
1616 GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
1617 GTEST_FLAG_SET(stream_result_to, "");
1618 GTEST_FLAG_SET(throw_on_failure, false);
1619 }
1620
1621 // Restores the Google Test flags that the tests have modified. This will
1622 // be called after the last test in this test case is run.
1623 static void TearDownTestSuite() {
1624 delete saver_;
1625 saver_ = nullptr;
1626 }
1627
1628 // Verifies that the Google Test flags have their default values, and then
1629 // modifies each of them.
1630 void VerifyAndModifyFlags() {
1631 EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests));
1632 EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure));
1633 EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions));
1634 EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str());
1635 EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork));
1636 EXPECT_FALSE(GTEST_FLAG_GET(fail_fast));
1637 EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str());
1638 EXPECT_FALSE(GTEST_FLAG_GET(list_tests));
1639 EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str());
1641 EXPECT_TRUE(GTEST_FLAG_GET(print_time));
1642 EXPECT_EQ(0, GTEST_FLAG_GET(random_seed));
1643 EXPECT_EQ(1, GTEST_FLAG_GET(repeat));
1644 EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating));
1645 EXPECT_FALSE(GTEST_FLAG_GET(shuffle));
1646 EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth));
1647 EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str());
1648 EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure));
1649
1650 GTEST_FLAG_SET(also_run_disabled_tests, true);
1651 GTEST_FLAG_SET(break_on_failure, true);
1652 GTEST_FLAG_SET(catch_exceptions, true);
1653 GTEST_FLAG_SET(color, "no");
1654 GTEST_FLAG_SET(death_test_use_fork, true);
1655 GTEST_FLAG_SET(fail_fast, true);
1656 GTEST_FLAG_SET(filter, "abc");
1657 GTEST_FLAG_SET(list_tests, true);
1658 GTEST_FLAG_SET(output, "xml:foo.xml");
1659 GTEST_FLAG_SET(brief, true);
1660 GTEST_FLAG_SET(print_time, false);
1661 GTEST_FLAG_SET(random_seed, 1);
1662 GTEST_FLAG_SET(repeat, 100);
1663 GTEST_FLAG_SET(recreate_environments_when_repeating, false);
1664 GTEST_FLAG_SET(shuffle, true);
1665 GTEST_FLAG_SET(stack_trace_depth, 1);
1666 GTEST_FLAG_SET(stream_result_to, "localhost:1234");
1667 GTEST_FLAG_SET(throw_on_failure, true);
1668 }
1669
1670 private:
1671 // For saving Google Test flags during this test case.
1672 static GTestFlagSaver* saver_;
1673};
1674
1675GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;
1676
1677// Google Test doesn't guarantee the order of tests. The following two
1678// tests are designed to work regardless of their order.
1679
1680// Modifies the Google Test flags in the test body.
1681TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); }
1682
1683// Verifies that the Google Test flags in the body of the previous test were
1684// restored to their original values.
1685TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); }
1686
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.
1690static void SetEnv(const char* name, const char* value) {
1691#ifdef GTEST_OS_WINDOWS_MOBILE
1692 // Environment variables are not supported on Windows CE.
1693 return;
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;
1699
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];
1705 }
1706 added_env[name] =
1707 new std::string((Message() << name << "=" << value).GetString());
1708
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()));
1713 delete prev_env;
1714#elif defined(GTEST_OS_WINDOWS) // If we are on Windows proper.
1715 _putenv((Message() << name << "=" << value).GetString().c_str());
1716#else
1717 if (*value == '\0') {
1718 unsetenv(name);
1719 } else {
1720 setenv(name, value, 1);
1721 }
1722#endif // GTEST_OS_WINDOWS_MOBILE
1723}
1724
1725#ifndef GTEST_OS_WINDOWS_MOBILE
1726// Environment variables are not supported on Windows CE.
1727
1729
1730// Tests Int32FromGTestEnv().
1731
1732// Tests that Int32FromGTestEnv() returns the default value when the
1733// environment variable is not set.
1734TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
1735 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
1736 EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
1737}
1738
1739#if !defined(GTEST_GET_INT32_FROM_ENV_)
1740
1741// Tests that Int32FromGTestEnv() returns the default value when the
1742// environment variable overflows as an Int32.
1743TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
1744 printf("(expecting 2 warnings)\n");
1745
1746 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
1747 EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
1748
1749 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
1750 EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
1751}
1752
1753// Tests that Int32FromGTestEnv() returns the default value when the
1754// environment variable does not represent a valid decimal integer.
1755TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
1756 printf("(expecting 2 warnings)\n");
1757
1758 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
1759 EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
1760
1761 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
1762 EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
1763}
1764
1765#endif // !defined(GTEST_GET_INT32_FROM_ENV_)
1766
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.
1770TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
1771 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
1772 EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
1773
1774 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
1775 EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
1776}
1777#endif // !GTEST_OS_WINDOWS_MOBILE
1778
1779// Tests ParseFlag().
1780
1781// Tests that ParseInt32Flag() returns false and doesn't change the
1782// output value when the flag has wrong format
1783TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
1784 int32_t value = 123;
1785 EXPECT_FALSE(ParseFlag("--a=100", "b", &value));
1786 EXPECT_EQ(123, value);
1787
1788 EXPECT_FALSE(ParseFlag("a=100", "a", &value));
1789 EXPECT_EQ(123, value);
1790}
1791
1792// Tests that ParseFlag() returns false and doesn't change the
1793// output value when the flag overflows as an Int32.
1794TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
1795 printf("(expecting 2 warnings)\n");
1796
1797 int32_t value = 123;
1798 EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value));
1799 EXPECT_EQ(123, value);
1800
1801 EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value));
1802 EXPECT_EQ(123, value);
1803}
1804
1805// Tests that ParseInt32Flag() returns false and doesn't change the
1806// output value when the flag does not represent a valid decimal
1807// integer.
1808TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
1809 printf("(expecting 2 warnings)\n");
1810
1811 int32_t value = 123;
1812 EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value));
1813 EXPECT_EQ(123, value);
1814
1815 EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value));
1816 EXPECT_EQ(123, value);
1817}
1818
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.
1822TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
1823 int32_t value = 123;
1824 EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
1825 EXPECT_EQ(456, value);
1826
1827 EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value));
1828 EXPECT_EQ(-789, value);
1829}
1830
1831// Tests that Int32FromEnvOrDie() parses the value of the var or
1832// returns the correct default.
1833// Environment variables are not supported on Windows CE.
1834#ifndef GTEST_OS_WINDOWS_MOBILE
1835TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
1836 EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1837 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
1838 EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1839 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
1840 EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
1841}
1842#endif // !GTEST_OS_WINDOWS_MOBILE
1843
1844// Tests that Int32FromEnvOrDie() aborts with an error message
1845// if the variable is not an int32_t.
1846TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
1847 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
1849 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*");
1850}
1851
1852// Tests that Int32FromEnvOrDie() aborts with an error message
1853// if the variable cannot be represented by an int32_t.
1854TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
1855 SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
1857 Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*");
1858}
1859
1860// Tests that ShouldRunTestOnShard() selects all tests
1861// where there is 1 shard.
1862TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
1863 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
1864 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
1865 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
1866 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
1867 EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
1868}
1869
1870class ShouldShardTest : public testing::Test {
1871 protected:
1872 void SetUp() override {
1873 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1874 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1875 }
1876
1877 void TearDown() override {
1878 SetEnv(index_var_, "");
1879 SetEnv(total_var_, "");
1880 }
1881
1882 const char* index_var_;
1883 const char* total_var_;
1884};
1885
1886// Tests that sharding is disabled if neither of the environment variables
1887// are set.
1888TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
1889 SetEnv(index_var_, "");
1890 SetEnv(total_var_, "");
1891
1892 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1893 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1894}
1895
1896// Tests that sharding is not enabled if total_shards == 1.
1897TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
1898 SetEnv(index_var_, "0");
1899 SetEnv(total_var_, "1");
1900 EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
1901 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1902}
1903
1904// Tests that sharding is enabled if total_shards > 1 and
1905// we are not in a death test subprocess.
1906// Environment variables are not supported on Windows CE.
1907#ifndef GTEST_OS_WINDOWS_MOBILE
1908TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
1909 SetEnv(index_var_, "4");
1910 SetEnv(total_var_, "22");
1911 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1912 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1913
1914 SetEnv(index_var_, "8");
1915 SetEnv(total_var_, "9");
1916 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1917 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1918
1919 SetEnv(index_var_, "0");
1920 SetEnv(total_var_, "9");
1921 EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
1922 EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
1923}
1924#endif // !GTEST_OS_WINDOWS_MOBILE
1925
1926// Tests that we exit in error if the sharding values are not valid.
1927
1928typedef ShouldShardTest ShouldShardDeathTest;
1929
1930TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
1931 SetEnv(index_var_, "4");
1932 SetEnv(total_var_, "4");
1933 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1934
1935 SetEnv(index_var_, "4");
1936 SetEnv(total_var_, "-2");
1937 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1938
1939 SetEnv(index_var_, "5");
1940 SetEnv(total_var_, "");
1941 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1942
1943 SetEnv(index_var_, "");
1944 SetEnv(total_var_, "5");
1945 EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
1946}
1947
1948// Tests that ShouldRunTestOnShard is a partition when 5
1949// shards are used.
1950TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
1951 // Choose an arbitrary number of tests and shards.
1952 const int num_tests = 17;
1953 const int num_shards = 5;
1954
1955 // Check partitioning: each test should be on exactly 1 shard.
1956 for (int test_id = 0; test_id < num_tests; test_id++) {
1957 int prev_selected_shard_index = -1;
1958 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1959 if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
1960 if (prev_selected_shard_index < 0) {
1961 prev_selected_shard_index = shard_index;
1962 } else {
1963 ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
1964 << shard_index << " are both selected to run test "
1965 << test_id;
1966 }
1967 }
1968 }
1969 }
1970
1971 // Check balance: This is not required by the sharding protocol, but is a
1972 // desirable property for performance.
1973 for (int shard_index = 0; shard_index < num_shards; shard_index++) {
1974 int num_tests_on_shard = 0;
1975 for (int test_id = 0; test_id < num_tests; test_id++) {
1976 num_tests_on_shard +=
1977 ShouldRunTestOnShard(num_shards, shard_index, test_id);
1978 }
1979 EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
1980 }
1981}
1982
1983// For the same reason we are not explicitly testing everything in the
1984// Test class, there are no separate tests for the following classes
1985// (except for some trivial cases):
1986//
1987// TestSuite, UnitTest, UnitTestResultPrinter.
1988//
1989// Similarly, there are no separate tests for the following macros:
1990//
1991// TEST, TEST_F, RUN_ALL_TESTS
1992
1993TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1994 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr);
1995 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1996}
1997
1998TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
1999 EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
2000 EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
2001}
2002
2003// When a property using a reserved key is supplied to this function, it
2004// tests that a non-fatal failure is added, a fatal failure is not added,
2005// and that the property is not recorded.
2006void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2007 const TestResult& test_result, const char* key) {
2008 EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
2009 ASSERT_EQ(0, test_result.test_property_count())
2010 << "Property for key '" << key << "' recorded unexpectedly.";
2011}
2012
2013void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2014 const char* key) {
2015 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
2016 ASSERT_TRUE(test_info != nullptr);
2017 ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
2018 key);
2019}
2020
2021void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2022 const char* key) {
2023 const testing::TestSuite* test_suite =
2024 UnitTest::GetInstance()->current_test_suite();
2025 ASSERT_TRUE(test_suite != nullptr);
2026 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2027 test_suite->ad_hoc_test_result(), key);
2028}
2029
2030void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2031 const char* key) {
2032 ExpectNonFatalFailureRecordingPropertyWithReservedKey(
2033 UnitTest::GetInstance()->ad_hoc_test_result(), key);
2034}
2035
2036// Tests that property recording functions in UnitTest outside of tests
2037// functions correctly. Creating a separate instance of UnitTest ensures it
2038// is in a state similar to the UnitTest's singleton's between tests.
2039class UnitTestRecordPropertyTest
2041 public:
2042 static void SetUpTestSuite() {
2043 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2044 "disabled");
2045 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2046 "errors");
2047 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2048 "failures");
2049 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2050 "name");
2051 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2052 "tests");
2053 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
2054 "time");
2055
2056 Test::RecordProperty("test_case_key_1", "1");
2057
2058 const testing::TestSuite* test_suite =
2059 UnitTest::GetInstance()->current_test_suite();
2060
2061 ASSERT_TRUE(test_suite != nullptr);
2062
2064 EXPECT_STREQ("test_case_key_1",
2065 test_suite->ad_hoc_test_result().GetTestProperty(0).key());
2066 EXPECT_STREQ("1",
2067 test_suite->ad_hoc_test_result().GetTestProperty(0).value());
2068 }
2069};
2070
2071// Tests TestResult has the expected property when added.
2072TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
2073 UnitTestRecordProperty("key_1", "1");
2074
2075 ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
2076
2077 EXPECT_STREQ("key_1",
2078 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2079 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2080}
2081
2082// Tests TestResult has multiple properties when added.
2083TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
2084 UnitTestRecordProperty("key_1", "1");
2085 UnitTestRecordProperty("key_2", "2");
2086
2087 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2088
2089 EXPECT_STREQ("key_1",
2090 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2091 EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2092
2093 EXPECT_STREQ("key_2",
2094 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2095 EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2096}
2097
2098// Tests TestResult::RecordProperty() overrides values for duplicate keys.
2099TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
2100 UnitTestRecordProperty("key_1", "1");
2101 UnitTestRecordProperty("key_2", "2");
2102 UnitTestRecordProperty("key_1", "12");
2103 UnitTestRecordProperty("key_2", "22");
2104
2105 ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
2106
2107 EXPECT_STREQ("key_1",
2108 unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
2109 EXPECT_STREQ("12",
2110 unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
2111
2112 EXPECT_STREQ("key_2",
2113 unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
2114 EXPECT_STREQ("22",
2115 unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
2116}
2117
2118TEST_F(UnitTestRecordPropertyTest,
2119 AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
2120 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("name");
2121 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2122 "value_param");
2123 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2124 "type_param");
2125 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("status");
2126 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("time");
2127 ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
2128 "classname");
2129}
2130
2131TEST_F(UnitTestRecordPropertyTest,
2132 AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
2134 Test::RecordProperty("name", "1"),
2135 "'classname', 'name', 'status', 'time', 'type_param', 'value_param',"
2136 " 'file', and 'line' are reserved");
2137}
2138
2139class UnitTestRecordPropertyTestEnvironment : public Environment {
2140 public:
2141 void TearDown() override {
2142 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2143 "tests");
2144 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2145 "failures");
2146 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2147 "disabled");
2148 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2149 "errors");
2150 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2151 "name");
2152 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2153 "timestamp");
2154 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2155 "time");
2156 ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
2157 "random_seed");
2158 }
2159};
2160
2161// This will test property recording outside of any test or test case.
2162static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ =
2163 AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
2164
2165// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
2166// of various arities. They do not attempt to be exhaustive. Rather,
2167// view them as smoke tests that can be easily reviewed and verified.
2168// A more complete set of tests for predicate assertions can be found
2169// in gtest_pred_impl_unittest.cc.
2170
2171// First, some predicates and predicate-formatters needed by the tests.
2172
2173// Returns true if and only if the argument is an even number.
2174bool IsEven(int n) { return (n % 2) == 0; }
2175
2176// A functor that returns true if and only if the argument is an even number.
2177struct IsEvenFunctor {
2178 bool operator()(int n) { return IsEven(n); }
2179};
2180
2181// A predicate-formatter function that asserts the argument is an even
2182// number.
2183AssertionResult AssertIsEven(const char* expr, int n) {
2184 if (IsEven(n)) {
2185 return AssertionSuccess();
2186 }
2187
2188 Message msg;
2189 msg << expr << " evaluates to " << n << ", which is not even.";
2190 return AssertionFailure(msg);
2191}
2192
2193// A predicate function that returns AssertionResult for use in
2194// EXPECT/ASSERT_TRUE/FALSE.
2195AssertionResult ResultIsEven(int n) {
2196 if (IsEven(n))
2197 return AssertionSuccess() << n << " is even";
2198 else
2199 return AssertionFailure() << n << " is odd";
2200}
2201
2202// A predicate function that returns AssertionResult but gives no
2203// explanation why it succeeds. Needed for testing that
2204// EXPECT/ASSERT_FALSE handles such functions correctly.
2205AssertionResult ResultIsEvenNoExplanation(int n) {
2206 if (IsEven(n))
2207 return AssertionSuccess();
2208 else
2209 return AssertionFailure() << n << " is odd";
2210}
2211
2212// A predicate-formatter functor that asserts the argument is an even
2213// number.
2214struct AssertIsEvenFunctor {
2215 AssertionResult operator()(const char* expr, int n) {
2216 return AssertIsEven(expr, n);
2217 }
2218};
2219
2220// Returns true if and only if the sum of the arguments is an even number.
2221bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); }
2222
2223// A functor that returns true if and only if the sum of the arguments is an
2224// even number.
2225struct SumIsEven3Functor {
2226 bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); }
2227};
2228
2229// A predicate-formatter function that asserts the sum of the
2230// arguments is an even number.
2231AssertionResult AssertSumIsEven4(const char* e1, const char* e2, const char* e3,
2232 const char* e4, int n1, int n2, int n3,
2233 int n4) {
2234 const int sum = n1 + n2 + n3 + n4;
2235 if (IsEven(sum)) {
2236 return AssertionSuccess();
2237 }
2238
2239 Message msg;
2240 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " (" << n1 << " + "
2241 << n2 << " + " << n3 << " + " << n4 << ") evaluates to " << sum
2242 << ", which is not even.";
2243 return AssertionFailure(msg);
2244}
2245
2246// A predicate-formatter functor that asserts the sum of the arguments
2247// is an even number.
2248struct AssertSumIsEven5Functor {
2249 AssertionResult operator()(const char* e1, const char* e2, const char* e3,
2250 const char* e4, const char* e5, int n1, int n2,
2251 int n3, int n4, int n5) {
2252 const int sum = n1 + n2 + n3 + n4 + n5;
2253 if (IsEven(sum)) {
2254 return AssertionSuccess();
2255 }
2256
2257 Message msg;
2258 msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
2259 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + "
2260 << n5 << ") evaluates to " << sum << ", which is not even.";
2261 return AssertionFailure(msg);
2262 }
2263};
2264
2265// Tests unary predicate assertions.
2266
2267// Tests unary predicate assertions that don't use a custom formatter.
2268TEST(Pred1Test, WithoutFormat) {
2269 // Success cases.
2270 EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
2271 ASSERT_PRED1(IsEven, 4);
2272
2273 // Failure cases.
2275 { // NOLINT
2276 EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
2277 },
2278 "This failure is expected.");
2279 EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), "evaluates to false");
2280}
2281
2282// Tests unary predicate assertions that use a custom formatter.
2283TEST(Pred1Test, WithFormat) {
2284 // Success cases.
2285 EXPECT_PRED_FORMAT1(AssertIsEven, 2);
2286 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
2287 << "This failure is UNEXPECTED!";
2288
2289 // Failure cases.
2290 const int n = 5;
2291 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
2292 "n evaluates to 5, which is not even.");
2294 { // NOLINT
2295 ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
2296 },
2297 "This failure is expected.");
2298}
2299
2300// Tests that unary predicate assertions evaluates their arguments
2301// exactly once.
2302TEST(Pred1Test, SingleEvaluationOnFailure) {
2303 // A success case.
2304 static int n = 0;
2305 EXPECT_PRED1(IsEven, n++);
2306 EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
2307
2308 // A failure case.
2310 { // NOLINT
2311 ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
2312 << "This failure is expected.";
2313 },
2314 "This failure is expected.");
2315 EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
2316}
2317
2318// Tests predicate assertions whose arity is >= 2.
2319
2320// Tests predicate assertions that don't use a custom formatter.
2321TEST(PredTest, WithoutFormat) {
2322 // Success cases.
2323 ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
2324 EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
2325
2326 // Failure cases.
2327 const int n1 = 1;
2328 const int n2 = 2;
2330 { // NOLINT
2331 EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
2332 },
2333 "This failure is expected.");
2335 { // NOLINT
2336 ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
2337 },
2338 "evaluates to false");
2339}
2340
2341// Tests predicate assertions that use a custom formatter.
2342TEST(PredTest, WithFormat) {
2343 // Success cases.
2344 ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10)
2345 << "This failure is UNEXPECTED!";
2346 EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
2347
2348 // Failure cases.
2349 const int n1 = 1;
2350 const int n2 = 2;
2351 const int n3 = 4;
2352 const int n4 = 6;
2354 { // NOLINT
2355 EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
2356 },
2357 "evaluates to 13, which is not even.");
2359 { // NOLINT
2360 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
2361 << "This failure is expected.";
2362 },
2363 "This failure is expected.");
2364}
2365
2366// Tests that predicate assertions evaluates their arguments
2367// exactly once.
2368TEST(PredTest, SingleEvaluationOnFailure) {
2369 // A success case.
2370 int n1 = 0;
2371 int n2 = 0;
2372 EXPECT_PRED2(SumIsEven2, n1++, n2++);
2373 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2374 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2375
2376 // Another success case.
2377 n1 = n2 = 0;
2378 int n3 = 0;
2379 int n4 = 0;
2380 int n5 = 0;
2381 ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), n1++, n2++, n3++, n4++, n5++)
2382 << "This failure is UNEXPECTED!";
2383 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2384 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2385 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2386 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2387 EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
2388
2389 // A failure case.
2390 n1 = n2 = n3 = 0;
2392 { // NOLINT
2393 EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
2394 << "This failure is expected.";
2395 },
2396 "This failure is expected.");
2397 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2398 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2399 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2400
2401 // Another failure case.
2402 n1 = n2 = n3 = n4 = 0;
2404 { // NOLINT
2405 EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
2406 },
2407 "evaluates to 1, which is not even.");
2408 EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
2409 EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
2410 EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
2411 EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
2412}
2413
2414// Test predicate assertions for sets
2415TEST(PredTest, ExpectPredEvalFailure) {
2416 std::set<int> set_a = {2, 1, 3, 4, 5};
2417 std::set<int> set_b = {0, 4, 8};
2418 const auto compare_sets = [](std::set<int>, std::set<int>) { return false; };
2420 EXPECT_PRED2(compare_sets, set_a, set_b),
2421 "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates "
2422 "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }");
2423}
2424
2425// Some helper functions for testing using overloaded/template
2426// functions with ASSERT_PREDn and EXPECT_PREDn.
2427
2428bool IsPositive(double x) { return x > 0; }
2429
2430template <typename T>
2431bool IsNegative(T x) {
2432 return x < 0;
2433}
2434
2435template <typename T1, typename T2>
2436bool GreaterThan(T1 x1, T2 x2) {
2437 return x1 > x2;
2438}
2439
2440// Tests that overloaded functions can be used in *_PRED* as long as
2441// their types are explicitly specified.
2442TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
2443 // C++Builder requires C-style casts rather than static_cast.
2444 EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
2445 ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
2446}
2447
2448// Tests that template functions can be used in *_PRED* as long as
2449// their types are explicitly specified.
2450TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
2451 EXPECT_PRED1(IsNegative<int>, -5);
2452 // Makes sure that we can handle templates with more than one
2453 // parameter.
2454 ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
2455}
2456
2457// Some helper functions for testing using overloaded/template
2458// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
2459
2460AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2461 return n > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
2462}
2463
2464AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2465 return x > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
2466}
2467
2468template <typename T>
2469AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
2470 return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
2471}
2472
2473template <typename T1, typename T2>
2474AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
2475 const T1& x1, const T2& x2) {
2476 return x1 == x2 ? AssertionSuccess()
2477 : AssertionFailure(Message() << "Failure");
2478}
2479
2480// Tests that overloaded functions can be used in *_PRED_FORMAT*
2481// without explicitly specifying their types.
2482TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
2483 EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
2484 ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
2485}
2486
2487// Tests that template functions can be used in *_PRED_FORMAT* without
2488// explicitly specifying their types.
2489TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
2490 EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
2491 ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
2492}
2493
2494// Tests string assertions.
2495
2496// Tests ASSERT_STREQ with non-NULL arguments.
2497TEST(StringAssertionTest, ASSERT_STREQ) {
2498 const char* const p1 = "good";
2499 ASSERT_STREQ(p1, p1);
2500
2501 // Let p2 have the same content as p1, but be at a different address.
2502 const char p2[] = "good";
2503 ASSERT_STREQ(p1, p2);
2504
2505 EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), " \"bad\"\n \"good\"");
2506}
2507
2508// Tests ASSERT_STREQ with NULL arguments.
2509TEST(StringAssertionTest, ASSERT_STREQ_Null) {
2510 ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr);
2511 EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null");
2512}
2513
2514// Tests ASSERT_STREQ with NULL arguments.
2515TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2516 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null");
2517}
2518
2519// Tests ASSERT_STRNE.
2520TEST(StringAssertionTest, ASSERT_STRNE) {
2521 ASSERT_STRNE("hi", "Hi");
2522 ASSERT_STRNE("Hi", nullptr);
2523 ASSERT_STRNE(nullptr, "Hi");
2524 ASSERT_STRNE("", nullptr);
2525 ASSERT_STRNE(nullptr, "");
2526 ASSERT_STRNE("", "Hi");
2527 ASSERT_STRNE("Hi", "");
2528 EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), "\"Hi\" vs \"Hi\"");
2529}
2530
2531// Tests ASSERT_STRCASEEQ.
2532TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
2533 ASSERT_STRCASEEQ("hi", "Hi");
2534 ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);
2535
2536 ASSERT_STRCASEEQ("", "");
2537 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), "Ignoring case");
2538}
2539
2540// Tests ASSERT_STRCASENE.
2541TEST(StringAssertionTest, ASSERT_STRCASENE) {
2542 ASSERT_STRCASENE("hi1", "Hi2");
2543 ASSERT_STRCASENE("Hi", nullptr);
2544 ASSERT_STRCASENE(nullptr, "Hi");
2545 ASSERT_STRCASENE("", nullptr);
2546 ASSERT_STRCASENE(nullptr, "");
2547 ASSERT_STRCASENE("", "Hi");
2548 ASSERT_STRCASENE("Hi", "");
2549 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), "(ignoring case)");
2550}
2551
2552// Tests *_STREQ on wide strings.
2553TEST(StringAssertionTest, STREQ_Wide) {
2554 // NULL strings.
2555 ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr);
2556
2557 // Empty strings.
2558 ASSERT_STREQ(L"", L"");
2559
2560 // Non-null vs NULL.
2561 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null");
2562
2563 // Equal strings.
2564 EXPECT_STREQ(L"Hi", L"Hi");
2565
2566 // Unequal strings.
2567 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), "Abc");
2568
2569 // Strings containing wide characters.
2570 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), "abc");
2571
2572 // The streaming variation.
2574 { // NOLINT
2575 EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
2576 },
2577 "Expected failure");
2578}
2579
2580// Tests *_STRNE on wide strings.
2581TEST(StringAssertionTest, STRNE_Wide) {
2582 // NULL strings.
2584 { // NOLINT
2585 EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr);
2586 },
2587 "");
2588
2589 // Empty strings.
2590 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), "L\"\"");
2591
2592 // Non-null vs NULL.
2593 ASSERT_STRNE(L"non-null", nullptr);
2594
2595 // Equal strings.
2596 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), "L\"Hi\"");
2597
2598 // Unequal strings.
2599 EXPECT_STRNE(L"abc", L"Abc");
2600
2601 // Strings containing wide characters.
2602 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), "abc");
2603
2604 // The streaming variation.
2605 ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
2606}
2607
2608// Tests for ::testing::IsSubstring().
2609
2610// Tests that IsSubstring() returns the correct result when the input
2611// argument type is const char*.
2612TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
2613 EXPECT_FALSE(IsSubstring("", "", nullptr, "a"));
2614 EXPECT_FALSE(IsSubstring("", "", "b", nullptr));
2615 EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
2616
2617 EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr));
2618 EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
2619}
2620
2621// Tests that IsSubstring() returns the correct result when the input
2622// argument type is const wchar_t*.
2623TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
2624 EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
2625 EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
2626 EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
2627
2629 IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr));
2630 EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
2631}
2632
2633// Tests that IsSubstring() generates the correct message when the input
2634// argument type is const char*.
2635TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
2637 "Value of: needle_expr\n"
2638 " Actual: \"needle\"\n"
2639 "Expected: a substring of haystack_expr\n"
2640 "Which is: \"haystack\"",
2641 IsSubstring("needle_expr", "haystack_expr", "needle", "haystack")
2642 .failure_message());
2643}
2644
2645// Tests that IsSubstring returns the correct result when the input
2646// argument type is ::std::string.
2647TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
2648 EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
2649 EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
2650}
2651
2652#if GTEST_HAS_STD_WSTRING
2653// Tests that IsSubstring returns the correct result when the input
2654// argument type is ::std::wstring.
2655TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
2656 EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2657 EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2658}
2659
2660// Tests that IsSubstring() generates the correct message when the input
2661// argument type is ::std::wstring.
2662TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
2664 "Value of: needle_expr\n"
2665 " Actual: L\"needle\"\n"
2666 "Expected: a substring of haystack_expr\n"
2667 "Which is: L\"haystack\"",
2668 IsSubstring("needle_expr", "haystack_expr", ::std::wstring(L"needle"),
2669 L"haystack")
2670 .failure_message());
2671}
2672
2673#endif // GTEST_HAS_STD_WSTRING
2674
2675// Tests for ::testing::IsNotSubstring().
2676
2677// Tests that IsNotSubstring() returns the correct result when the input
2678// argument type is const char*.
2679TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
2680 EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
2681 EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
2682}
2683
2684// Tests that IsNotSubstring() returns the correct result when the input
2685// argument type is const wchar_t*.
2686TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
2687 EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
2688 EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
2689}
2690
2691// Tests that IsNotSubstring() generates the correct message when the input
2692// argument type is const wchar_t*.
2693TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
2695 "Value of: needle_expr\n"
2696 " Actual: L\"needle\"\n"
2697 "Expected: not a substring of haystack_expr\n"
2698 "Which is: L\"two needles\"",
2699 IsNotSubstring("needle_expr", "haystack_expr", L"needle", L"two needles")
2700 .failure_message());
2701}
2702
2703// Tests that IsNotSubstring returns the correct result when the input
2704// argument type is ::std::string.
2705TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
2706 EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
2707 EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
2708}
2709
2710// Tests that IsNotSubstring() generates the correct message when the input
2711// argument type is ::std::string.
2712TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
2714 "Value of: needle_expr\n"
2715 " Actual: \"needle\"\n"
2716 "Expected: not a substring of haystack_expr\n"
2717 "Which is: \"two needles\"",
2718 IsNotSubstring("needle_expr", "haystack_expr", ::std::string("needle"),
2719 "two needles")
2720 .failure_message());
2721}
2722
2723#if GTEST_HAS_STD_WSTRING
2724
2725// Tests that IsNotSubstring returns the correct result when the input
2726// argument type is ::std::wstring.
2727TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
2729 IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
2730 EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
2731}
2732
2733#endif // GTEST_HAS_STD_WSTRING
2734
2735// Tests floating-point assertions.
2736
2737template <typename RawType>
2738class FloatingPointTest : public Test {
2739 protected:
2740 // Pre-calculated numbers to be used by the tests.
2741 struct TestValues {
2742 RawType close_to_positive_zero;
2743 RawType close_to_negative_zero;
2744 RawType further_from_negative_zero;
2745
2746 RawType close_to_one;
2747 RawType further_from_one;
2748
2749 RawType infinity;
2750 RawType close_to_infinity;
2751 RawType further_from_infinity;
2752
2753 RawType nan1;
2754 RawType nan2;
2755 };
2756
2757 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2758 typedef typename Floating::Bits Bits;
2759
2760 void SetUp() override {
2761 const uint32_t max_ulps = Floating::kMaxUlps;
2762
2763 // The bits that represent 0.0.
2764 const Bits zero_bits = Floating(0).bits();
2765
2766 // Makes some numbers close to 0.0.
2767 values_.close_to_positive_zero =
2768 Floating::ReinterpretBits(zero_bits + max_ulps / 2);
2769 values_.close_to_negative_zero =
2770 -Floating::ReinterpretBits(zero_bits + max_ulps - max_ulps / 2);
2771 values_.further_from_negative_zero =
2772 -Floating::ReinterpretBits(zero_bits + max_ulps + 1 - max_ulps / 2);
2773
2774 // The bits that represent 1.0.
2775 const Bits one_bits = Floating(1).bits();
2776
2777 // Makes some numbers close to 1.0.
2778 values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
2779 values_.further_from_one =
2780 Floating::ReinterpretBits(one_bits + max_ulps + 1);
2781
2782 // +infinity.
2783 values_.infinity = Floating::Infinity();
2784
2785 // The bits that represent +infinity.
2786 const Bits infinity_bits = Floating(values_.infinity).bits();
2787
2788 // Makes some numbers close to infinity.
2789 values_.close_to_infinity =
2790 Floating::ReinterpretBits(infinity_bits - max_ulps);
2791 values_.further_from_infinity =
2792 Floating::ReinterpretBits(infinity_bits - max_ulps - 1);
2793
2794 // Makes some NAN's. Sets the most significant bit of the fraction so that
2795 // our NaN's are quiet; trying to process a signaling NaN would raise an
2796 // exception if our environment enables floating point exceptions.
2797 values_.nan1 = Floating::ReinterpretBits(
2798 Floating::kExponentBitMask |
2799 (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
2800 values_.nan2 = Floating::ReinterpretBits(
2801 Floating::kExponentBitMask |
2802 (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
2803 }
2804
2805 void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); }
2806
2807 static TestValues values_;
2808};
2809
2810template <typename RawType>
2811typename FloatingPointTest<RawType>::TestValues
2812 FloatingPointTest<RawType>::values_;
2813
2814// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
2815typedef FloatingPointTest<float> FloatTest;
2816
2817// Tests that the size of Float::Bits matches the size of float.
2818TEST_F(FloatTest, Size) { TestSize(); }
2819
2820// Tests comparing with +0 and -0.
2821TEST_F(FloatTest, Zeros) {
2822 EXPECT_FLOAT_EQ(0.0, -0.0);
2823 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), "1.0");
2824 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), "1.5");
2825}
2826
2827// Tests comparing numbers close to 0.
2828//
2829// This ensures that *_FLOAT_EQ handles the sign correctly and no
2830// overflow occurs when comparing numbers whose absolute value is very
2831// small.
2832TEST_F(FloatTest, AlmostZeros) {
2833 // In C++Builder, names within local classes (such as used by
2834 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2835 // scoping class. Use a static local alias as a workaround.
2836 // We use the assignment syntax since some compilers, like Sun Studio,
2837 // don't allow initializing references using construction syntax
2838 // (parentheses).
2839 static const FloatTest::TestValues& v = this->values_;
2840
2841 EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
2842 EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
2843 EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
2844
2846 { // NOLINT
2847 ASSERT_FLOAT_EQ(v.close_to_positive_zero, v.further_from_negative_zero);
2848 },
2849 "v.further_from_negative_zero");
2850}
2851
2852// Tests comparing numbers close to each other.
2853TEST_F(FloatTest, SmallDiff) {
2854 EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
2855 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
2856 "values_.further_from_one");
2857}
2858
2859// Tests comparing numbers far apart.
2860TEST_F(FloatTest, LargeDiff) {
2861 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), "3.0");
2862}
2863
2864// Tests comparing with infinity.
2865//
2866// This ensures that no overflow occurs when comparing numbers whose
2867// absolute value is very large.
2868TEST_F(FloatTest, Infinity) {
2869 EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
2870 EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
2871 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
2872 "-values_.infinity");
2873
2874 // This is interesting as the representations of infinity and nan1
2875 // are only 1 DLP apart.
2876 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
2877 "values_.nan1");
2878}
2879
2880// Tests that comparing with NAN always returns false.
2881TEST_F(FloatTest, NaN) {
2882 // In C++Builder, names within local classes (such as used by
2883 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2884 // scoping class. Use a static local alias as a workaround.
2885 // We use the assignment syntax since some compilers, like Sun Studio,
2886 // don't allow initializing references using construction syntax
2887 // (parentheses).
2888 static const FloatTest::TestValues& v = this->values_;
2889
2890 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), "v.nan1");
2891 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), "v.nan2");
2892 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), "v.nan1");
2893
2894 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity");
2895}
2896
2897// Tests that *_FLOAT_EQ are reflexive.
2898TEST_F(FloatTest, Reflexive) {
2899 EXPECT_FLOAT_EQ(0.0, 0.0);
2900 EXPECT_FLOAT_EQ(1.0, 1.0);
2901 ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
2902}
2903
2904// Tests that *_FLOAT_EQ are commutative.
2905TEST_F(FloatTest, Commutative) {
2906 // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
2907 EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
2908
2909 // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
2910 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
2911 "1.0");
2912}
2913
2914// Tests EXPECT_NEAR.
2915TEST_F(FloatTest, EXPECT_NEAR) {
2916 EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
2917 EXPECT_NEAR(2.0f, 3.0f, 1.0f);
2918 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
2919 "The difference between 1.0f and 1.5f is 0.5, "
2920 "which exceeds 0.25f");
2921}
2922
2923// Tests ASSERT_NEAR.
2924TEST_F(FloatTest, ASSERT_NEAR) {
2925 ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
2926 ASSERT_NEAR(2.0f, 3.0f, 1.0f);
2927 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
2928 "The difference between 1.0f and 1.5f is 0.5, "
2929 "which exceeds 0.25f");
2930}
2931
2932// Tests the cases where FloatLE() should succeed.
2933TEST_F(FloatTest, FloatLESucceeds) {
2934 EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
2935 ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
2936
2937 // or when val1 is greater than, but almost equals to, val2.
2938 EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
2939}
2940
2941// Tests the cases where FloatLE() should fail.
2942TEST_F(FloatTest, FloatLEFails) {
2943 // When val1 is greater than val2 by a large margin,
2944 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
2945 "(2.0f) <= (1.0f)");
2946
2947 // or by a small yet non-negligible margin,
2949 { // NOLINT
2950 EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
2951 },
2952 "(values_.further_from_one) <= (1.0f)");
2953
2955 { // NOLINT
2956 EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
2957 },
2958 "(values_.nan1) <= (values_.infinity)");
2960 { // NOLINT
2961 EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
2962 },
2963 "(-values_.infinity) <= (values_.nan1)");
2965 { // NOLINT
2966 ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
2967 },
2968 "(values_.nan1) <= (values_.nan1)");
2969}
2970
2971// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
2972typedef FloatingPointTest<double> DoubleTest;
2973
2974// Tests that the size of Double::Bits matches the size of double.
2975TEST_F(DoubleTest, Size) { TestSize(); }
2976
2977// Tests comparing with +0 and -0.
2978TEST_F(DoubleTest, Zeros) {
2979 EXPECT_DOUBLE_EQ(0.0, -0.0);
2980 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), "1.0");
2981 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), "1.0");
2982}
2983
2984// Tests comparing numbers close to 0.
2985//
2986// This ensures that *_DOUBLE_EQ handles the sign correctly and no
2987// overflow occurs when comparing numbers whose absolute value is very
2988// small.
2989TEST_F(DoubleTest, AlmostZeros) {
2990 // In C++Builder, names within local classes (such as used by
2991 // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
2992 // scoping class. Use a static local alias as a workaround.
2993 // We use the assignment syntax since some compilers, like Sun Studio,
2994 // don't allow initializing references using construction syntax
2995 // (parentheses).
2996 static const DoubleTest::TestValues& v = this->values_;
2997
2998 EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
2999 EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
3000 EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
3001
3003 { // NOLINT
3004 ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
3005 v.further_from_negative_zero);
3006 },
3007 "v.further_from_negative_zero");
3008}
3009
3010// Tests comparing numbers close to each other.
3011TEST_F(DoubleTest, SmallDiff) {
3012 EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
3013 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
3014 "values_.further_from_one");
3015}
3016
3017// Tests comparing numbers far apart.
3018TEST_F(DoubleTest, LargeDiff) {
3019 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), "3.0");
3020}
3021
3022// Tests comparing with infinity.
3023//
3024// This ensures that no overflow occurs when comparing numbers whose
3025// absolute value is very large.
3026TEST_F(DoubleTest, Infinity) {
3027 EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
3028 EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
3029 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
3030 "-values_.infinity");
3031
3032 // This is interesting as the representations of infinity_ and nan1_
3033 // are only 1 DLP apart.
3034 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
3035 "values_.nan1");
3036}
3037
3038// Tests that comparing with NAN always returns false.
3039TEST_F(DoubleTest, NaN) {
3040 static const DoubleTest::TestValues& v = this->values_;
3041
3042 // Nokia's STLport crashes if we try to output infinity or NaN.
3043 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), "v.nan1");
3044 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
3045 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
3046 EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity");
3047}
3048
3049// Tests that *_DOUBLE_EQ are reflexive.
3050TEST_F(DoubleTest, Reflexive) {
3051 EXPECT_DOUBLE_EQ(0.0, 0.0);
3052 EXPECT_DOUBLE_EQ(1.0, 1.0);
3053 ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
3054}
3055
3056// Tests that *_DOUBLE_EQ are commutative.
3057TEST_F(DoubleTest, Commutative) {
3058 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
3059 EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
3060
3061 // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
3062 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
3063 "1.0");
3064}
3065
3066// Tests EXPECT_NEAR.
3067TEST_F(DoubleTest, EXPECT_NEAR) {
3068 EXPECT_NEAR(-1.0, -1.1, 0.2);
3069 EXPECT_NEAR(2.0, 3.0, 1.0);
3070 EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
3071 "The difference between 1.0 and 1.5 is 0.5, "
3072 "which exceeds 0.25");
3073 // At this magnitude adjacent doubles are 512.0 apart, so this triggers a
3074 // slightly different failure reporting path.
3076 EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),
3077 "The abs_error parameter 1.0 evaluates to 1 which is smaller than the "
3078 "minimum distance between doubles for numbers of this magnitude which is "
3079 "512");
3080}
3081
3082// Tests ASSERT_NEAR.
3083TEST_F(DoubleTest, ASSERT_NEAR) {
3084 ASSERT_NEAR(-1.0, -1.1, 0.2);
3085 ASSERT_NEAR(2.0, 3.0, 1.0);
3086 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
3087 "The difference between 1.0 and 1.5 is 0.5, "
3088 "which exceeds 0.25");
3089}
3090
3091// Tests the cases where DoubleLE() should succeed.
3092TEST_F(DoubleTest, DoubleLESucceeds) {
3093 EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
3094 ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
3095
3096 // or when val1 is greater than, but almost equals to, val2.
3097 EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
3098}
3099
3100// Tests the cases where DoubleLE() should fail.
3101TEST_F(DoubleTest, DoubleLEFails) {
3102 // When val1 is greater than val2 by a large margin,
3103 EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
3104 "(2.0) <= (1.0)");
3105
3106 // or by a small yet non-negligible margin,
3108 { // NOLINT
3109 EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
3110 },
3111 "(values_.further_from_one) <= (1.0)");
3112
3114 { // NOLINT
3115 EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
3116 },
3117 "(values_.nan1) <= (values_.infinity)");
3119 { // NOLINT
3120 EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
3121 },
3122 " (-values_.infinity) <= (values_.nan1)");
3124 { // NOLINT
3125 ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
3126 },
3127 "(values_.nan1) <= (values_.nan1)");
3128}
3129
3130// Verifies that a test or test case whose name starts with DISABLED_ is
3131// not run.
3132
3133// A test whose name starts with DISABLED_.
3134// Should not run.
3135TEST(DisabledTest, DISABLED_TestShouldNotRun) {
3136 FAIL() << "Unexpected failure: Disabled test should not be run.";
3137}
3138
3139// A test whose name does not start with DISABLED_.
3140// Should run.
3141TEST(DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); }
3142
3143// A test case whose name starts with DISABLED_.
3144// Should not run.
3145TEST(DISABLED_TestSuite, TestShouldNotRun) {
3146 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3147}
3148
3149// A test case and test whose names start with DISABLED_.
3150// Should not run.
3151TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {
3152 FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
3153}
3154
3155// Check that when all tests in a test case are disabled, SetUpTestSuite() and
3156// TearDownTestSuite() are not called.
3157class DisabledTestsTest : public Test {
3158 protected:
3159 static void SetUpTestSuite() {
3160 FAIL() << "Unexpected failure: All tests disabled in test case. "
3161 "SetUpTestSuite() should not be called.";
3162 }
3163
3164 static void TearDownTestSuite() {
3165 FAIL() << "Unexpected failure: All tests disabled in test case. "
3166 "TearDownTestSuite() should not be called.";
3167 }
3168};
3169
3170TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3171 FAIL() << "Unexpected failure: Disabled test should not be run.";
3172}
3173
3174TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
3175 FAIL() << "Unexpected failure: Disabled test should not be run.";
3176}
3177
3178// Tests that disabled typed tests aren't run.
3179
3180template <typename T>
3181class TypedTest : public Test {};
3182
3184TYPED_TEST_SUITE(TypedTest, NumericTypes);
3185
3186TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3187 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3188}
3189
3190template <typename T>
3191class DISABLED_TypedTest : public Test {};
3192
3193TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
3194
3195TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3196 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3197}
3198
3199// Tests that disabled type-parameterized tests aren't run.
3200
3201template <typename T>
3202class TypedTestP : public Test {};
3203
3205
3206TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3207 FAIL() << "Unexpected failure: "
3208 << "Disabled type-parameterized test should not run.";
3209}
3210
3211REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
3212
3214
3215template <typename T>
3216class DISABLED_TypedTestP : public Test {};
3217
3218TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
3219
3220TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3221 FAIL() << "Unexpected failure: "
3222 << "Disabled type-parameterized test should not run.";
3223}
3224
3225REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
3226
3227INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
3228
3229// Tests that assertion macros evaluate their arguments exactly once.
3230
3231class SingleEvaluationTest : public Test {
3232 public: // Must be public and not protected due to a bug in g++ 3.4.2.
3233 // This helper function is needed by the FailedASSERT_STREQ test
3234 // below. It's public to work around C++Builder's bug with scoping local
3235 // classes.
3236 static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); }
3237
3238 // This helper function is needed by the FailedASSERT_NE test below. It's
3239 // public to work around C++Builder's bug with scoping local classes.
3240 static void CompareAndIncrementInts() { ASSERT_NE(a_++, b_++); }
3241
3242 protected:
3243 SingleEvaluationTest() {
3244 p1_ = s1_;
3245 p2_ = s2_;
3246 a_ = 0;
3247 b_ = 0;
3248 }
3249
3250 static const char* const s1_;
3251 static const char* const s2_;
3252 static const char* p1_;
3253 static const char* p2_;
3254
3255 static int a_;
3256 static int b_;
3257};
3258
3259const char* const SingleEvaluationTest::s1_ = "01234";
3260const char* const SingleEvaluationTest::s2_ = "abcde";
3261const char* SingleEvaluationTest::p1_;
3262const char* SingleEvaluationTest::p2_;
3263int SingleEvaluationTest::a_;
3264int SingleEvaluationTest::b_;
3265
3266// Tests that when ASSERT_STREQ fails, it evaluates its arguments
3267// exactly once.
3268TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3269 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3270 "p2_++");
3271 EXPECT_EQ(s1_ + 1, p1_);
3272 EXPECT_EQ(s2_ + 1, p2_);
3273}
3274
3275// Tests that string assertion arguments are evaluated exactly once.
3276TEST_F(SingleEvaluationTest, ASSERT_STR) {
3277 // successful EXPECT_STRNE
3278 EXPECT_STRNE(p1_++, p2_++);
3279 EXPECT_EQ(s1_ + 1, p1_);
3280 EXPECT_EQ(s2_ + 1, p2_);
3281
3282 // failed EXPECT_STRCASEEQ
3283 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), "Ignoring case");
3284 EXPECT_EQ(s1_ + 2, p1_);
3285 EXPECT_EQ(s2_ + 2, p2_);
3286}
3287
3288// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3289// once.
3290TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3291 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3292 "(a_++) != (b_++)");
3293 EXPECT_EQ(1, a_);
3294 EXPECT_EQ(1, b_);
3295}
3296
3297// Tests that assertion arguments are evaluated exactly once.
3298TEST_F(SingleEvaluationTest, OtherCases) {
3299 // successful EXPECT_TRUE
3300 EXPECT_TRUE(0 == a_++); // NOLINT
3301 EXPECT_EQ(1, a_);
3302
3303 // failed EXPECT_TRUE
3304 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3305 EXPECT_EQ(2, a_);
3306
3307 // successful EXPECT_GT
3308 EXPECT_GT(a_++, b_++);
3309 EXPECT_EQ(3, a_);
3310 EXPECT_EQ(1, b_);
3311
3312 // failed EXPECT_LT
3313 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3314 EXPECT_EQ(4, a_);
3315 EXPECT_EQ(2, b_);
3316
3317 // successful ASSERT_TRUE
3318 ASSERT_TRUE(0 < a_++); // NOLINT
3319 EXPECT_EQ(5, a_);
3320
3321 // successful ASSERT_GT
3322 ASSERT_GT(a_++, b_++);
3323 EXPECT_EQ(6, a_);
3324 EXPECT_EQ(3, b_);
3325}
3326
3327#if GTEST_HAS_EXCEPTIONS
3328
3329#if GTEST_HAS_RTTI
3330
3331#define ERROR_DESC "std::runtime_error"
3332
3333#else // GTEST_HAS_RTTI
3334
3335#define ERROR_DESC "an std::exception-derived error"
3336
3337#endif // GTEST_HAS_RTTI
3338
3339void ThrowAnInteger() { throw 1; }
3340void ThrowRuntimeError(const char* what) { throw std::runtime_error(what); }
3341
3342// Tests that assertion arguments are evaluated exactly once.
3343TEST_F(SingleEvaluationTest, ExceptionTests) {
3344 // successful EXPECT_THROW
3346 { // NOLINT
3347 a_++;
3348 ThrowAnInteger();
3349 },
3350 int);
3351 EXPECT_EQ(1, a_);
3352
3353 // failed EXPECT_THROW, throws different
3355 { // NOLINT
3356 a_++;
3357 ThrowAnInteger();
3358 },
3359 bool),
3360 "throws a different type");
3361 EXPECT_EQ(2, a_);
3362
3363 // failed EXPECT_THROW, throws runtime error
3365 { // NOLINT
3366 a_++;
3367 ThrowRuntimeError("A description");
3368 },
3369 bool),
3370 "throws " ERROR_DESC
3371 " with description \"A description\"");
3372 EXPECT_EQ(3, a_);
3373
3374 // failed EXPECT_THROW, throws nothing
3375 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3376 EXPECT_EQ(4, a_);
3377
3378 // successful EXPECT_NO_THROW
3380 EXPECT_EQ(5, a_);
3381
3382 // failed EXPECT_NO_THROW
3384 a_++;
3385 ThrowAnInteger();
3386 }),
3387 "it throws");
3388 EXPECT_EQ(6, a_);
3389
3390 // successful EXPECT_ANY_THROW
3391 EXPECT_ANY_THROW({ // NOLINT
3392 a_++;
3393 ThrowAnInteger();
3394 });
3395 EXPECT_EQ(7, a_);
3396
3397 // failed EXPECT_ANY_THROW
3399 EXPECT_EQ(8, a_);
3400}
3401
3402#endif // GTEST_HAS_EXCEPTIONS
3403
3404// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3405class NoFatalFailureTest : public Test {
3406 protected:
3407 void Succeeds() {}
3408 void FailsNonFatal() { ADD_FAILURE() << "some non-fatal failure"; }
3409 void Fails() { FAIL() << "some fatal failure"; }
3410
3411 void DoAssertNoFatalFailureOnFails() {
3412 ASSERT_NO_FATAL_FAILURE(Fails());
3413 ADD_FAILURE() << "should not reach here.";
3414 }
3415
3416 void DoExpectNoFatalFailureOnFails() {
3417 EXPECT_NO_FATAL_FAILURE(Fails());
3418 ADD_FAILURE() << "other failure";
3419 }
3420};
3421
3422TEST_F(NoFatalFailureTest, NoFailure) {
3423 EXPECT_NO_FATAL_FAILURE(Succeeds());
3424 ASSERT_NO_FATAL_FAILURE(Succeeds());
3425}
3426
3427TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3429 "some non-fatal failure");
3431 "some non-fatal failure");
3432}
3433
3434TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3435 TestPartResultArray gtest_failures;
3436 {
3437 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3438 DoAssertNoFatalFailureOnFails();
3439 }
3440 ASSERT_EQ(2, gtest_failures.size());
3441 EXPECT_EQ(TestPartResult::kFatalFailure,
3442 gtest_failures.GetTestPartResult(0).type());
3443 EXPECT_EQ(TestPartResult::kFatalFailure,
3444 gtest_failures.GetTestPartResult(1).type());
3445 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3446 gtest_failures.GetTestPartResult(0).message());
3448 gtest_failures.GetTestPartResult(1).message());
3449}
3450
3451TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3452 TestPartResultArray gtest_failures;
3453 {
3454 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3455 DoExpectNoFatalFailureOnFails();
3456 }
3457 ASSERT_EQ(3, gtest_failures.size());
3458 EXPECT_EQ(TestPartResult::kFatalFailure,
3459 gtest_failures.GetTestPartResult(0).type());
3460 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3461 gtest_failures.GetTestPartResult(1).type());
3462 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3463 gtest_failures.GetTestPartResult(2).type());
3464 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3465 gtest_failures.GetTestPartResult(0).message());
3467 gtest_failures.GetTestPartResult(1).message());
3469 gtest_failures.GetTestPartResult(2).message());
3470}
3471
3472TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3473 TestPartResultArray gtest_failures;
3474 {
3475 ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
3476 EXPECT_NO_FATAL_FAILURE([] { FAIL() << "foo"; }()) << "my message";
3477 }
3478 ASSERT_EQ(2, gtest_failures.size());
3479 EXPECT_EQ(TestPartResult::kFatalFailure,
3480 gtest_failures.GetTestPartResult(0).type());
3481 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3482 gtest_failures.GetTestPartResult(1).type());
3484 gtest_failures.GetTestPartResult(0).message());
3486 gtest_failures.GetTestPartResult(1).message());
3487}
3488
3489// Tests non-string assertions.
3490
3491std::string EditsToString(const std::vector<EditType>& edits) {
3492 std::string out;
3493 for (size_t i = 0; i < edits.size(); ++i) {
3494 static const char kEdits[] = " +-/";
3495 out.append(1, kEdits[edits[i]]);
3496 }
3497 return out;
3498}
3499
3500std::vector<size_t> CharsToIndices(const std::string& str) {
3501 std::vector<size_t> out;
3502 for (size_t i = 0; i < str.size(); ++i) {
3503 out.push_back(static_cast<size_t>(str[i]));
3504 }
3505 return out;
3506}
3507
3508std::vector<std::string> CharsToLines(const std::string& str) {
3509 std::vector<std::string> out;
3510 for (size_t i = 0; i < str.size(); ++i) {
3511 out.push_back(str.substr(i, 1));
3512 }
3513 return out;
3514}
3515
3516TEST(EditDistance, TestSuites) {
3517 struct Case {
3518 int line;
3519 const char* left;
3520 const char* right;
3521 const char* expected_edits;
3522 const char* expected_diff;
3523 };
3524 static const Case kCases[] = {
3525 // No change.
3526 {__LINE__, "A", "A", " ", ""},
3527 {__LINE__, "ABCDE", "ABCDE", " ", ""},
3528 // Simple adds.
3529 {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
3530 {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
3531 // Simple removes.
3532 {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
3533 {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
3534 // Simple replaces.
3535 {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
3536 {__LINE__, "ABCD", "abcd", "////",
3537 "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
3538 // Path finding.
3539 {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
3540 "@@ -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"},
3541 {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
3542 "@@ -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"},
3543 {__LINE__, "ABCDE", "BCDCD", "- +/",
3544 "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
3545 {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
3546 "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
3547 "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
3548 {}};
3549 for (const Case* c = kCases; c->left; ++c) {
3550 EXPECT_TRUE(c->expected_edits ==
3551 EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3552 CharsToIndices(c->right))))
3553 << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
3554 << EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3555 CharsToIndices(c->right)))
3556 << ">";
3557 EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
3558 CharsToLines(c->right)))
3559 << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
3560 << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
3561 << ">";
3562 }
3563}
3564
3565// Tests EqFailure(), used for implementing *EQ* assertions.
3566TEST(AssertionTest, EqFailure) {
3567 const std::string foo_val("5"), bar_val("6");
3568 const std::string msg1(
3569 EqFailure("foo", "bar", foo_val, bar_val, false).failure_message());
3571 "Expected equality of these values:\n"
3572 " foo\n"
3573 " Which is: 5\n"
3574 " bar\n"
3575 " Which is: 6",
3576 msg1.c_str());
3577
3578 const std::string msg2(
3579 EqFailure("foo", "6", foo_val, bar_val, false).failure_message());
3581 "Expected equality of these values:\n"
3582 " foo\n"
3583 " Which is: 5\n"
3584 " 6",
3585 msg2.c_str());
3586
3587 const std::string msg3(
3588 EqFailure("5", "bar", foo_val, bar_val, false).failure_message());
3590 "Expected equality of these values:\n"
3591 " 5\n"
3592 " bar\n"
3593 " Which is: 6",
3594 msg3.c_str());
3595
3596 const std::string msg4(
3597 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3599 "Expected equality of these values:\n"
3600 " 5\n"
3601 " 6",
3602 msg4.c_str());
3603
3604 const std::string msg5(
3605 EqFailure("foo", "bar", std::string("\"x\""), std::string("\"y\""), true)
3606 .failure_message());
3608 "Expected equality of these values:\n"
3609 " foo\n"
3610 " Which is: \"x\"\n"
3611 " bar\n"
3612 " Which is: \"y\"\n"
3613 "Ignoring case",
3614 msg5.c_str());
3615}
3616
3617TEST(AssertionTest, EqFailureWithDiff) {
3618 const std::string left(
3619 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
3620 const std::string right(
3621 "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
3622 const std::string msg1(
3623 EqFailure("left", "right", left, right, false).failure_message());
3625 "Expected equality of these values:\n"
3626 " left\n"
3627 " Which is: "
3628 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3629 " right\n"
3630 " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3631 "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
3632 "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
3633 msg1.c_str());
3634}
3635
3636// Tests AppendUserMessage(), used for implementing the *EQ* macros.
3637TEST(AssertionTest, AppendUserMessage) {
3638 const std::string foo("foo");
3639
3640 Message msg;
3641 EXPECT_STREQ("foo", AppendUserMessage(foo, msg).c_str());
3642
3643 msg << "bar";
3644 EXPECT_STREQ("foo\nbar", AppendUserMessage(foo, msg).c_str());
3645}
3646
3647#ifdef __BORLANDC__
3648// Silences warnings: "Condition is always true", "Unreachable code"
3649#pragma option push -w-ccc -w-rch
3650#endif
3651
3652// Tests ASSERT_TRUE.
3653TEST(AssertionTest, ASSERT_TRUE) {
3654 ASSERT_TRUE(2 > 1); // NOLINT
3655 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), "2 < 1");
3656}
3657
3658// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
3659TEST(AssertionTest, AssertTrueWithAssertionResult) {
3660 ASSERT_TRUE(ResultIsEven(2));
3661#ifndef __BORLANDC__
3662 // ICE's in C++Builder.
3663 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3664 "Value of: ResultIsEven(3)\n"
3665 " Actual: false (3 is odd)\n"
3666 "Expected: true");
3667#endif
3668 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3669 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3670 "Value of: ResultIsEvenNoExplanation(3)\n"
3671 " Actual: false (3 is odd)\n"
3672 "Expected: true");
3673}
3674
3675// Tests ASSERT_FALSE.
3676TEST(AssertionTest, ASSERT_FALSE) {
3677 ASSERT_FALSE(2 < 1); // NOLINT
3679 "Value of: 2 > 1\n"
3680 " Actual: true\n"
3681 "Expected: false");
3682}
3683
3684// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
3685TEST(AssertionTest, AssertFalseWithAssertionResult) {
3686 ASSERT_FALSE(ResultIsEven(3));
3687#ifndef __BORLANDC__
3688 // ICE's in C++Builder.
3689 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3690 "Value of: ResultIsEven(2)\n"
3691 " Actual: true (2 is even)\n"
3692 "Expected: false");
3693#endif
3694 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3695 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3696 "Value of: ResultIsEvenNoExplanation(2)\n"
3697 " Actual: true\n"
3698 "Expected: false");
3699}
3700
3701#ifdef __BORLANDC__
3702// Restores warnings after previous "#pragma option push" suppressed them
3703#pragma option pop
3704#endif
3705
3706// Tests using ASSERT_EQ on double values. The purpose is to make
3707// sure that the specialization we did for integer and anonymous enums
3708// isn't used for double arguments.
3709TEST(ExpectTest, ASSERT_EQ_Double) {
3710 // A success.
3711 ASSERT_EQ(5.6, 5.6);
3712
3713 // A failure.
3714 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), "5.1");
3715}
3716
3717// Tests ASSERT_EQ.
3718TEST(AssertionTest, ASSERT_EQ) {
3719 ASSERT_EQ(5, 2 + 3);
3720 // clang-format off
3722 "Expected equality of these values:\n"
3723 " 5\n"
3724 " 2*3\n"
3725 " Which is: 6");
3726 // clang-format on
3727}
3728
3729// Tests ASSERT_EQ(NULL, pointer).
3730TEST(AssertionTest, ASSERT_EQ_NULL) {
3731 // A success.
3732 const char* p = nullptr;
3733 ASSERT_EQ(nullptr, p);
3734
3735 // A failure.
3736 static int n = 0;
3737 EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:");
3738}
3739
3740// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3741// treated as a null pointer by the compiler, we need to make sure
3742// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3743// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
3744TEST(ExpectTest, ASSERT_EQ_0) {
3745 int n = 0;
3746
3747 // A success.
3748 ASSERT_EQ(0, n);
3749
3750 // A failure.
3751 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), " 0\n 5.6");
3752}
3753
3754// Tests ASSERT_NE.
3755TEST(AssertionTest, ASSERT_NE) {
3756 ASSERT_NE(6, 7);
3758 "Expected: ('a') != ('a'), "
3759 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3760}
3761
3762// Tests ASSERT_LE.
3763TEST(AssertionTest, ASSERT_LE) {
3764 ASSERT_LE(2, 3);
3765 ASSERT_LE(2, 2);
3766 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0");
3767}
3768
3769// Tests ASSERT_LT.
3770TEST(AssertionTest, ASSERT_LT) {
3771 ASSERT_LT(2, 3);
3772 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2");
3773}
3774
3775// Tests ASSERT_GE.
3776TEST(AssertionTest, ASSERT_GE) {
3777 ASSERT_GE(2, 1);
3778 ASSERT_GE(2, 2);
3779 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3");
3780}
3781
3782// Tests ASSERT_GT.
3783TEST(AssertionTest, ASSERT_GT) {
3784 ASSERT_GT(2, 1);
3785 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2");
3786}
3787
3788#if GTEST_HAS_EXCEPTIONS
3789
3790void ThrowNothing() {}
3791
3792// Tests ASSERT_THROW.
3793TEST(AssertionTest, ASSERT_THROW) {
3794 ASSERT_THROW(ThrowAnInteger(), int);
3795
3796#ifndef __BORLANDC__
3797
3798 // ICE's in C++Builder 2007 and 2009.
3800 ASSERT_THROW(ThrowAnInteger(), bool),
3801 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3802 " Actual: it throws a different type.");
3804 ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
3805 "Expected: ThrowRuntimeError(\"A description\") "
3806 "throws an exception of type std::logic_error.\n "
3807 "Actual: it throws " ERROR_DESC
3808 " "
3809 "with description \"A description\".");
3810#endif
3811
3813 ASSERT_THROW(ThrowNothing(), bool),
3814 "Expected: ThrowNothing() throws an exception of type bool.\n"
3815 " Actual: it throws nothing.");
3816}
3817
3818// Tests ASSERT_NO_THROW.
3819TEST(AssertionTest, ASSERT_NO_THROW) {
3820 ASSERT_NO_THROW(ThrowNothing());
3821 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3822 "Expected: ThrowAnInteger() doesn't throw an exception."
3823 "\n Actual: it throws.");
3824 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
3825 "Expected: ThrowRuntimeError(\"A description\") "
3826 "doesn't throw an exception.\n "
3827 "Actual: it throws " ERROR_DESC
3828 " "
3829 "with description \"A description\".");
3830}
3831
3832// Tests ASSERT_ANY_THROW.
3833TEST(AssertionTest, ASSERT_ANY_THROW) {
3834 ASSERT_ANY_THROW(ThrowAnInteger());
3835 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()),
3836 "Expected: ThrowNothing() throws an exception.\n"
3837 " Actual: it doesn't.");
3838}
3839
3840#endif // GTEST_HAS_EXCEPTIONS
3841
3842// Makes sure we deal with the precedence of <<. This test should
3843// compile.
3844TEST(AssertionTest, AssertPrecedence) {
3845 ASSERT_EQ(1 < 2, true);
3846 bool false_value = false;
3847 ASSERT_EQ(true && false_value, false);
3848}
3849
3850// A subroutine used by the following test.
3851void TestEq1(int x) { ASSERT_EQ(1, x); }
3852
3853// Tests calling a test subroutine that's not part of a fixture.
3854TEST(AssertionTest, NonFixtureSubroutine) {
3855 EXPECT_FATAL_FAILURE(TestEq1(2), " x\n Which is: 2");
3856}
3857
3858// An uncopyable class.
3859class Uncopyable {
3860 public:
3861 explicit Uncopyable(int a_value) : value_(a_value) {}
3862
3863 int value() const { return value_; }
3864 bool operator==(const Uncopyable& rhs) const {
3865 return value() == rhs.value();
3866 }
3867
3868 private:
3869 // This constructor deliberately has no implementation, as we don't
3870 // want this class to be copyable.
3871 Uncopyable(const Uncopyable&); // NOLINT
3872
3873 int value_;
3874};
3875
3876::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3877 return os << value.value();
3878}
3879
3880bool IsPositiveUncopyable(const Uncopyable& x) { return x.value() > 0; }
3881
3882// A subroutine used by the following test.
3883void TestAssertNonPositive() {
3884 Uncopyable y(-1);
3885 ASSERT_PRED1(IsPositiveUncopyable, y);
3886}
3887// A subroutine used by the following test.
3888void TestAssertEqualsUncopyable() {
3889 Uncopyable x(5);
3890 Uncopyable y(-1);
3891 ASSERT_EQ(x, y);
3892}
3893
3894// Tests that uncopyable objects can be used in assertions.
3895TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3896 Uncopyable x(5);
3897 ASSERT_PRED1(IsPositiveUncopyable, x);
3898 ASSERT_EQ(x, x);
3900 TestAssertNonPositive(),
3901 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3902 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3903 "Expected equality of these values:\n"
3904 " x\n Which is: 5\n y\n Which is: -1");
3905}
3906
3907// Tests that uncopyable objects can be used in expects.
3908TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3909 Uncopyable x(5);
3910 EXPECT_PRED1(IsPositiveUncopyable, x);
3911 Uncopyable y(-1);
3913 EXPECT_PRED1(IsPositiveUncopyable, y),
3914 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3915 EXPECT_EQ(x, x);
3917 "Expected equality of these values:\n"
3918 " x\n Which is: 5\n y\n Which is: -1");
3919}
3920
3921enum NamedEnum { kE1 = 0, kE2 = 1 };
3922
3923TEST(AssertionTest, NamedEnum) {
3924 EXPECT_EQ(kE1, kE1);
3925 EXPECT_LT(kE1, kE2);
3926 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3927 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
3928}
3929
3930// Sun Studio and HP aCC2reject this code.
3931#if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3932
3933// Tests using assertions with anonymous enums.
3934enum {
3935 kCaseA = -1,
3936
3937#ifdef GTEST_OS_LINUX
3938
3939 // We want to test the case where the size of the anonymous enum is
3940 // larger than sizeof(int), to make sure our implementation of the
3941 // assertions doesn't truncate the enums. However, MSVC
3942 // (incorrectly) doesn't allow an enum value to exceed the range of
3943 // an int, so this has to be conditionally compiled.
3944 //
3945 // On Linux, kCaseB and kCaseA have the same value when truncated to
3946 // int size. We want to test whether this will confuse the
3947 // assertions.
3949
3950#else
3951
3952 kCaseB = INT_MAX,
3953
3954#endif // GTEST_OS_LINUX
3955
3956 kCaseC = 42
3957};
3958
3959TEST(AssertionTest, AnonymousEnum) {
3960#ifdef GTEST_OS_LINUX
3961
3962 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
3963
3964#endif // GTEST_OS_LINUX
3965
3966 EXPECT_EQ(kCaseA, kCaseA);
3967 EXPECT_NE(kCaseA, kCaseB);
3968 EXPECT_LT(kCaseA, kCaseB);
3969 EXPECT_LE(kCaseA, kCaseB);
3970 EXPECT_GT(kCaseB, kCaseA);
3971 EXPECT_GE(kCaseA, kCaseA);
3972 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), "(kCaseA) >= (kCaseB)");
3973 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), "-1 vs 42");
3974
3975 ASSERT_EQ(kCaseA, kCaseA);
3976 ASSERT_NE(kCaseA, kCaseB);
3977 ASSERT_LT(kCaseA, kCaseB);
3978 ASSERT_LE(kCaseA, kCaseB);
3979 ASSERT_GT(kCaseB, kCaseA);
3980 ASSERT_GE(kCaseA, kCaseA);
3981
3982#ifndef __BORLANDC__
3983
3984 // ICE's in C++Builder.
3985 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), " kCaseB\n Which is: ");
3986 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: 42");
3987#endif
3988
3989 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: -1");
3990}
3991
3992#endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
3993
3994#ifdef GTEST_OS_WINDOWS
3995
3996static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; }
3997
3998static HRESULT OkHRESULTSuccess() { return S_OK; }
3999
4000static HRESULT FalseHRESULTSuccess() { return S_FALSE; }
4001
4002// HRESULT assertion tests test both zero and non-zero
4003// success codes as well as failure message for each.
4004//
4005// Windows CE doesn't support message texts.
4006TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
4007 EXPECT_HRESULT_SUCCEEDED(S_OK);
4008 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
4009
4010 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4011 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4012 " Actual: 0x8000FFFF");
4013}
4014
4015TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
4016 ASSERT_HRESULT_SUCCEEDED(S_OK);
4017 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
4018
4019 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4020 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4021 " Actual: 0x8000FFFF");
4022}
4023
4024TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
4025 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
4026
4027 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
4028 "Expected: (OkHRESULTSuccess()) fails.\n"
4029 " Actual: 0x0");
4030 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
4031 "Expected: (FalseHRESULTSuccess()) fails.\n"
4032 " Actual: 0x1");
4033}
4034
4035TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4036 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
4037
4038#ifndef __BORLANDC__
4039
4040 // ICE's in C++Builder 2007 and 2009.
4041 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4042 "Expected: (OkHRESULTSuccess()) fails.\n"
4043 " Actual: 0x0");
4044#endif
4045
4046 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4047 "Expected: (FalseHRESULTSuccess()) fails.\n"
4048 " Actual: 0x1");
4049}
4050
4051// Tests that streaming to the HRESULT macros works.
4052TEST(HRESULTAssertionTest, Streaming) {
4053 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4054 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4055 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4056 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4057
4058 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED)
4059 << "expected failure",
4060 "expected failure");
4061
4062#ifndef __BORLANDC__
4063
4064 // ICE's in C++Builder 2007 and 2009.
4065 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED)
4066 << "expected failure",
4067 "expected failure");
4068#endif
4069
4070 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4071 "expected failure");
4072
4073 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4074 "expected failure");
4075}
4076
4077#endif // GTEST_OS_WINDOWS
4078
4079// The following code intentionally tests a suboptimal syntax.
4080#ifdef __GNUC__
4081#pragma GCC diagnostic push
4082#pragma GCC diagnostic ignored "-Wdangling-else"
4083#pragma GCC diagnostic ignored "-Wempty-body"
4084#pragma GCC diagnostic ignored "-Wpragmas"
4085#endif
4086// Tests that the assertion macros behave like single statements.
4087TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4088 if (AlwaysFalse())
4089 ASSERT_TRUE(false) << "This should never be executed; "
4090 "It's a compilation test only.";
4091
4092 if (AlwaysTrue())
4093 EXPECT_FALSE(false);
4094 else
4095 ; // NOLINT
4096
4097 if (AlwaysFalse()) ASSERT_LT(1, 3);
4098
4099 if (AlwaysFalse())
4100 ; // NOLINT
4101 else
4102 EXPECT_GT(3, 2) << "";
4103}
4104#ifdef __GNUC__
4105#pragma GCC diagnostic pop
4106#endif
4107
4108#if GTEST_HAS_EXCEPTIONS
4109// Tests that the compiler will not complain about unreachable code in the
4110// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
4111TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4112 int n = 0;
4113
4114 EXPECT_THROW(throw 1, int);
4116 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4117 EXPECT_NO_THROW(n++);
4119 EXPECT_ANY_THROW(throw 1);
4121}
4122
4123TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
4124 EXPECT_THROW(throw std::exception(), std::exception);
4125}
4126
4127// The following code intentionally tests a suboptimal syntax.
4128#ifdef __GNUC__
4129#pragma GCC diagnostic push
4130#pragma GCC diagnostic ignored "-Wdangling-else"
4131#pragma GCC diagnostic ignored "-Wempty-body"
4132#pragma GCC diagnostic ignored "-Wpragmas"
4133#endif
4134TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4135 if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool);
4136
4137 if (AlwaysTrue())
4138 EXPECT_THROW(ThrowAnInteger(), int);
4139 else
4140 ; // NOLINT
4141
4142 if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger());
4143
4144 if (AlwaysTrue())
4145 EXPECT_NO_THROW(ThrowNothing());
4146 else
4147 ; // NOLINT
4148
4149 if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing());
4150
4151 if (AlwaysTrue())
4152 EXPECT_ANY_THROW(ThrowAnInteger());
4153 else
4154 ; // NOLINT
4155}
4156#ifdef __GNUC__
4157#pragma GCC diagnostic pop
4158#endif
4159
4160#endif // GTEST_HAS_EXCEPTIONS
4161
4162// The following code intentionally tests a suboptimal syntax.
4163#ifdef __GNUC__
4164#pragma GCC diagnostic push
4165#pragma GCC diagnostic ignored "-Wdangling-else"
4166#pragma GCC diagnostic ignored "-Wempty-body"
4167#pragma GCC diagnostic ignored "-Wpragmas"
4168#endif
4169TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4170 if (AlwaysFalse())
4171 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4172 << "It's a compilation test only.";
4173 else
4174 ; // NOLINT
4175
4176 if (AlwaysFalse())
4178 else
4179 ; // NOLINT
4180
4181 if (AlwaysTrue())
4183 else
4184 ; // NOLINT
4185
4186 if (AlwaysFalse())
4187 ; // NOLINT
4188 else
4190}
4191#ifdef __GNUC__
4192#pragma GCC diagnostic pop
4193#endif
4194
4195// Tests that the assertion macros work well with switch statements.
4196TEST(AssertionSyntaxTest, WorksWithSwitch) {
4197 switch (0) {
4198 case 1:
4199 break;
4200 default:
4201 ASSERT_TRUE(true);
4202 }
4203
4204 switch (0)
4205 case 0:
4206 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4207
4208 // Binary assertions are implemented using a different code path
4209 // than the Boolean assertions. Hence we test them separately.
4210 switch (0) {
4211 case 1:
4212 default:
4213 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4214 }
4215
4216 switch (0)
4217 case 0:
4218 EXPECT_NE(1, 2);
4219}
4220
4221#if GTEST_HAS_EXCEPTIONS
4222
4223void ThrowAString() { throw "std::string"; }
4224
4225// Test that the exception assertion macros compile and work with const
4226// type qualifier.
4227TEST(AssertionSyntaxTest, WorksWithConst) {
4228 ASSERT_THROW(ThrowAString(), const char*);
4229
4230 EXPECT_THROW(ThrowAString(), const char*);
4231}
4232
4233#endif // GTEST_HAS_EXCEPTIONS
4234
4235} // namespace
4236
4237namespace testing {
4238
4239// Tests that Google Test tracks SUCCEED*.
4240TEST(SuccessfulAssertionTest, SUCCEED) {
4241 SUCCEED();
4242 SUCCEED() << "OK";
4243 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4244}
4245
4246// Tests that Google Test doesn't track successful EXPECT_*.
4247TEST(SuccessfulAssertionTest, EXPECT) {
4248 EXPECT_TRUE(true);
4249 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4250}
4251
4252// Tests that Google Test doesn't track successful EXPECT_STR*.
4253TEST(SuccessfulAssertionTest, EXPECT_STR) {
4254 EXPECT_STREQ("", "");
4255 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4256}
4257
4258// Tests that Google Test doesn't track successful ASSERT_*.
4259TEST(SuccessfulAssertionTest, ASSERT) {
4260 ASSERT_TRUE(true);
4261 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4262}
4263
4264// Tests that Google Test doesn't track successful ASSERT_STR*.
4265TEST(SuccessfulAssertionTest, ASSERT_STR) {
4266 ASSERT_STREQ("", "");
4267 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4268}
4269
4270} // namespace testing
4271
4272namespace {
4273
4274// Tests the message streaming variation of assertions.
4275
4276TEST(AssertionWithMessageTest, EXPECT) {
4277 EXPECT_EQ(1, 1) << "This should succeed.";
4278 EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4279 "Expected failure #1");
4280 EXPECT_LE(1, 2) << "This should succeed.";
4281 EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4282 "Expected failure #2.");
4283 EXPECT_GE(1, 0) << "This should succeed.";
4284 EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4285 "Expected failure #3.");
4286
4287 EXPECT_STREQ("1", "1") << "This should succeed.";
4288 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4289 "Expected failure #4.");
4290 EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4291 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4292 "Expected failure #5.");
4293
4294 EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4295 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4296 "Expected failure #6.");
4297 EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4298}
4299
4300TEST(AssertionWithMessageTest, ASSERT) {
4301 ASSERT_EQ(1, 1) << "This should succeed.";
4302 ASSERT_NE(1, 2) << "This should succeed.";
4303 ASSERT_LE(1, 2) << "This should succeed.";
4304 ASSERT_LT(1, 2) << "This should succeed.";
4305 ASSERT_GE(1, 0) << "This should succeed.";
4306 EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4307 "Expected failure.");
4308}
4309
4310TEST(AssertionWithMessageTest, ASSERT_STR) {
4311 ASSERT_STREQ("1", "1") << "This should succeed.";
4312 ASSERT_STRNE("1", "2") << "This should succeed.";
4313 ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4314 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4315 "Expected failure.");
4316}
4317
4318TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4319 ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4320 ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4321 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT
4322 "Expect failure.");
4323}
4324
4325// Tests using ASSERT_FALSE with a streamed message.
4326TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4327 ASSERT_FALSE(false) << "This shouldn't fail.";
4329 { // NOLINT
4330 ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4331 << " evaluates to " << true;
4332 },
4333 "Expected failure");
4334}
4335
4336// Tests using FAIL with a streamed message.
4337TEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0, "0"); }
4338
4339// Tests using SUCCEED with a streamed message.
4340TEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() << "Success == " << 1; }
4341
4342// Tests using ASSERT_TRUE with a streamed message.
4343TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4344 ASSERT_TRUE(true) << "This should succeed.";
4345 ASSERT_TRUE(true) << true;
4347 { // NOLINT
4348 ASSERT_TRUE(false) << static_cast<const char*>(nullptr)
4349 << static_cast<char*>(nullptr);
4350 },
4351 "(null)(null)");
4352}
4353
4354#ifdef GTEST_OS_WINDOWS
4355// Tests using wide strings in assertion messages.
4356TEST(AssertionWithMessageTest, WideStringMessage) {
4358 { // NOLINT
4359 EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4360 },
4361 "This failure is expected.");
4363 { // NOLINT
4364 ASSERT_EQ(1, 2) << "This failure is " << L"expected too.\x8120";
4365 },
4366 "This failure is expected too.");
4367}
4368#endif // GTEST_OS_WINDOWS
4369
4370// Tests EXPECT_TRUE.
4371TEST(ExpectTest, EXPECT_TRUE) {
4372 EXPECT_TRUE(true) << "Intentional success";
4373 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4374 "Intentional failure #1.");
4375 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4376 "Intentional failure #2.");
4377 EXPECT_TRUE(2 > 1); // NOLINT
4379 "Value of: 2 < 1\n"
4380 " Actual: false\n"
4381 "Expected: true");
4382 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), "2 > 3");
4383}
4384
4385// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
4386TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4387 EXPECT_TRUE(ResultIsEven(2));
4388 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4389 "Value of: ResultIsEven(3)\n"
4390 " Actual: false (3 is odd)\n"
4391 "Expected: true");
4392 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4393 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4394 "Value of: ResultIsEvenNoExplanation(3)\n"
4395 " Actual: false (3 is odd)\n"
4396 "Expected: true");
4397}
4398
4399// Tests EXPECT_FALSE with a streamed message.
4400TEST(ExpectTest, EXPECT_FALSE) {
4401 EXPECT_FALSE(2 < 1); // NOLINT
4402 EXPECT_FALSE(false) << "Intentional success";
4403 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4404 "Intentional failure #1.");
4405 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4406 "Intentional failure #2.");
4408 "Value of: 2 > 1\n"
4409 " Actual: true\n"
4410 "Expected: false");
4411 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), "2 < 3");
4412}
4413
4414// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
4415TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4416 EXPECT_FALSE(ResultIsEven(3));
4417 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4418 "Value of: ResultIsEven(2)\n"
4419 " Actual: true (2 is even)\n"
4420 "Expected: false");
4421 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4422 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4423 "Value of: ResultIsEvenNoExplanation(2)\n"
4424 " Actual: true\n"
4425 "Expected: false");
4426}
4427
4428#ifdef __BORLANDC__
4429// Restores warnings after previous "#pragma option push" suppressed them
4430#pragma option pop
4431#endif
4432
4433// Tests EXPECT_EQ.
4434TEST(ExpectTest, EXPECT_EQ) {
4435 EXPECT_EQ(5, 2 + 3);
4436 // clang-format off
4438 "Expected equality of these values:\n"
4439 " 5\n"
4440 " 2*3\n"
4441 " Which is: 6");
4442 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), "2 - 3");
4443 // clang-format on
4444}
4445
4446// Tests using EXPECT_EQ on double values. The purpose is to make
4447// sure that the specialization we did for integer and anonymous enums
4448// isn't used for double arguments.
4449TEST(ExpectTest, EXPECT_EQ_Double) {
4450 // A success.
4451 EXPECT_EQ(5.6, 5.6);
4452
4453 // A failure.
4454 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), "5.1");
4455}
4456
4457// Tests EXPECT_EQ(NULL, pointer).
4458TEST(ExpectTest, EXPECT_EQ_NULL) {
4459 // A success.
4460 const char* p = nullptr;
4461 EXPECT_EQ(nullptr, p);
4462
4463 // A failure.
4464 int n = 0;
4465 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:");
4466}
4467
4468// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4469// treated as a null pointer by the compiler, we need to make sure
4470// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4471// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
4472TEST(ExpectTest, EXPECT_EQ_0) {
4473 int n = 0;
4474
4475 // A success.
4476 EXPECT_EQ(0, n);
4477
4478 // A failure.
4479 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), " 0\n 5.6");
4480}
4481
4482// Tests EXPECT_NE.
4483TEST(ExpectTest, EXPECT_NE) {
4484 EXPECT_NE(6, 7);
4485
4487 "Expected: ('a') != ('a'), "
4488 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4490 char* const p0 = nullptr;
4491 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), "p0");
4492 // Only way to get the Nokia compiler to compile the cast
4493 // is to have a separate void* variable first. Putting
4494 // the two casts on the same line doesn't work, neither does
4495 // a direct C-style to char*.
4496 void* pv1 = (void*)0x1234; // NOLINT
4497 char* const p1 = reinterpret_cast<char*>(pv1);
4498 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), "p1");
4499}
4500
4501// Tests EXPECT_LE.
4502TEST(ExpectTest, EXPECT_LE) {
4503 EXPECT_LE(2, 3);
4504 EXPECT_LE(2, 2);
4506 "Expected: (2) <= (0), actual: 2 vs 0");
4507 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), "(1.1) <= (0.9)");
4508}
4509
4510// Tests EXPECT_LT.
4511TEST(ExpectTest, EXPECT_LT) {
4512 EXPECT_LT(2, 3);
4514 "Expected: (2) < (2), actual: 2 vs 2");
4515 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), "(2) < (1)");
4516}
4517
4518// Tests EXPECT_GE.
4519TEST(ExpectTest, EXPECT_GE) {
4520 EXPECT_GE(2, 1);
4521 EXPECT_GE(2, 2);
4523 "Expected: (2) >= (3), actual: 2 vs 3");
4524 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), "(0.9) >= (1.1)");
4525}
4526
4527// Tests EXPECT_GT.
4528TEST(ExpectTest, EXPECT_GT) {
4529 EXPECT_GT(2, 1);
4531 "Expected: (2) > (2), actual: 2 vs 2");
4532 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), "(2) > (3)");
4533}
4534
4535#if GTEST_HAS_EXCEPTIONS
4536
4537// Tests EXPECT_THROW.
4538TEST(ExpectTest, EXPECT_THROW) {
4539 EXPECT_THROW(ThrowAnInteger(), int);
4540 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4541 "Expected: ThrowAnInteger() throws an exception of "
4542 "type bool.\n Actual: it throws a different type.");
4544 EXPECT_THROW(ThrowRuntimeError("A description"), std::logic_error),
4545 "Expected: ThrowRuntimeError(\"A description\") "
4546 "throws an exception of type std::logic_error.\n "
4547 "Actual: it throws " ERROR_DESC
4548 " "
4549 "with description \"A description\".");
4551 EXPECT_THROW(ThrowNothing(), bool),
4552 "Expected: ThrowNothing() throws an exception of type bool.\n"
4553 " Actual: it throws nothing.");
4554}
4555
4556// Tests EXPECT_NO_THROW.
4557TEST(ExpectTest, EXPECT_NO_THROW) {
4558 EXPECT_NO_THROW(ThrowNothing());
4559 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4560 "Expected: ThrowAnInteger() doesn't throw an "
4561 "exception.\n Actual: it throws.");
4562 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
4563 "Expected: ThrowRuntimeError(\"A description\") "
4564 "doesn't throw an exception.\n "
4565 "Actual: it throws " ERROR_DESC
4566 " "
4567 "with description \"A description\".");
4568}
4569
4570// Tests EXPECT_ANY_THROW.
4571TEST(ExpectTest, EXPECT_ANY_THROW) {
4572 EXPECT_ANY_THROW(ThrowAnInteger());
4574 "Expected: ThrowNothing() throws an exception.\n"
4575 " Actual: it doesn't.");
4576}
4577
4578#endif // GTEST_HAS_EXCEPTIONS
4579
4580// Make sure we deal with the precedence of <<.
4581TEST(ExpectTest, ExpectPrecedence) {
4582 EXPECT_EQ(1 < 2, true);
4583 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4584 " true && false\n Which is: false");
4585}
4586
4587// Tests the StreamableToString() function.
4588
4589// Tests using StreamableToString() on a scalar.
4590TEST(StreamableToStringTest, Scalar) {
4591 EXPECT_STREQ("5", StreamableToString(5).c_str());
4592}
4593
4594// Tests using StreamableToString() on a non-char pointer.
4595TEST(StreamableToStringTest, Pointer) {
4596 int n = 0;
4597 int* p = &n;
4598 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4599}
4600
4601// Tests using StreamableToString() on a NULL non-char pointer.
4602TEST(StreamableToStringTest, NullPointer) {
4603 int* p = nullptr;
4604 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4605}
4606
4607// Tests using StreamableToString() on a C string.
4608TEST(StreamableToStringTest, CString) {
4609 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4610}
4611
4612// Tests using StreamableToString() on a NULL C string.
4613TEST(StreamableToStringTest, NullCString) {
4614 char* p = nullptr;
4615 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4616}
4617
4618// Tests using streamable values as assertion messages.
4619
4620// Tests using std::string as an assertion message.
4621TEST(StreamableTest, string) {
4622 static const std::string str(
4623 "This failure message is a std::string, and is expected.");
4624 EXPECT_FATAL_FAILURE(FAIL() << str, str.c_str());
4625}
4626
4627// Tests that we can output strings containing embedded NULs.
4628// Limited to Linux because we can only do this with std::string's.
4629TEST(StreamableTest, stringWithEmbeddedNUL) {
4630 static const char char_array_with_nul[] =
4631 "Here's a NUL\0 and some more string";
4632 static const std::string string_with_nul(
4633 char_array_with_nul,
4634 sizeof(char_array_with_nul) - 1); // drops the trailing NUL
4635 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4636 "Here's a NUL\\0 and some more string");
4637}
4638
4639// Tests that we can output a NUL char.
4640TEST(StreamableTest, NULChar) {
4642 { // NOLINT
4643 FAIL() << "A NUL" << '\0' << " and some more string";
4644 },
4645 "A NUL\\0 and some more string");
4646}
4647
4648// Tests using int as an assertion message.
4649TEST(StreamableTest, int) { EXPECT_FATAL_FAILURE(FAIL() << 900913, "900913"); }
4650
4651// Tests using NULL char pointer as an assertion message.
4652//
4653// In MSVC, streaming a NULL char * causes access violation. Google Test
4654// implemented a workaround (substituting "(null)" for NULL). This
4655// tests whether the workaround works.
4656TEST(StreamableTest, NullCharPtr) {
4657 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)");
4658}
4659
4660// Tests that basic IO manipulators (endl, ends, and flush) can be
4661// streamed to testing::Message.
4662TEST(StreamableTest, BasicIoManip) {
4664 { // NOLINT
4665 FAIL() << "Line 1." << std::endl
4666 << "A NUL char " << std::ends << std::flush << " in line 2.";
4667 },
4668 "Line 1.\nA NUL char \\0 in line 2.");
4669}
4670
4671// Tests the macros that haven't been covered so far.
4672
4673void AddFailureHelper(bool* aborted) {
4674 *aborted = true;
4675 ADD_FAILURE() << "Intentional failure.";
4676 *aborted = false;
4677}
4678
4679// Tests ADD_FAILURE.
4680TEST(MacroTest, ADD_FAILURE) {
4681 bool aborted = true;
4682 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), "Intentional failure.");
4683 EXPECT_FALSE(aborted);
4684}
4685
4686// Tests ADD_FAILURE_AT.
4687TEST(MacroTest, ADD_FAILURE_AT) {
4688 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4689 // the failure message contains the user-streamed part.
4690 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4691
4692 // Verifies that the user-streamed part is optional.
4693 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4694
4695 // Unfortunately, we cannot verify that the failure message contains
4696 // the right file path and line number the same way, as
4697 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4698 // line number. Instead, we do that in googletest-output-test_.cc.
4699}
4700
4701// Tests FAIL.
4702TEST(MacroTest, FAIL) {
4703 EXPECT_FATAL_FAILURE(FAIL(), "Failed");
4704 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4705 "Intentional failure.");
4706}
4707
4708// Tests GTEST_FAIL_AT.
4709TEST(MacroTest, GTEST_FAIL_AT) {
4710 // Verifies that GTEST_FAIL_AT does generate a fatal failure and
4711 // the failure message contains the user-streamed part.
4712 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4713
4714 // Verifies that the user-streamed part is optional.
4715 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed");
4716
4717 // See the ADD_FAIL_AT test above to see how we test that the failure message
4718 // contains the right filename and line number -- the same applies here.
4719}
4720
4721// Tests SUCCEED
4722TEST(MacroTest, SUCCEED) {
4723 SUCCEED();
4724 SUCCEED() << "Explicit success.";
4725}
4726
4727// Tests for EXPECT_EQ() and ASSERT_EQ().
4728//
4729// These tests fail *intentionally*, s.t. the failure messages can be
4730// generated and tested.
4731//
4732// We have different tests for different argument types.
4733
4734// Tests using bool values in {EXPECT|ASSERT}_EQ.
4735TEST(EqAssertionTest, Bool) {
4736 EXPECT_EQ(true, true);
4738 {
4739 bool false_value = false;
4740 ASSERT_EQ(false_value, true);
4741 },
4742 " false_value\n Which is: false\n true");
4743}
4744
4745// Tests using int values in {EXPECT|ASSERT}_EQ.
4746TEST(EqAssertionTest, Int) {
4747 ASSERT_EQ(32, 32);
4748 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), " 32\n 33");
4749}
4750
4751// Tests using time_t values in {EXPECT|ASSERT}_EQ.
4752TEST(EqAssertionTest, Time_T) {
4753 EXPECT_EQ(static_cast<time_t>(0), static_cast<time_t>(0));
4755 ASSERT_EQ(static_cast<time_t>(0), static_cast<time_t>(1234)), "1234");
4756}
4757
4758// Tests using char values in {EXPECT|ASSERT}_EQ.
4759TEST(EqAssertionTest, Char) {
4760 ASSERT_EQ('z', 'z');
4761 const char ch = 'b';
4762 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), " ch\n Which is: 'b'");
4763 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), " ch\n Which is: 'b'");
4764}
4765
4766// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
4767TEST(EqAssertionTest, WideChar) {
4768 EXPECT_EQ(L'b', L'b');
4769
4771 "Expected equality of these values:\n"
4772 " L'\0'\n"
4773 " Which is: L'\0' (0, 0x0)\n"
4774 " L'x'\n"
4775 " Which is: L'x' (120, 0x78)");
4776
4777 static wchar_t wchar;
4778 wchar = L'b';
4779 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), "wchar");
4780 wchar = 0x8119;
4781 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
4782 " wchar\n Which is: L'");
4783}
4784
4785// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
4786TEST(EqAssertionTest, StdString) {
4787 // Compares a const char* to an std::string that has identical
4788 // content.
4789 ASSERT_EQ("Test", ::std::string("Test"));
4790
4791 // Compares two identical std::strings.
4792 static const ::std::string str1("A * in the middle");
4793 static const ::std::string str2(str1);
4794 EXPECT_EQ(str1, str2);
4795
4796 // Compares a const char* to an std::string that has different
4797 // content
4798 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), "\"test\"");
4799
4800 // Compares an std::string to a char* that has different content.
4801 char* const p1 = const_cast<char*>("foo");
4802 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), "p1");
4803
4804 // Compares two std::strings that have different contents, one of
4805 // which having a NUL character in the middle. This should fail.
4806 static ::std::string str3(str1);
4807 str3.at(2) = '\0';
4808 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4809 " str3\n Which is: \"A \\0 in the middle\"");
4810}
4811
4812#if GTEST_HAS_STD_WSTRING
4813
4814// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
4815TEST(EqAssertionTest, StdWideString) {
4816 // Compares two identical std::wstrings.
4817 const ::std::wstring wstr1(L"A * in the middle");
4818 const ::std::wstring wstr2(wstr1);
4819 ASSERT_EQ(wstr1, wstr2);
4820
4821 // Compares an std::wstring to a const wchar_t* that has identical
4822 // content.
4823 const wchar_t kTestX8119[] = {'T', 'e', 's', 't', 0x8119, '\0'};
4824 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4825
4826 // Compares an std::wstring to a const wchar_t* that has different
4827 // content.
4828 const wchar_t kTestX8120[] = {'T', 'e', 's', 't', 0x8120, '\0'};
4830 { // NOLINT
4831 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4832 },
4833 "kTestX8120");
4834
4835 // Compares two std::wstrings that have different contents, one of
4836 // which having a NUL character in the middle.
4837 ::std::wstring wstr3(wstr1);
4838 wstr3.at(2) = L'\0';
4839 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), "wstr3");
4840
4841 // Compares a wchar_t* to an std::wstring that has different
4842 // content.
4844 { // NOLINT
4845 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4846 },
4847 "");
4848}
4849
4850#endif // GTEST_HAS_STD_WSTRING
4851
4852// Tests using char pointers in {EXPECT|ASSERT}_EQ.
4853TEST(EqAssertionTest, CharPointer) {
4854 char* const p0 = nullptr;
4855 // Only way to get the Nokia compiler to compile the cast
4856 // is to have a separate void* variable first. Putting
4857 // the two casts on the same line doesn't work, neither does
4858 // a direct C-style to char*.
4859 void* pv1 = (void*)0x1234; // NOLINT
4860 void* pv2 = (void*)0xABC0; // NOLINT
4861 char* const p1 = reinterpret_cast<char*>(pv1);
4862 char* const p2 = reinterpret_cast<char*>(pv2);
4863 ASSERT_EQ(p1, p1);
4864
4865 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:");
4866 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:");
4867 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4868 reinterpret_cast<char*>(0xABC0)),
4869 "ABC0");
4870}
4871
4872// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
4873TEST(EqAssertionTest, WideCharPointer) {
4874 wchar_t* const p0 = nullptr;
4875 // Only way to get the Nokia compiler to compile the cast
4876 // is to have a separate void* variable first. Putting
4877 // the two casts on the same line doesn't work, neither does
4878 // a direct C-style to char*.
4879 void* pv1 = (void*)0x1234; // NOLINT
4880 void* pv2 = (void*)0xABC0; // NOLINT
4881 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4882 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4883 EXPECT_EQ(p0, p0);
4884
4885 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:");
4886 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:");
4887 void* pv3 = (void*)0x1234; // NOLINT
4888 void* pv4 = (void*)0xABC0; // NOLINT
4889 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4890 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4891 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), "p4");
4892}
4893
4894// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
4895TEST(EqAssertionTest, OtherPointer) {
4896 ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));
4897 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),
4898 reinterpret_cast<const int*>(0x1234)),
4899 "0x1234");
4900}
4901
4902// A class that supports binary comparison operators but not streaming.
4903class UnprintableChar {
4904 public:
4905 explicit UnprintableChar(char ch) : char_(ch) {}
4906
4907 bool operator==(const UnprintableChar& rhs) const {
4908 return char_ == rhs.char_;
4909 }
4910 bool operator!=(const UnprintableChar& rhs) const {
4911 return char_ != rhs.char_;
4912 }
4913 bool operator<(const UnprintableChar& rhs) const { return char_ < rhs.char_; }
4914 bool operator<=(const UnprintableChar& rhs) const {
4915 return char_ <= rhs.char_;
4916 }
4917 bool operator>(const UnprintableChar& rhs) const { return char_ > rhs.char_; }
4918 bool operator>=(const UnprintableChar& rhs) const {
4919 return char_ >= rhs.char_;
4920 }
4921
4922 private:
4923 char char_;
4924};
4925
4926// Tests that ASSERT_EQ() and friends don't require the arguments to
4927// be printable.
4928TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
4929 const UnprintableChar x('x'), y('y');
4930 ASSERT_EQ(x, x);
4931 EXPECT_NE(x, y);
4932 ASSERT_LT(x, y);
4933 EXPECT_LE(x, y);
4934 ASSERT_GT(y, x);
4935 EXPECT_GE(x, x);
4936
4937 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
4938 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
4939 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
4940 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
4941 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
4942
4943 // Code tested by EXPECT_FATAL_FAILURE cannot reference local
4944 // variables, so we have to write UnprintableChar('x') instead of x.
4945#ifndef __BORLANDC__
4946 // ICE's in C++Builder.
4947 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
4948 "1-byte object <78>");
4949 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4950 "1-byte object <78>");
4951#endif
4952 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
4953 "1-byte object <79>");
4954 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4955 "1-byte object <78>");
4956 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
4957 "1-byte object <79>");
4958}
4959
4960// Tests the FRIEND_TEST macro.
4961
4962// This class has a private member we want to test. We will test it
4963// both in a TEST and in a TEST_F.
4964class Foo {
4965 public:
4966 Foo() = default;
4967
4968 private:
4969 int Bar() const { return 1; }
4970
4971 // Declares the friend tests that can access the private member
4972 // Bar().
4973 FRIEND_TEST(FRIEND_TEST_Test, TEST);
4974 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
4975};
4976
4977// Tests that the FRIEND_TEST declaration allows a TEST to access a
4978// class's private members. This should compile.
4979TEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); }
4980
4981// The fixture needed to test using FRIEND_TEST with TEST_F.
4982class FRIEND_TEST_Test2 : public Test {
4983 protected:
4984 Foo foo;
4985};
4986
4987// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
4988// class's private members. This should compile.
4989TEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); }
4990
4991// Tests the life cycle of Test objects.
4992
4993// The test fixture for testing the life cycle of Test objects.
4994//
4995// This class counts the number of live test objects that uses this
4996// fixture.
4997class TestLifeCycleTest : public Test {
4998 protected:
4999 // Constructor. Increments the number of test objects that uses
5000 // this fixture.
5001 TestLifeCycleTest() { count_++; }
5002
5003 // Destructor. Decrements the number of test objects that uses this
5004 // fixture.
5005 ~TestLifeCycleTest() override { count_--; }
5006
5007 // Returns the number of live test objects that uses this fixture.
5008 int count() const { return count_; }
5009
5010 private:
5011 static int count_;
5012};
5013
5014int TestLifeCycleTest::count_ = 0;
5015
5016// Tests the life cycle of test objects.
5017TEST_F(TestLifeCycleTest, Test1) {
5018 // There should be only one test object in this test case that's
5019 // currently alive.
5020 ASSERT_EQ(1, count());
5021}
5022
5023// Tests the life cycle of test objects.
5024TEST_F(TestLifeCycleTest, Test2) {
5025 // After Test1 is done and Test2 is started, there should still be
5026 // only one live test object, as the object for Test1 should've been
5027 // deleted.
5028 ASSERT_EQ(1, count());
5029}
5030
5031} // namespace
5032
5033// Tests that the copy constructor works when it is NOT optimized away by
5034// the compiler.
5035TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5036 // Checks that the copy constructor doesn't try to dereference NULL pointers
5037 // in the source object.
5038 AssertionResult r1 = AssertionSuccess();
5039 AssertionResult r2 = r1;
5040 // The following line is added to prevent the compiler from optimizing
5041 // away the constructor call.
5042 r1 << "abc";
5043
5044 AssertionResult r3 = r1;
5045 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
5046 EXPECT_STREQ("abc", r1.message());
5047}
5048
5049// Tests that AssertionSuccess and AssertionFailure construct
5050// AssertionResult objects as expected.
5051TEST(AssertionResultTest, ConstructionWorks) {
5052 AssertionResult r1 = AssertionSuccess();
5053 EXPECT_TRUE(r1);
5054 EXPECT_STREQ("", r1.message());
5055
5056 AssertionResult r2 = AssertionSuccess() << "abc";
5057 EXPECT_TRUE(r2);
5058 EXPECT_STREQ("abc", r2.message());
5059
5060 AssertionResult r3 = AssertionFailure();
5061 EXPECT_FALSE(r3);
5062 EXPECT_STREQ("", r3.message());
5063
5064 AssertionResult r4 = AssertionFailure() << "def";
5065 EXPECT_FALSE(r4);
5066 EXPECT_STREQ("def", r4.message());
5067
5068 AssertionResult r5 = AssertionFailure(Message() << "ghi");
5069 EXPECT_FALSE(r5);
5070 EXPECT_STREQ("ghi", r5.message());
5071}
5072
5073// Tests that the negation flips the predicate result but keeps the message.
5074TEST(AssertionResultTest, NegationWorks) {
5075 AssertionResult r1 = AssertionSuccess() << "abc";
5076 EXPECT_FALSE(!r1);
5077 EXPECT_STREQ("abc", (!r1).message());
5078
5079 AssertionResult r2 = AssertionFailure() << "def";
5080 EXPECT_TRUE(!r2);
5081 EXPECT_STREQ("def", (!r2).message());
5082}
5083
5084TEST(AssertionResultTest, StreamingWorks) {
5085 AssertionResult r = AssertionSuccess();
5086 r << "abc" << 'd' << 0 << true;
5087 EXPECT_STREQ("abcd0true", r.message());
5088}
5089
5090TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5091 AssertionResult r = AssertionSuccess();
5092 r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5093 EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5094}
5095
5096// The next test uses explicit conversion operators
5097
5098TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5099 struct ExplicitlyConvertibleToBool {
5100 explicit operator bool() const { return value; }
5101 bool value;
5102 };
5103 ExplicitlyConvertibleToBool v1 = {false};
5104 ExplicitlyConvertibleToBool v2 = {true};
5105 EXPECT_FALSE(v1);
5106 EXPECT_TRUE(v2);
5107}
5108
5110 operator AssertionResult() const { return AssertionResult(true); }
5111};
5112
5113TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5115 EXPECT_TRUE(obj);
5116}
5117
5118// Tests streaming a user type whose definition and operator << are
5119// both in the global namespace.
5120class Base {
5121 public:
5122 explicit Base(int an_x) : x_(an_x) {}
5123 int x() const { return x_; }
5124
5125 private:
5126 int x_;
5127};
5128std::ostream& operator<<(std::ostream& os, const Base& val) {
5129 return os << val.x();
5130}
5131std::ostream& operator<<(std::ostream& os, const Base* pointer) {
5132 return os << "(" << pointer->x() << ")";
5133}
5134
5135TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5136 Message msg;
5137 Base a(1);
5138
5139 msg << a << &a; // Uses ::operator<<.
5140 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5141}
5142
5143// Tests streaming a user type whose definition and operator<< are
5144// both in an unnamed namespace.
5145namespace {
5146class MyTypeInUnnamedNameSpace : public Base {
5147 public:
5148 explicit MyTypeInUnnamedNameSpace(int an_x) : Base(an_x) {}
5149};
5150std::ostream& operator<<(std::ostream& os,
5151 const MyTypeInUnnamedNameSpace& val) {
5152 return os << val.x();
5153}
5154std::ostream& operator<<(std::ostream& os,
5155 const MyTypeInUnnamedNameSpace* pointer) {
5156 return os << "(" << pointer->x() << ")";
5157}
5158} // namespace
5159
5160TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5161 Message msg;
5162 MyTypeInUnnamedNameSpace a(1);
5163
5164 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
5165 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5166}
5167
5168// Tests streaming a user type whose definition and operator<< are
5169// both in a user namespace.
5170namespace namespace1 {
5171class MyTypeInNameSpace1 : public Base {
5172 public:
5173 explicit MyTypeInNameSpace1(int an_x) : Base(an_x) {}
5174};
5175std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1& val) {
5176 return os << val.x();
5177}
5178std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1* pointer) {
5179 return os << "(" << pointer->x() << ")";
5180}
5181} // namespace namespace1
5182
5183TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5184 Message msg;
5186
5187 msg << a << &a; // Uses namespace1::operator<<.
5188 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5189}
5190
5191// Tests streaming a user type whose definition is in a user namespace
5192// but whose operator<< is in the global namespace.
5193namespace namespace2 {
5195 public:
5196 explicit MyTypeInNameSpace2(int an_x) : Base(an_x) {}
5197};
5198} // namespace namespace2
5199std::ostream& operator<<(std::ostream& os,
5200 const namespace2::MyTypeInNameSpace2& val) {
5201 return os << val.x();
5202}
5203std::ostream& operator<<(std::ostream& os,
5204 const namespace2::MyTypeInNameSpace2* pointer) {
5205 return os << "(" << pointer->x() << ")";
5206}
5207
5208TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5209 Message msg;
5211
5212 msg << a << &a; // Uses ::operator<<.
5213 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5214}
5215
5216// Tests streaming NULL pointers to testing::Message.
5217TEST(MessageTest, NullPointers) {
5218 Message msg;
5219 char* const p1 = nullptr;
5220 unsigned char* const p2 = nullptr;
5221 int* p3 = nullptr;
5222 double* p4 = nullptr;
5223 bool* p5 = nullptr;
5224 Message* p6 = nullptr;
5225
5226 msg << p1 << p2 << p3 << p4 << p5 << p6;
5227 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", msg.GetString().c_str());
5228}
5229
5230// Tests streaming wide strings to testing::Message.
5231TEST(MessageTest, WideStrings) {
5232 // Streams a NULL of type const wchar_t*.
5233 const wchar_t* const_wstr = nullptr;
5234 EXPECT_STREQ("(null)", (Message() << const_wstr).GetString().c_str());
5235
5236 // Streams a NULL of type wchar_t*.
5237 wchar_t* wstr = nullptr;
5238 EXPECT_STREQ("(null)", (Message() << wstr).GetString().c_str());
5239
5240 // Streams a non-NULL of type const wchar_t*.
5241 const_wstr = L"abc\x8119";
5242 EXPECT_STREQ("abc\xe8\x84\x99",
5243 (Message() << const_wstr).GetString().c_str());
5244
5245 // Streams a non-NULL of type wchar_t*.
5246 wstr = const_cast<wchar_t*>(const_wstr);
5247 EXPECT_STREQ("abc\xe8\x84\x99", (Message() << wstr).GetString().c_str());
5248}
5249
5250// This line tests that we can define tests in the testing namespace.
5251namespace testing {
5252
5253// Tests the TestInfo class.
5254
5255class TestInfoTest : public Test {
5256 protected:
5257 static const TestInfo* GetTestInfo(const char* test_name) {
5258 const TestSuite* const test_suite =
5259 GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr);
5260
5261 for (int i = 0; i < test_suite->total_test_count(); ++i) {
5262 const TestInfo* const test_info = test_suite->GetTestInfo(i);
5263 if (strcmp(test_name, test_info->name()) == 0) return test_info;
5264 }
5265 return nullptr;
5266 }
5267
5268 static const TestResult* GetTestResult(const TestInfo* test_info) {
5269 return test_info->result();
5270 }
5271};
5272
5273// Tests TestInfo::test_case_name() and TestInfo::name().
5275 const TestInfo* const test_info = GetTestInfo("Names");
5276
5277 ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
5278 ASSERT_STREQ("Names", test_info->name());
5279}
5280
5281// Tests TestInfo::result().
5283 const TestInfo* const test_info = GetTestInfo("result");
5284
5285 // Initially, there is no TestPartResult for this test.
5286 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5287
5288 // After the previous assertion, there is still none.
5289 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5290}
5291
5292#define VERIFY_CODE_LOCATION \
5293 const int expected_line = __LINE__ - 1; \
5294 const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
5295 ASSERT_TRUE(test_info); \
5296 EXPECT_STREQ(__FILE__, test_info->file()); \
5297 EXPECT_EQ(expected_line, test_info->line())
5298
5299// clang-format off
5300TEST(CodeLocationForTEST, Verify) {
5302}
5303
5304class CodeLocationForTESTF : public Test {};
5305
5309
5311
5315
5317
5318template <typename T>
5320
5322
5326
5327template <typename T>
5329
5331
5335
5337
5339
5340#undef VERIFY_CODE_LOCATION
5341// clang-format on
5342
5343// Tests setting up and tearing down a test case.
5344// Legacy API is deprecated but still available
5345#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5346class SetUpTestCaseTest : public Test {
5347 protected:
5348 // This will be called once before the first test in this test case
5349 // is run.
5350 static void SetUpTestCase() {
5351 printf("Setting up the test case . . .\n");
5352
5353 // Initializes some shared resource. In this simple example, we
5354 // just create a C string. More complex stuff can be done if
5355 // desired.
5356 shared_resource_ = "123";
5357
5358 // Increments the number of test cases that have been set up.
5359 counter_++;
5360
5361 // SetUpTestCase() should be called only once.
5362 EXPECT_EQ(1, counter_);
5363 }
5364
5365 // This will be called once after the last test in this test case is
5366 // run.
5367 static void TearDownTestCase() {
5368 printf("Tearing down the test case . . .\n");
5369
5370 // Decrements the number of test cases that have been set up.
5371 counter_--;
5372
5373 // TearDownTestCase() should be called only once.
5374 EXPECT_EQ(0, counter_);
5375
5376 // Cleans up the shared resource.
5377 shared_resource_ = nullptr;
5378 }
5379
5380 // This will be called before each test in this test case.
5381 void SetUp() override {
5382 // SetUpTestCase() should be called only once, so counter_ should
5383 // always be 1.
5384 EXPECT_EQ(1, counter_);
5385 }
5386
5387 // Number of test cases that have been set up.
5388 static int counter_;
5389
5390 // Some resource to be shared by all tests in this test case.
5391 static const char* shared_resource_;
5392};
5393
5395const char* SetUpTestCaseTest::shared_resource_ = nullptr;
5396
5397// A test that uses the shared resource.
5398TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
5399
5400// Another test that uses the shared resource.
5401TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); }
5402#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5403
5404// Tests SetupTestSuite/TearDown TestSuite
5405class SetUpTestSuiteTest : public Test {
5406 protected:
5407 // This will be called once before the first test in this test case
5408 // is run.
5409 static void SetUpTestSuite() {
5410 printf("Setting up the test suite . . .\n");
5411
5412 // Initializes some shared resource. In this simple example, we
5413 // just create a C string. More complex stuff can be done if
5414 // desired.
5415 shared_resource_ = "123";
5416
5417 // Increments the number of test cases that have been set up.
5418 counter_++;
5419
5420 // SetUpTestSuite() should be called only once.
5421 EXPECT_EQ(1, counter_);
5422 }
5423
5424 // This will be called once after the last test in this test case is
5425 // run.
5426 static void TearDownTestSuite() {
5427 printf("Tearing down the test suite . . .\n");
5428
5429 // Decrements the number of test suites that have been set up.
5430 counter_--;
5431
5432 // TearDownTestSuite() should be called only once.
5433 EXPECT_EQ(0, counter_);
5434
5435 // Cleans up the shared resource.
5436 shared_resource_ = nullptr;
5437 }
5438
5439 // This will be called before each test in this test case.
5440 void SetUp() override {
5441 // SetUpTestSuite() should be called only once, so counter_ should
5442 // always be 1.
5443 EXPECT_EQ(1, counter_);
5444 }
5445
5446 // Number of test suites that have been set up.
5447 static int counter_;
5448
5449 // Some resource to be shared by all tests in this test case.
5450 static const char* shared_resource_;
5451};
5452
5454const char* SetUpTestSuiteTest::shared_resource_ = nullptr;
5455
5456// A test that uses the shared resource.
5457TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) {
5458 EXPECT_STRNE(nullptr, shared_resource_);
5459}
5460
5461// Another test that uses the shared resource.
5462TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
5463 EXPECT_STREQ("123", shared_resource_);
5464}
5465
5466// The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.
5467
5468// The Flags struct stores a copy of all Google Test flags.
5469struct Flags {
5470 // Constructs a Flags struct where each flag has its default value.
5472 : also_run_disabled_tests(false),
5473 break_on_failure(false),
5474 catch_exceptions(false),
5475 death_test_use_fork(false),
5476 fail_fast(false),
5477 filter(""),
5478 list_tests(false),
5479 output(""),
5480 brief(false),
5481 print_time(true),
5482 random_seed(0),
5483 repeat(1),
5485 shuffle(false),
5486 stack_trace_depth(kMaxStackTraceDepth),
5487 stream_result_to(""),
5488 throw_on_failure(false) {}
5489
5490 // Factory methods.
5491
5492 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5493 // the given value.
5495 Flags flags;
5497 return flags;
5498 }
5499
5500 // Creates a Flags struct where the gtest_break_on_failure flag has
5501 // the given value.
5503 Flags flags;
5505 return flags;
5506 }
5507
5508 // Creates a Flags struct where the gtest_catch_exceptions flag has
5509 // the given value.
5511 Flags flags;
5513 return flags;
5514 }
5515
5516 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5517 // the given value.
5519 Flags flags;
5521 return flags;
5522 }
5523
5524 // Creates a Flags struct where the gtest_fail_fast flag has
5525 // the given value.
5526 static Flags FailFast(bool fail_fast) {
5527 Flags flags;
5528 flags.fail_fast = fail_fast;
5529 return flags;
5530 }
5531
5532 // Creates a Flags struct where the gtest_filter flag has the given
5533 // value.
5534 static Flags Filter(const char* filter) {
5535 Flags flags;
5536 flags.filter = filter;
5537 return flags;
5538 }
5539
5540 // Creates a Flags struct where the gtest_list_tests flag has the
5541 // given value.
5543 Flags flags;
5544 flags.list_tests = list_tests;
5545 return flags;
5546 }
5547
5548 // Creates a Flags struct where the gtest_output flag has the given
5549 // value.
5550 static Flags Output(const char* output) {
5551 Flags flags;
5552 flags.output = output;
5553 return flags;
5554 }
5555
5556 // Creates a Flags struct where the gtest_brief flag has the given
5557 // value.
5558 static Flags Brief(bool brief) {
5559 Flags flags;
5560 flags.brief = brief;
5561 return flags;
5562 }
5563
5564 // Creates a Flags struct where the gtest_print_time flag has the given
5565 // value.
5567 Flags flags;
5568 flags.print_time = print_time;
5569 return flags;
5570 }
5571
5572 // Creates a Flags struct where the gtest_random_seed flag has the given
5573 // value.
5574 static Flags RandomSeed(int32_t random_seed) {
5575 Flags flags;
5576 flags.random_seed = random_seed;
5577 return flags;
5578 }
5579
5580 // Creates a Flags struct where the gtest_repeat flag has the given
5581 // value.
5582 static Flags Repeat(int32_t repeat) {
5583 Flags flags;
5584 flags.repeat = repeat;
5585 return flags;
5586 }
5587
5588 // Creates a Flags struct where the gtest_recreate_environments_when_repeating
5589 // flag has the given value.
5597
5598 // Creates a Flags struct where the gtest_shuffle flag has the given
5599 // value.
5600 static Flags Shuffle(bool shuffle) {
5601 Flags flags;
5602 flags.shuffle = shuffle;
5603 return flags;
5604 }
5605
5606 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5607 // the given value.
5609 Flags flags;
5611 return flags;
5612 }
5613
5614 // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5615 // the given value.
5617 Flags flags;
5619 return flags;
5620 }
5621
5622 // Creates a Flags struct where the gtest_throw_on_failure flag has
5623 // the given value.
5625 Flags flags;
5627 return flags;
5628 }
5629
5630 // These fields store the flag values.
5636 const char* filter;
5638 const char* output;
5639 bool brief;
5642 int32_t repeat;
5646 const char* stream_result_to;
5648};
5649
5650// Fixture for testing ParseGoogleTestFlagsOnly().
5651class ParseFlagsTest : public Test {
5652 protected:
5653 // Clears the flags before each test.
5654 void SetUp() override {
5655 GTEST_FLAG_SET(also_run_disabled_tests, false);
5656 GTEST_FLAG_SET(break_on_failure, false);
5657 GTEST_FLAG_SET(catch_exceptions, false);
5658 GTEST_FLAG_SET(death_test_use_fork, false);
5659 GTEST_FLAG_SET(fail_fast, false);
5660 GTEST_FLAG_SET(filter, "");
5661 GTEST_FLAG_SET(list_tests, false);
5662 GTEST_FLAG_SET(output, "");
5663 GTEST_FLAG_SET(brief, false);
5664 GTEST_FLAG_SET(print_time, true);
5665 GTEST_FLAG_SET(random_seed, 0);
5666 GTEST_FLAG_SET(repeat, 1);
5667 GTEST_FLAG_SET(recreate_environments_when_repeating, true);
5668 GTEST_FLAG_SET(shuffle, false);
5669 GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
5670 GTEST_FLAG_SET(stream_result_to, "");
5671 GTEST_FLAG_SET(throw_on_failure, false);
5672 }
5673
5674 // Asserts that two narrow or wide string arrays are equal.
5675 template <typename CharType>
5676 static void AssertStringArrayEq(int size1, CharType** array1, int size2,
5677 CharType** array2) {
5678 ASSERT_EQ(size1, size2) << " Array sizes different.";
5679
5680 for (int i = 0; i != size1; i++) {
5681 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5682 }
5683 }
5684
5685 // Verifies that the flag values match the expected values.
5686 static void CheckFlags(const Flags& expected) {
5688 GTEST_FLAG_GET(also_run_disabled_tests));
5689 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure));
5690 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions));
5692 GTEST_FLAG_GET(death_test_use_fork));
5693 EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast));
5694 EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str());
5695 EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests));
5696 EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str());
5697 EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief));
5698 EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time));
5699 EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed));
5700 EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat));
5702 GTEST_FLAG_GET(recreate_environments_when_repeating));
5703 EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle));
5704 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth));
5706 GTEST_FLAG_GET(stream_result_to).c_str());
5707 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure));
5708 }
5709
5710 // Parses a command line (specified by argc1 and argv1), then
5711 // verifies that the flag values are expected and that the
5712 // recognized flags are removed from the command line.
5713 template <typename CharType>
5714 static void TestParsingFlags(int argc1, const CharType** argv1, int argc2,
5715 const CharType** argv2, const Flags& expected,
5716 bool should_print_help) {
5717 const bool saved_help_flag = ::testing::internal::g_help_flag;
5719
5720#if GTEST_HAS_STREAM_REDIRECTION
5721 CaptureStdout();
5722#endif
5723
5724 // Parses the command line.
5725 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5726
5727#if GTEST_HAS_STREAM_REDIRECTION
5728 const std::string captured_stdout = GetCapturedStdout();
5729#endif
5730
5731 // Verifies the flag values.
5732 CheckFlags(expected);
5733
5734 // Verifies that the recognized flags are removed from the command
5735 // line.
5736 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5737
5738 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5739 // help message for the flags it recognizes.
5740 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5741
5742#if GTEST_HAS_STREAM_REDIRECTION
5743 const char* const expected_help_fragment =
5744 "This program contains tests written using";
5745 if (should_print_help) {
5746 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5747 } else {
5748 EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment,
5749 captured_stdout);
5750 }
5751#endif // GTEST_HAS_STREAM_REDIRECTION
5752
5753 ::testing::internal::g_help_flag = saved_help_flag;
5754 }
5755
5756 // This macro wraps TestParsingFlags s.t. the user doesn't need
5757 // to specify the array sizes.
5758
5759#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5760 TestParsingFlags(sizeof(argv1) / sizeof(*argv1) - 1, argv1, \
5761 sizeof(argv2) / sizeof(*argv2) - 1, argv2, expected, \
5762 should_print_help)
5763};
5764
5765// Tests parsing an empty command line.
5767 const char* argv[] = {nullptr};
5768
5769 const char* argv2[] = {nullptr};
5770
5771 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5772}
5773
5774// Tests parsing a command line that has no flag.
5776 const char* argv[] = {"foo.exe", nullptr};
5777
5778 const char* argv2[] = {"foo.exe", nullptr};
5779
5780 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5781}
5782
5783// Tests parsing --gtest_fail_fast.
5785 const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
5786
5787 const char* argv2[] = {"foo.exe", nullptr};
5788
5789 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
5790}
5791
5792// Tests parsing an empty --gtest_filter flag.
5793TEST_F(ParseFlagsTest, FilterEmpty) {
5794 const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
5795
5796 const char* argv2[] = {"foo.exe", nullptr};
5797
5798 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5799}
5800
5801// Tests parsing a non-empty --gtest_filter flag.
5802TEST_F(ParseFlagsTest, FilterNonEmpty) {
5803 const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr};
5804
5805 const char* argv2[] = {"foo.exe", nullptr};
5806
5807 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5808}
5809
5810// Tests parsing --gtest_break_on_failure.
5811TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {
5812 const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr};
5813
5814 const char* argv2[] = {"foo.exe", nullptr};
5815
5816 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5817}
5818
5819// Tests parsing --gtest_break_on_failure=0.
5820TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {
5821 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr};
5822
5823 const char* argv2[] = {"foo.exe", nullptr};
5824
5825 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5826}
5827
5828// Tests parsing --gtest_break_on_failure=f.
5829TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {
5830 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr};
5831
5832 const char* argv2[] = {"foo.exe", nullptr};
5833
5834 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5835}
5836
5837// Tests parsing --gtest_break_on_failure=F.
5838TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {
5839 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr};
5840
5841 const char* argv2[] = {"foo.exe", nullptr};
5842
5843 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5844}
5845
5846// Tests parsing a --gtest_break_on_failure flag that has a "true"
5847// definition.
5848TEST_F(ParseFlagsTest, BreakOnFailureTrue) {
5849 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr};
5850
5851 const char* argv2[] = {"foo.exe", nullptr};
5852
5853 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5854}
5855
5856// Tests parsing --gtest_catch_exceptions.
5857TEST_F(ParseFlagsTest, CatchExceptions) {
5858 const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr};
5859
5860 const char* argv2[] = {"foo.exe", nullptr};
5861
5862 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5863}
5864
5865// Tests parsing --gtest_death_test_use_fork.
5866TEST_F(ParseFlagsTest, DeathTestUseFork) {
5867 const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr};
5868
5869 const char* argv2[] = {"foo.exe", nullptr};
5870
5871 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5872}
5873
5874// Tests having the same flag twice with different values. The
5875// expected behavior is that the one coming last takes precedence.
5876TEST_F(ParseFlagsTest, DuplicatedFlags) {
5877 const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b",
5878 nullptr};
5879
5880 const char* argv2[] = {"foo.exe", nullptr};
5881
5882 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5883}
5884
5885// Tests having an unrecognized flag on the command line.
5886TEST_F(ParseFlagsTest, UnrecognizedFlag) {
5887 const char* argv[] = {"foo.exe", "--gtest_break_on_failure",
5888 "bar", // Unrecognized by Google Test.
5889 "--gtest_filter=b", nullptr};
5890
5891 const char* argv2[] = {"foo.exe", "bar", nullptr};
5892
5893 Flags flags;
5894 flags.break_on_failure = true;
5895 flags.filter = "b";
5896 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5897}
5898
5899// Tests having a --gtest_list_tests flag
5900TEST_F(ParseFlagsTest, ListTestsFlag) {
5901 const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr};
5902
5903 const char* argv2[] = {"foo.exe", nullptr};
5904
5905 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5906}
5907
5908// Tests having a --gtest_list_tests flag with a "true" value
5909TEST_F(ParseFlagsTest, ListTestsTrue) {
5910 const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr};
5911
5912 const char* argv2[] = {"foo.exe", nullptr};
5913
5914 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
5915}
5916
5917// Tests having a --gtest_list_tests flag with a "false" value
5918TEST_F(ParseFlagsTest, ListTestsFalse) {
5919 const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr};
5920
5921 const char* argv2[] = {"foo.exe", nullptr};
5922
5923 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5924}
5925
5926// Tests parsing --gtest_list_tests=f.
5927TEST_F(ParseFlagsTest, ListTestsFalse_f) {
5928 const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr};
5929
5930 const char* argv2[] = {"foo.exe", nullptr};
5931
5932 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5933}
5934
5935// Tests parsing --gtest_list_tests=F.
5936TEST_F(ParseFlagsTest, ListTestsFalse_F) {
5937 const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr};
5938
5939 const char* argv2[] = {"foo.exe", nullptr};
5940
5941 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
5942}
5943
5944// Tests parsing --gtest_output=xml
5946 const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
5947
5948 const char* argv2[] = {"foo.exe", nullptr};
5949
5950 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
5951}
5952
5953// Tests parsing --gtest_output=xml:file
5954TEST_F(ParseFlagsTest, OutputXmlFile) {
5955 const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr};
5956
5957 const char* argv2[] = {"foo.exe", nullptr};
5958
5959 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
5960}
5961
5962// Tests parsing --gtest_output=xml:directory/path/
5963TEST_F(ParseFlagsTest, OutputXmlDirectory) {
5964 const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/",
5965 nullptr};
5966
5967 const char* argv2[] = {"foo.exe", nullptr};
5968
5969 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"),
5970 false);
5971}
5972
5973// Tests having a --gtest_brief flag
5975 const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
5976
5977 const char* argv2[] = {"foo.exe", nullptr};
5978
5979 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
5980}
5981
5982// Tests having a --gtest_brief flag with a "true" value
5983TEST_F(ParseFlagsTest, BriefFlagTrue) {
5984 const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
5985
5986 const char* argv2[] = {"foo.exe", nullptr};
5987
5988 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
5989}
5990
5991// Tests having a --gtest_brief flag with a "false" value
5992TEST_F(ParseFlagsTest, BriefFlagFalse) {
5993 const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
5994
5995 const char* argv2[] = {"foo.exe", nullptr};
5996
5997 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
5998}
5999
6000// Tests having a --gtest_print_time flag
6001TEST_F(ParseFlagsTest, PrintTimeFlag) {
6002 const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
6003
6004 const char* argv2[] = {"foo.exe", nullptr};
6005
6006 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6007}
6008
6009// Tests having a --gtest_print_time flag with a "true" value
6010TEST_F(ParseFlagsTest, PrintTimeTrue) {
6011 const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr};
6012
6013 const char* argv2[] = {"foo.exe", nullptr};
6014
6015 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6016}
6017
6018// Tests having a --gtest_print_time flag with a "false" value
6019TEST_F(ParseFlagsTest, PrintTimeFalse) {
6020 const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr};
6021
6022 const char* argv2[] = {"foo.exe", nullptr};
6023
6024 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6025}
6026
6027// Tests parsing --gtest_print_time=f.
6028TEST_F(ParseFlagsTest, PrintTimeFalse_f) {
6029 const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr};
6030
6031 const char* argv2[] = {"foo.exe", nullptr};
6032
6033 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6034}
6035
6036// Tests parsing --gtest_print_time=F.
6037TEST_F(ParseFlagsTest, PrintTimeFalse_F) {
6038 const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr};
6039
6040 const char* argv2[] = {"foo.exe", nullptr};
6041
6042 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6043}
6044
6045// Tests parsing --gtest_random_seed=number
6047 const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr};
6048
6049 const char* argv2[] = {"foo.exe", nullptr};
6050
6051 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6052}
6053
6054// Tests parsing --gtest_repeat=number
6056 const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr};
6057
6058 const char* argv2[] = {"foo.exe", nullptr};
6059
6060 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
6061}
6062
6063// Tests parsing --gtest_recreate_environments_when_repeating
6064TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) {
6065 const char* argv[] = {
6066 "foo.exe",
6067 "--gtest_recreate_environments_when_repeating=0",
6068 nullptr,
6069 };
6070
6071 const char* argv2[] = {"foo.exe", nullptr};
6072
6074 argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false);
6075}
6076
6077// Tests having a --gtest_also_run_disabled_tests flag
6078TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
6079 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
6080
6081 const char* argv2[] = {"foo.exe", nullptr};
6082
6084 false);
6085}
6086
6087// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
6088TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {
6089 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1",
6090 nullptr};
6091
6092 const char* argv2[] = {"foo.exe", nullptr};
6093
6095 false);
6096}
6097
6098// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
6099TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {
6100 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0",
6101 nullptr};
6102
6103 const char* argv2[] = {"foo.exe", nullptr};
6104
6106 false);
6107}
6108
6109// Tests parsing --gtest_shuffle.
6110TEST_F(ParseFlagsTest, ShuffleWithoutValue) {
6111 const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr};
6112
6113 const char* argv2[] = {"foo.exe", nullptr};
6114
6115 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6116}
6117
6118// Tests parsing --gtest_shuffle=0.
6119TEST_F(ParseFlagsTest, ShuffleFalse_0) {
6120 const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr};
6121
6122 const char* argv2[] = {"foo.exe", nullptr};
6123
6124 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6125}
6126
6127// Tests parsing a --gtest_shuffle flag that has a "true" definition.
6128TEST_F(ParseFlagsTest, ShuffleTrue) {
6129 const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr};
6130
6131 const char* argv2[] = {"foo.exe", nullptr};
6132
6133 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6134}
6135
6136// Tests parsing --gtest_stack_trace_depth=number.
6137TEST_F(ParseFlagsTest, StackTraceDepth) {
6138 const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr};
6139
6140 const char* argv2[] = {"foo.exe", nullptr};
6141
6142 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6143}
6144
6145TEST_F(ParseFlagsTest, StreamResultTo) {
6146 const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234",
6147 nullptr};
6148
6149 const char* argv2[] = {"foo.exe", nullptr};
6150
6151 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6152 Flags::StreamResultTo("localhost:1234"), false);
6153}
6154
6155// Tests parsing --gtest_throw_on_failure.
6156TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
6157 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr};
6158
6159 const char* argv2[] = {"foo.exe", nullptr};
6160
6161 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6162}
6163
6164// Tests parsing --gtest_throw_on_failure=0.
6165TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {
6166 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr};
6167
6168 const char* argv2[] = {"foo.exe", nullptr};
6169
6170 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
6171}
6172
6173// Tests parsing a --gtest_throw_on_failure flag that has a "true"
6174// definition.
6175TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
6176 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr};
6177
6178 const char* argv2[] = {"foo.exe", nullptr};
6179
6180 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6181}
6182
6183// Tests parsing a bad --gtest_filter flag.
6185 const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
6186
6187 const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
6188
6189#if defined(GTEST_HAS_ABSL) && defined(GTEST_HAS_DEATH_TEST)
6190 // Invalid flag arguments are a fatal error when using the Abseil Flags.
6191 EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true),
6192 testing::ExitedWithCode(1),
6193 "ERROR: Missing the value for the flag 'gtest_filter'");
6194#elif !defined(GTEST_HAS_ABSL)
6195 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
6196#else
6197 static_cast<void>(argv);
6198 static_cast<void>(argv2);
6199#endif
6200}
6201
6202// Tests parsing --gtest_output (invalid).
6203TEST_F(ParseFlagsTest, OutputEmpty) {
6204 const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
6205
6206 const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
6207
6208#if defined(GTEST_HAS_ABSL) && defined(GTEST_HAS_DEATH_TEST)
6209 // Invalid flag arguments are a fatal error when using the Abseil Flags.
6210 EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true),
6211 testing::ExitedWithCode(1),
6212 "ERROR: Missing the value for the flag 'gtest_output'");
6213#elif !defined(GTEST_HAS_ABSL)
6214 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
6215#else
6216 static_cast<void>(argv);
6217 static_cast<void>(argv2);
6218#endif
6219}
6220
6221#ifdef GTEST_HAS_ABSL
6222TEST_F(ParseFlagsTest, AbseilPositionalFlags) {
6223 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", "--",
6224 "--other_flag", nullptr};
6225
6226 // When using Abseil flags, it should be possible to pass flags not recognized
6227 // using "--" to delimit positional arguments. These flags should be returned
6228 // though argv.
6229 const char* argv2[] = {"foo.exe", "--other_flag", nullptr};
6230
6231 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6232}
6233#endif
6234
6235TEST_F(ParseFlagsTest, UnrecognizedFlags) {
6236 const char* argv[] = {"foo.exe", "--gtest_filter=abcd", "--other_flag",
6237 nullptr};
6238
6239 const char* argv2[] = {"foo.exe", "--other_flag", nullptr};
6240
6241 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abcd"), false);
6242}
6243
6244#ifdef GTEST_OS_WINDOWS
6245// Tests parsing wide strings.
6246TEST_F(ParseFlagsTest, WideStrings) {
6247 const wchar_t* argv[] = {L"foo.exe",
6248 L"--gtest_filter=Foo*",
6249 L"--gtest_list_tests=1",
6250 L"--gtest_break_on_failure",
6251 L"--non_gtest_flag",
6252 NULL};
6253
6254 const wchar_t* argv2[] = {L"foo.exe", L"--non_gtest_flag", NULL};
6255
6256 Flags expected_flags;
6257 expected_flags.break_on_failure = true;
6258 expected_flags.filter = "Foo*";
6259 expected_flags.list_tests = true;
6260
6261 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6262}
6263#endif // GTEST_OS_WINDOWS
6264
6265#if GTEST_USE_OWN_FLAGFILE_FLAG_
6266class FlagfileTest : public ParseFlagsTest {
6267 public:
6268 void SetUp() override {
6269 ParseFlagsTest::SetUp();
6270
6271 testdata_path_.Set(internal::FilePath(
6272 testing::TempDir() + internal::GetCurrentExecutableName().string() +
6273 "_flagfile_test"));
6275 EXPECT_TRUE(testdata_path_.CreateFolder());
6276 }
6277
6278 void TearDown() override {
6280 ParseFlagsTest::TearDown();
6281 }
6282
6283 internal::FilePath CreateFlagfile(const char* contents) {
6284 internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
6285 testdata_path_, internal::FilePath("unique"), "txt"));
6286 FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
6287 fprintf(f, "%s", contents);
6288 fclose(f);
6289 return file_path;
6290 }
6291
6292 private:
6293 internal::FilePath testdata_path_;
6294};
6295
6296// Tests an empty flagfile.
6297TEST_F(FlagfileTest, Empty) {
6298 internal::FilePath flagfile_path(CreateFlagfile(""));
6299 std::string flagfile_flag =
6300 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6301
6302 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6303
6304 const char* argv2[] = {"foo.exe", nullptr};
6305
6306 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
6307}
6308
6309// Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
6310TEST_F(FlagfileTest, FilterNonEmpty) {
6311 internal::FilePath flagfile_path(
6312 CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc"));
6313 std::string flagfile_flag =
6314 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6315
6316 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6317
6318 const char* argv2[] = {"foo.exe", nullptr};
6319
6320 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
6321}
6322
6323// Tests passing several flags via --gtest_flagfile.
6324TEST_F(FlagfileTest, SeveralFlags) {
6325 internal::FilePath flagfile_path(
6326 CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc\n"
6327 "--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
6328 "--" GTEST_FLAG_PREFIX_ "list_tests"));
6329 std::string flagfile_flag =
6330 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6331
6332 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6333
6334 const char* argv2[] = {"foo.exe", nullptr};
6335
6336 Flags expected_flags;
6337 expected_flags.break_on_failure = true;
6338 expected_flags.filter = "abc";
6339 expected_flags.list_tests = true;
6340
6341 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6342}
6343#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6344
6345// Tests current_test_info() in UnitTest.
6347 protected:
6348 // Tests that current_test_info() returns NULL before the first test in
6349 // the test case is run.
6350 static void SetUpTestSuite() {
6351 // There should be no tests running at this point.
6352 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
6353 EXPECT_TRUE(test_info == nullptr)
6354 << "There should be no tests running at this point.";
6355 }
6356
6357 // Tests that current_test_info() returns NULL after the last test in
6358 // the test case has run.
6359 static void TearDownTestSuite() {
6360 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
6361 EXPECT_TRUE(test_info == nullptr)
6362 << "There should be no tests running at this point.";
6363 }
6364};
6365
6366// Tests that current_test_info() returns TestInfo for currently running
6367// test by checking the expected test name against the actual one.
6368TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
6369 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
6370 ASSERT_TRUE(nullptr != test_info)
6371 << "There is a test running so we should have a valid TestInfo.";
6372 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6373 << "Expected the name of the currently running test suite.";
6374 EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
6375 << "Expected the name of the currently running test.";
6376}
6377
6378// Tests that current_test_info() returns TestInfo for currently running
6379// test by checking the expected test name against the actual one. We
6380// use this test to see that the TestInfo object actually changed from
6381// the previous invocation.
6382TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
6383 const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
6384 ASSERT_TRUE(nullptr != test_info)
6385 << "There is a test running so we should have a valid TestInfo.";
6386 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6387 << "Expected the name of the currently running test suite.";
6388 EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
6389 << "Expected the name of the currently running test.";
6390}
6391
6392} // namespace testing
6393
6394// These two lines test that we can define tests in a namespace that
6395// has the name "testing" and is nested in another namespace.
6396namespace my_namespace {
6397namespace testing {
6398
6399// Makes sure that TEST knows to use ::testing::Test instead of
6400// ::my_namespace::testing::Test.
6401class Test {};
6402
6403// Makes sure that an assertion knows to use ::testing::Message instead of
6404// ::my_namespace::testing::Message.
6405class Message {};
6406
6407// Makes sure that an assertion knows to use
6408// ::testing::AssertionResult instead of
6409// ::my_namespace::testing::AssertionResult.
6411
6412// Tests that an assertion that should succeed works as expected.
6413TEST(NestedTestingNamespaceTest, Success) {
6414 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6415}
6416
6417// Tests that an assertion that should fail works as expected.
6418TEST(NestedTestingNamespaceTest, Failure) {
6419 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6420 "This failure is expected.");
6421}
6422
6423} // namespace testing
6424} // namespace my_namespace
6425
6426// Tests that one can call superclass SetUp and TearDown methods--
6427// that is, that they are not private.
6428// No tests are based on this fixture; the test "passes" if it compiles
6429// successfully.
6431 protected:
6432 void SetUp() override { Test::SetUp(); }
6433 void TearDown() override { Test::TearDown(); }
6434};
6435
6436// StreamingAssertionsTest tests the streaming versions of a representative
6437// sample of assertions.
6438TEST(StreamingAssertionsTest, Unconditional) {
6439 SUCCEED() << "expected success";
6440 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6441 "expected failure");
6442 EXPECT_FATAL_FAILURE(FAIL() << "expected failure", "expected failure");
6443}
6444
6445#ifdef __BORLANDC__
6446// Silences warnings: "Condition is always true", "Unreachable code"
6447#pragma option push -w-ccc -w-rch
6448#endif
6449
6450TEST(StreamingAssertionsTest, Truth) {
6451 EXPECT_TRUE(true) << "unexpected failure";
6452 ASSERT_TRUE(true) << "unexpected failure";
6453 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6454 "expected failure");
6455 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6456 "expected failure");
6457}
6458
6459TEST(StreamingAssertionsTest, Truth2) {
6460 EXPECT_FALSE(false) << "unexpected failure";
6461 ASSERT_FALSE(false) << "unexpected failure";
6462 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6463 "expected failure");
6464 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6465 "expected failure");
6466}
6467
6468#ifdef __BORLANDC__
6469// Restores warnings after previous "#pragma option push" suppressed them
6470#pragma option pop
6471#endif
6472
6473TEST(StreamingAssertionsTest, IntegerEquals) {
6474 EXPECT_EQ(1, 1) << "unexpected failure";
6475 ASSERT_EQ(1, 1) << "unexpected failure";
6476 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6477 "expected failure");
6478 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6479 "expected failure");
6480}
6481
6482TEST(StreamingAssertionsTest, IntegerLessThan) {
6483 EXPECT_LT(1, 2) << "unexpected failure";
6484 ASSERT_LT(1, 2) << "unexpected failure";
6485 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6486 "expected failure");
6487 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6488 "expected failure");
6489}
6490
6491TEST(StreamingAssertionsTest, StringsEqual) {
6492 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6493 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6494 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6495 "expected failure");
6496 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6497 "expected failure");
6498}
6499
6500TEST(StreamingAssertionsTest, StringsNotEqual) {
6501 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6502 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6503 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6504 "expected failure");
6505 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6506 "expected failure");
6507}
6508
6509TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6510 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6511 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6512 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6513 "expected failure");
6514 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6515 "expected failure");
6516}
6517
6518TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6519 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6520 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6521 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6522 "expected failure");
6523 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6524 "expected failure");
6525}
6526
6527TEST(StreamingAssertionsTest, FloatingPointEquals) {
6528 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6529 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6530 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6531 "expected failure");
6532 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6533 "expected failure");
6534}
6535
6536#if GTEST_HAS_EXCEPTIONS
6537
6538TEST(StreamingAssertionsTest, Throw) {
6539 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6540 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6541 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool)
6542 << "expected failure",
6543 "expected failure");
6544 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool)
6545 << "expected failure",
6546 "expected failure");
6547}
6548
6549TEST(StreamingAssertionsTest, NoThrow) {
6550 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6551 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6553 << "expected failure",
6554 "expected failure");
6555 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << "expected failure",
6556 "expected failure");
6557}
6558
6559TEST(StreamingAssertionsTest, AnyThrow) {
6560 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6561 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6563 << "expected failure",
6564 "expected failure");
6565 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << "expected failure",
6566 "expected failure");
6567}
6568
6569#endif // GTEST_HAS_EXCEPTIONS
6570
6571// Tests that Google Test correctly decides whether to use colors in the output.
6572
6573TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6574 GTEST_FLAG_SET(color, "yes");
6575
6576 SetEnv("TERM", "xterm"); // TERM supports colors.
6577 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6578 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6579
6580 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6581 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6582 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6583}
6584
6585TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6586 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6587
6588 GTEST_FLAG_SET(color, "True");
6589 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6590
6591 GTEST_FLAG_SET(color, "t");
6592 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6593
6594 GTEST_FLAG_SET(color, "1");
6595 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6596}
6597
6598TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6599 GTEST_FLAG_SET(color, "no");
6600
6601 SetEnv("TERM", "xterm"); // TERM supports colors.
6602 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6603 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6604
6605 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6606 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6607 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6608}
6609
6610TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6611 SetEnv("TERM", "xterm"); // TERM supports colors.
6612
6613 GTEST_FLAG_SET(color, "F");
6614 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6615
6616 GTEST_FLAG_SET(color, "0");
6617 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6618
6619 GTEST_FLAG_SET(color, "unknown");
6620 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6621}
6622
6623TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6624 GTEST_FLAG_SET(color, "auto");
6625
6626 SetEnv("TERM", "xterm"); // TERM supports colors.
6627 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6628 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6629}
6630
6631TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6632 GTEST_FLAG_SET(color, "auto");
6633
6634#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW)
6635 // On Windows, we ignore the TERM variable as it's usually not set.
6636
6637 SetEnv("TERM", "dumb");
6638 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6639
6640 SetEnv("TERM", "");
6641 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6642
6643 SetEnv("TERM", "xterm");
6644 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6645#else
6646 // On non-Windows platforms, we rely on TERM to determine if the
6647 // terminal supports colors.
6648
6649 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6650 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6651
6652 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6653 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6654
6655 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6656 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6657
6658 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6659 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6660
6661 SetEnv("TERM", "xterm"); // TERM supports colors.
6662 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6663
6664 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6665 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6666
6667 SetEnv("TERM", "xterm-kitty"); // TERM supports colors.
6668 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6669
6670 SetEnv("TERM", "xterm-256color"); // TERM supports colors.
6671 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6672
6673 SetEnv("TERM", "screen"); // TERM supports colors.
6674 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6675
6676 SetEnv("TERM", "screen-256color"); // TERM supports colors.
6677 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6678
6679 SetEnv("TERM", "tmux"); // TERM supports colors.
6680 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6681
6682 SetEnv("TERM", "tmux-256color"); // TERM supports colors.
6683 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6684
6685 SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
6686 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6687
6688 SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
6689 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6690
6691 SetEnv("TERM", "linux"); // TERM supports colors.
6692 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6693
6694 SetEnv("TERM", "cygwin"); // TERM supports colors.
6695 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6696#endif // GTEST_OS_WINDOWS
6697}
6698
6699// Verifies that StaticAssertTypeEq works in a namespace scope.
6700
6701static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6702static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6703 StaticAssertTypeEq<const int, const int>();
6704
6705// Verifies that StaticAssertTypeEq works in a class.
6706
6707template <typename T>
6709 public:
6710 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6711};
6712
6713TEST(StaticAssertTypeEqTest, WorksInClass) {
6715}
6716
6717// Verifies that StaticAssertTypeEq works inside a function.
6718
6719typedef int IntAlias;
6720
6721TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6722 StaticAssertTypeEq<int, IntAlias>();
6723 StaticAssertTypeEq<int*, IntAlias*>();
6724}
6725
6726TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6727 EXPECT_FALSE(HasNonfatalFailure());
6728}
6729
6730static void FailFatally() { FAIL(); }
6731
6732TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6733 FailFatally();
6734 const bool has_nonfatal_failure = HasNonfatalFailure();
6735 ClearCurrentTestPartResults();
6736 EXPECT_FALSE(has_nonfatal_failure);
6737}
6738
6739TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6740 ADD_FAILURE();
6741 const bool has_nonfatal_failure = HasNonfatalFailure();
6742 ClearCurrentTestPartResults();
6743 EXPECT_TRUE(has_nonfatal_failure);
6744}
6745
6746TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6747 FailFatally();
6748 ADD_FAILURE();
6749 const bool has_nonfatal_failure = HasNonfatalFailure();
6750 ClearCurrentTestPartResults();
6751 EXPECT_TRUE(has_nonfatal_failure);
6752}
6753
6754// A wrapper for calling HasNonfatalFailure outside of a test body.
6758
6759TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6761}
6762
6763TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6764 ADD_FAILURE();
6765 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6766 ClearCurrentTestPartResults();
6767 EXPECT_TRUE(has_nonfatal_failure);
6768}
6769
6770TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6771 EXPECT_FALSE(HasFailure());
6772}
6773
6774TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6775 FailFatally();
6776 const bool has_failure = HasFailure();
6777 ClearCurrentTestPartResults();
6778 EXPECT_TRUE(has_failure);
6779}
6780
6781TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6782 ADD_FAILURE();
6783 const bool has_failure = HasFailure();
6784 ClearCurrentTestPartResults();
6785 EXPECT_TRUE(has_failure);
6786}
6787
6788TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6789 FailFatally();
6790 ADD_FAILURE();
6791 const bool has_failure = HasFailure();
6792 ClearCurrentTestPartResults();
6793 EXPECT_TRUE(has_failure);
6794}
6795
6796// A wrapper for calling HasFailure outside of a test body.
6798
6799TEST(HasFailureTest, WorksOutsideOfTestBody) {
6801}
6802
6803TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6804 ADD_FAILURE();
6805 const bool has_failure = HasFailureHelper();
6806 ClearCurrentTestPartResults();
6807 EXPECT_TRUE(has_failure);
6808}
6809
6811 public:
6812 TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
6813 TestListener(int* on_start_counter, bool* is_destroyed)
6814 : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {}
6815
6816 ~TestListener() override {
6817 if (is_destroyed_) *is_destroyed_ = true;
6818 }
6819
6820 protected:
6821 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6822 if (on_start_counter_ != nullptr) (*on_start_counter_)++;
6823 }
6824
6825 private:
6826 int* on_start_counter_;
6827 bool* is_destroyed_;
6828};
6829
6830// Tests the constructor.
6831TEST(TestEventListenersTest, ConstructionWorks) {
6832 TestEventListeners listeners;
6833
6835 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
6836 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
6837}
6838
6839// Tests that the TestEventListeners destructor deletes all the listeners it
6840// owns.
6841TEST(TestEventListenersTest, DestructionWorks) {
6842 bool default_result_printer_is_destroyed = false;
6843 bool default_xml_printer_is_destroyed = false;
6844 bool extra_listener_is_destroyed = false;
6845 TestListener* default_result_printer =
6846 new TestListener(nullptr, &default_result_printer_is_destroyed);
6847 TestListener* default_xml_printer =
6848 new TestListener(nullptr, &default_xml_printer_is_destroyed);
6849 TestListener* extra_listener =
6850 new TestListener(nullptr, &extra_listener_is_destroyed);
6851
6852 {
6853 TestEventListeners listeners;
6855 default_result_printer);
6857 default_xml_printer);
6858 listeners.Append(extra_listener);
6859 }
6860 EXPECT_TRUE(default_result_printer_is_destroyed);
6861 EXPECT_TRUE(default_xml_printer_is_destroyed);
6862 EXPECT_TRUE(extra_listener_is_destroyed);
6863}
6864
6865// Tests that a listener Append'ed to a TestEventListeners list starts
6866// receiving events.
6867TEST(TestEventListenersTest, Append) {
6868 int on_start_counter = 0;
6869 bool is_destroyed = false;
6870 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6871 {
6872 TestEventListeners listeners;
6873 listeners.Append(listener);
6876 EXPECT_EQ(1, on_start_counter);
6877 }
6878 EXPECT_TRUE(is_destroyed);
6879}
6880
6881// Tests that listeners receive events in the order they were appended to
6882// the list, except for *End requests, which must be received in the reverse
6883// order.
6885 public:
6886 SequenceTestingListener(std::vector<std::string>* vector, const char* id)
6887 : vector_(vector), id_(id) {}
6888
6889 protected:
6890 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6891 vector_->push_back(GetEventDescription("OnTestProgramStart"));
6892 }
6893
6894 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {
6895 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
6896 }
6897
6898 void OnTestIterationStart(const UnitTest& /*unit_test*/,
6899 int /*iteration*/) override {
6900 vector_->push_back(GetEventDescription("OnTestIterationStart"));
6901 }
6902
6903 void OnTestIterationEnd(const UnitTest& /*unit_test*/,
6904 int /*iteration*/) override {
6905 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
6906 }
6907
6908 private:
6909 std::string GetEventDescription(const char* method) {
6910 Message message;
6911 message << id_ << "." << method;
6912 return message.GetString();
6913 }
6914
6915 std::vector<std::string>* vector_;
6916 const char* const id_;
6917
6919 SequenceTestingListener& operator=(const SequenceTestingListener&) = delete;
6920};
6921
6922TEST(EventListenerTest, AppendKeepsOrder) {
6923 std::vector<std::string> vec;
6924 TestEventListeners listeners;
6925 listeners.Append(new SequenceTestingListener(&vec, "1st"));
6926 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
6927 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
6928
6931 ASSERT_EQ(3U, vec.size());
6932 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
6933 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
6934 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
6935
6936 vec.clear();
6939 ASSERT_EQ(3U, vec.size());
6940 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
6941 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
6942 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
6943
6944 vec.clear();
6947 ASSERT_EQ(3U, vec.size());
6948 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
6949 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
6950 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
6951
6952 vec.clear();
6955 ASSERT_EQ(3U, vec.size());
6956 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
6957 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
6958 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
6959}
6960
6961// Tests that a listener removed from a TestEventListeners list stops receiving
6962// events and is not deleted when the list is destroyed.
6963TEST(TestEventListenersTest, Release) {
6964 int on_start_counter = 0;
6965 bool is_destroyed = false;
6966 // Although Append passes the ownership of this object to the list,
6967 // the following calls release it, and we need to delete it before the
6968 // test ends.
6969 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6970 {
6971 TestEventListeners listeners;
6972 listeners.Append(listener);
6973 EXPECT_EQ(listener, listeners.Release(listener));
6976 EXPECT_TRUE(listeners.Release(listener) == nullptr);
6977 }
6978 EXPECT_EQ(0, on_start_counter);
6979 EXPECT_FALSE(is_destroyed);
6980 delete listener;
6981}
6982
6983// Tests that no events are forwarded when event forwarding is disabled.
6984TEST(EventListenerTest, SuppressEventForwarding) {
6985 int on_start_counter = 0;
6986 TestListener* listener = new TestListener(&on_start_counter, nullptr);
6987
6988 TestEventListeners listeners;
6989 listeners.Append(listener);
6995 EXPECT_EQ(0, on_start_counter);
6996}
6997
6998// Tests that events generated by Google Test are not forwarded in
6999// death test subprocesses.
7000TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprocesses) {
7002 {
7004 *GetUnitTestImpl()->listeners()))
7005 << "expected failure";
7006 },
7007 "expected failure");
7008}
7009
7010// Tests that a listener installed via SetDefaultResultPrinter() starts
7011// receiving events and is returned via default_result_printer() and that
7012// the previous default_result_printer is removed from the list and deleted.
7013TEST(EventListenerTest, default_result_printer) {
7014 int on_start_counter = 0;
7015 bool is_destroyed = false;
7016 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7017
7018 TestEventListeners listeners;
7020
7021 EXPECT_EQ(listener, listeners.default_result_printer());
7022
7025
7026 EXPECT_EQ(1, on_start_counter);
7027
7028 // Replacing default_result_printer with something else should remove it
7029 // from the list and destroy it.
7031
7032 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7033 EXPECT_TRUE(is_destroyed);
7034
7035 // After broadcasting an event the counter is still the same, indicating
7036 // the listener is not in the list anymore.
7039 EXPECT_EQ(1, on_start_counter);
7040}
7041
7042// Tests that the default_result_printer listener stops receiving events
7043// when removed via Release and that is not owned by the list anymore.
7044TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
7045 int on_start_counter = 0;
7046 bool is_destroyed = false;
7047 // Although Append passes the ownership of this object to the list,
7048 // the following calls release it, and we need to delete it before the
7049 // test ends.
7050 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7051 {
7052 TestEventListeners listeners;
7054
7055 EXPECT_EQ(listener, listeners.Release(listener));
7056 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7057 EXPECT_FALSE(is_destroyed);
7058
7059 // Broadcasting events now should not affect default_result_printer.
7062 EXPECT_EQ(0, on_start_counter);
7063 }
7064 // Destroying the list should not affect the listener now, too.
7065 EXPECT_FALSE(is_destroyed);
7066 delete listener;
7067}
7068
7069// Tests that a listener installed via SetDefaultXmlGenerator() starts
7070// receiving events and is returned via default_xml_generator() and that
7071// the previous default_xml_generator is removed from the list and deleted.
7072TEST(EventListenerTest, default_xml_generator) {
7073 int on_start_counter = 0;
7074 bool is_destroyed = false;
7075 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7076
7077 TestEventListeners listeners;
7079
7080 EXPECT_EQ(listener, listeners.default_xml_generator());
7081
7084
7085 EXPECT_EQ(1, on_start_counter);
7086
7087 // Replacing default_xml_generator with something else should remove it
7088 // from the list and destroy it.
7090
7091 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7092 EXPECT_TRUE(is_destroyed);
7093
7094 // After broadcasting an event the counter is still the same, indicating
7095 // the listener is not in the list anymore.
7098 EXPECT_EQ(1, on_start_counter);
7099}
7100
7101// Tests that the default_xml_generator listener stops receiving events
7102// when removed via Release and that is not owned by the list anymore.
7103TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
7104 int on_start_counter = 0;
7105 bool is_destroyed = false;
7106 // Although Append passes the ownership of this object to the list,
7107 // the following calls release it, and we need to delete it before the
7108 // test ends.
7109 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7110 {
7111 TestEventListeners listeners;
7113
7114 EXPECT_EQ(listener, listeners.Release(listener));
7115 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7116 EXPECT_FALSE(is_destroyed);
7117
7118 // Broadcasting events now should not affect default_xml_generator.
7121 EXPECT_EQ(0, on_start_counter);
7122 }
7123 // Destroying the list should not affect the listener now, too.
7124 EXPECT_FALSE(is_destroyed);
7125 delete listener;
7126}
7127
7128// Tests to ensure that the alternative, verbose spellings of
7129// some of the macros work. We don't test them thoroughly as that
7130// would be quite involved. Since their implementations are
7131// straightforward, and they are rarely used, we'll just rely on the
7132// users to tell us when they are broken.
7133GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
7134 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
7135
7136 // GTEST_FAIL is the same as FAIL.
7137 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
7138 "An expected failure");
7139
7140 // GTEST_ASSERT_XY is the same as ASSERT_XY.
7141
7142 GTEST_ASSERT_EQ(0, 0);
7143 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
7144 "An expected failure");
7145 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
7146 "An expected failure");
7147
7148 GTEST_ASSERT_NE(0, 1);
7149 GTEST_ASSERT_NE(1, 0);
7150 EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
7151 "An expected failure");
7152
7153 GTEST_ASSERT_LE(0, 0);
7154 GTEST_ASSERT_LE(0, 1);
7155 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
7156 "An expected failure");
7157
7158 GTEST_ASSERT_LT(0, 1);
7159 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
7160 "An expected failure");
7161 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
7162 "An expected failure");
7163
7164 GTEST_ASSERT_GE(0, 0);
7165 GTEST_ASSERT_GE(1, 0);
7166 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
7167 "An expected failure");
7168
7169 GTEST_ASSERT_GT(1, 0);
7170 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
7171 "An expected failure");
7172 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
7173 "An expected failure");
7174}
7175
7176// Tests for internal utilities necessary for implementation of the universal
7177// printing.
7178
7181
7183 std::string DebugString() const { return ""; }
7184 std::string ShortDebugString() const { return ""; }
7185};
7186
7188
7190 std::string DebugString() const { return ""; }
7191 int ShortDebugString() const { return 1; }
7192};
7193
7195 std::string DebugString() { return ""; }
7196 std::string ShortDebugString() const { return ""; }
7197};
7198
7200 std::string DebugString() { return ""; }
7201};
7202
7203struct IncompleteType;
7204
7205// Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
7206// constant.
7207TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
7209 "const_true");
7210 static_assert(
7212 "const_true");
7215 "const_true");
7216 static_assert(
7218 "const_false");
7219 static_assert(
7221 "const_false");
7222 static_assert(
7224 "const_false");
7226 "const_false");
7227 static_assert(!HasDebugStringAndShortDebugString<int>::value, "const_false");
7228}
7229
7230// Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
7231// needed methods.
7232TEST(HasDebugStringAndShortDebugStringTest,
7233 ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
7236}
7237
7238// Tests that HasDebugStringAndShortDebugString<T>::value is false when T
7239// doesn't have needed methods.
7240TEST(HasDebugStringAndShortDebugStringTest,
7241 ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7245}
7246
7247// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7248
7249template <typename T1, typename T2>
7251 static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value,
7252 "GTEST_REMOVE_REFERENCE_AND_CONST_ failed.");
7253}
7254
7262
7263// Tests GTEST_REFERENCE_TO_CONST_.
7264
7265template <typename T1, typename T2>
7267 static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value,
7268 "GTEST_REFERENCE_TO_CONST_ failed.");
7269}
7270
7277
7278// Tests IsContainerTest.
7279
7281
7282TEST(IsContainerTestTest, WorksForNonContainer) {
7283 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7284 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7285 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7286}
7287
7288TEST(IsContainerTestTest, WorksForContainer) {
7289 EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::vector<bool>>(0)));
7290 EXPECT_EQ(sizeof(IsContainer),
7291 sizeof(IsContainerTest<std::map<int, double>>(0)));
7292}
7293
7299
7302 const int& operator*() const;
7303 const_iterator& operator++(/* pre-increment */);
7304 };
7307};
7308
7309TEST(IsContainerTestTest, ConstOnlyContainer) {
7310 EXPECT_EQ(sizeof(IsContainer),
7311 sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
7312 EXPECT_EQ(sizeof(IsContainer),
7313 sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
7314}
7315
7316// Tests IsHashTable.
7318 typedef void hasher;
7319};
7321 typedef void hasher;
7322 typedef void reverse_iterator;
7323};
7330
7331// Tests ArrayEq().
7332
7333TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7334 EXPECT_TRUE(ArrayEq(5, 5L));
7335 EXPECT_FALSE(ArrayEq('a', 0));
7336}
7337
7338TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7339 // Note that a and b are distinct but compatible types.
7340 const int a[] = {0, 1};
7341 long b[] = {0, 1};
7342 EXPECT_TRUE(ArrayEq(a, b));
7343 EXPECT_TRUE(ArrayEq(a, 2, b));
7344
7345 b[0] = 2;
7346 EXPECT_FALSE(ArrayEq(a, b));
7347 EXPECT_FALSE(ArrayEq(a, 1, b));
7348}
7349
7350TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7351 const char a[][3] = {"hi", "lo"};
7352 const char b[][3] = {"hi", "lo"};
7353 const char c[][3] = {"hi", "li"};
7354
7355 EXPECT_TRUE(ArrayEq(a, b));
7356 EXPECT_TRUE(ArrayEq(a, 2, b));
7357
7358 EXPECT_FALSE(ArrayEq(a, c));
7359 EXPECT_FALSE(ArrayEq(a, 2, c));
7360}
7361
7362// Tests ArrayAwareFind().
7363
7364TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7365 const char a[] = "hello";
7366 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7367 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7368}
7369
7370TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7371 int a[][2] = {{0, 1}, {2, 3}, {4, 5}};
7372 const int b[2] = {2, 3};
7373 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7374
7375 const int c[2] = {6, 7};
7376 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7377}
7378
7379// Tests CopyArray().
7380
7381TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7382 int n = 0;
7383 CopyArray('a', &n);
7384 EXPECT_EQ('a', n);
7385}
7386
7387TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7388 const char a[3] = "hi";
7389 int b[3];
7390#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7391 CopyArray(a, &b);
7392 EXPECT_TRUE(ArrayEq(a, b));
7393#endif
7394
7395 int c[3];
7396 CopyArray(a, 3, c);
7397 EXPECT_TRUE(ArrayEq(a, c));
7398}
7399
7400TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7401 const int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
7402 int b[2][3];
7403#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7404 CopyArray(a, &b);
7405 EXPECT_TRUE(ArrayEq(a, b));
7406#endif
7407
7408 int c[2][3];
7409 CopyArray(a, 2, c);
7410 EXPECT_TRUE(ArrayEq(a, c));
7411}
7412
7413// Tests NativeArray.
7414
7415TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7416 const int a[3] = {0, 1, 2};
7418 EXPECT_EQ(3U, na.size());
7419 EXPECT_EQ(a, na.begin());
7420}
7421
7422TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7423 typedef int Array[2];
7424 Array* a = new Array[1];
7425 (*a)[0] = 0;
7426 (*a)[1] = 1;
7428 EXPECT_NE(*a, na.begin());
7429 delete[] a;
7430 EXPECT_EQ(0, na.begin()[0]);
7431 EXPECT_EQ(1, na.begin()[1]);
7432
7433 // We rely on the heap checker to verify that na deletes the copy of
7434 // array.
7435}
7436
7437TEST(NativeArrayTest, TypeMembersAreCorrect) {
7438 StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7439 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7440
7441 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7442 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7443}
7444
7445TEST(NativeArrayTest, MethodsWork) {
7446 const int a[3] = {0, 1, 2};
7448 ASSERT_EQ(3U, na.size());
7449 EXPECT_EQ(3, na.end() - na.begin());
7450
7452 EXPECT_EQ(0, *it);
7453 ++it;
7454 EXPECT_EQ(1, *it);
7455 it++;
7456 EXPECT_EQ(2, *it);
7457 ++it;
7458 EXPECT_EQ(na.end(), it);
7459
7460 EXPECT_TRUE(na == na);
7461
7463 EXPECT_TRUE(na == na2);
7464
7465 const int b1[3] = {0, 1, 1};
7466 const int b2[4] = {0, 1, 2, 3};
7469}
7470
7471TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7472 const char a[2][3] = {"hi", "lo"};
7474 ASSERT_EQ(2U, na.size());
7475 EXPECT_EQ(a, na.begin());
7476}
7477
7478// IndexSequence
7479TEST(IndexSequence, MakeIndexSequence) {
7483 (std::is_same<IndexSequence<>, MakeIndexSequence<0>::type>::value));
7485 (std::is_same<IndexSequence<0>, MakeIndexSequence<1>::type>::value));
7487 (std::is_same<IndexSequence<0, 1>, MakeIndexSequence<2>::type>::value));
7488 EXPECT_TRUE((
7489 std::is_same<IndexSequence<0, 1, 2>, MakeIndexSequence<3>::type>::value));
7491 (std::is_base_of<IndexSequence<0, 1, 2>, MakeIndexSequence<3>>::value));
7492}
7493
7494// ElemFromList
7495TEST(ElemFromList, Basic) {
7498 (std::is_same<int, ElemFromList<0, int, double, char>::type>::value));
7500 (std::is_same<double, ElemFromList<1, int, double, char>::type>::value));
7502 (std::is_same<char, ElemFromList<2, int, double, char>::type>::value));
7503 EXPECT_TRUE((
7504 std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int,
7505 char, int, int, int, int>::type>::value));
7506}
7507
7508// FlatTuple
7509TEST(FlatTuple, Basic) {
7511
7512 FlatTuple<int, double, const char*> tuple = {};
7513 EXPECT_EQ(0, tuple.Get<0>());
7514 EXPECT_EQ(0.0, tuple.Get<1>());
7515 EXPECT_EQ(nullptr, tuple.Get<2>());
7516
7517 tuple = FlatTuple<int, double, const char*>(
7519 EXPECT_EQ(7, tuple.Get<0>());
7520 EXPECT_EQ(3.2, tuple.Get<1>());
7521 EXPECT_EQ(std::string("Foo"), tuple.Get<2>());
7522
7523 tuple.Get<1>() = 5.1;
7524 EXPECT_EQ(5.1, tuple.Get<1>());
7525}
7526
7527namespace {
7528std::string AddIntToString(int i, const std::string& s) {
7529 return s + std::to_string(i);
7530}
7531} // namespace
7532
7533TEST(FlatTuple, Apply) {
7535
7536 FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},
7537 5, "Hello"};
7538
7539 // Lambda.
7540 EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
7541 return i == static_cast<int>(s.size());
7542 }));
7543
7544 // Function.
7545 EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
7546
7547 // Mutating operations.
7548 tuple.Apply([](int& i, std::string& s) {
7549 ++i;
7550 s += s;
7551 });
7552 EXPECT_EQ(tuple.Get<0>(), 6);
7553 EXPECT_EQ(tuple.Get<1>(), "HelloHello");
7554}
7555
7586
7593
7594TEST(FlatTuple, ConstructorCalls) {
7596
7597 // Default construction.
7599 { FlatTuple<ConstructionCounting> tuple; }
7606
7607 // Copy construction.
7609 {
7611 FlatTuple<ConstructionCounting> tuple{
7613 }
7620
7621 // Move construction.
7623 {
7624 FlatTuple<ConstructionCounting> tuple{
7626 }
7633
7634 // Copy assignment.
7635 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7636 // elements
7638 {
7639 FlatTuple<ConstructionCounting> tuple;
7641 tuple.Get<0>() = elem;
7642 }
7649
7650 // Move assignment.
7651 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7652 // elements
7654 {
7655 FlatTuple<ConstructionCounting> tuple;
7656 tuple.Get<0>() = ConstructionCounting{};
7657 }
7664
7666}
7667
7668TEST(FlatTuple, ManyTypes) {
7670
7671 // Instantiate FlatTuple with 257 ints.
7672 // Tests show that we can do it with thousands of elements, but very long
7673 // compile times makes it unusuitable for this test.
7674#define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int,
7675#define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8
7676#define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16
7677#define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32
7678#define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64
7679#define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128
7680
7681 // Let's make sure that we can have a very long list of types without blowing
7682 // up the template instantiation depth.
7683 FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple;
7684
7685 tuple.Get<0>() = 7;
7686 tuple.Get<99>() = 17;
7687 tuple.Get<256>() = 1000;
7688 EXPECT_EQ(7, tuple.Get<0>());
7689 EXPECT_EQ(17, tuple.Get<99>());
7690 EXPECT_EQ(1000, tuple.Get<256>());
7691}
7692
7693// Tests SkipPrefix().
7694
7695TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7696 const char* const str = "hello";
7697
7698 const char* p = str;
7699 EXPECT_TRUE(SkipPrefix("", &p));
7700 EXPECT_EQ(str, p);
7701
7702 p = str;
7703 EXPECT_TRUE(SkipPrefix("hell", &p));
7704 EXPECT_EQ(str + 4, p);
7705}
7706
7707TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7708 const char* const str = "world";
7709
7710 const char* p = str;
7711 EXPECT_FALSE(SkipPrefix("W", &p));
7712 EXPECT_EQ(str, p);
7713
7714 p = str;
7715 EXPECT_FALSE(SkipPrefix("world!", &p));
7716 EXPECT_EQ(str, p);
7717}
7718
7719// Tests ad_hoc_test_result().
7720TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
7721 const testing::TestResult& test_result =
7723 EXPECT_FALSE(test_result.Failed());
7724}
7725
7727
7728class DynamicTest : public DynamicUnitTestFixture {
7729 void TestBody() override { EXPECT_TRUE(true); }
7730};
7731
7733 "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__,
7734 __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });
7735
7736TEST(RegisterTest, WasRegistered) {
7737 const auto& unittest = testing::UnitTest::GetInstance();
7738 for (int i = 0; i < unittest->total_test_suite_count(); ++i) {
7739 auto* tests = unittest->GetTestSuite(i);
7740 if (tests->name() != std::string("DynamicUnitTestFixture")) continue;
7741 for (int j = 0; j < tests->total_test_count(); ++j) {
7742 if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue;
7743 // Found it.
7744 EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE");
7745 EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE");
7746 return;
7747 }
7748 }
7749
7750 FAIL() << "Didn't find the test!";
7751}
7752
7753// Test that the pattern globbing algorithm is linear. If not, this test should
7754// time out.
7755TEST(PatternGlobbingTest, MatchesFilterLinearRuntime) {
7756 std::string name(100, 'a'); // Construct the string (a^100)b
7757 name.push_back('b');
7758
7759 std::string pattern; // Construct the string ((a*)^100)b
7760 for (int i = 0; i < 100; ++i) {
7761 pattern.append("a*");
7762 }
7763 pattern.push_back('b');
7764
7767}
7768
7769TEST(PatternGlobbingTest, MatchesFilterWithMultiplePatterns) {
7770 const std::string name = "aaaa";
7776}
7777
Definition gtest_unittest.cc:5120
Base(int an_x)
Definition gtest_unittest.cc:5122
int x() const
Definition gtest_unittest.cc:5123
Definition gtest_unittest.cc:7179
Definition gtest_unittest.cc:7180
Definition gtest_xml_output_unittest_.cc:65
Definition googletest-output-test_.cc:945
void TestBody() override
Definition googletest-output-test_.cc:947
Definition gtest_unittest.cc:7726
Definition googletest-list-tests-unittest_.cc:69
Definition gtest_unittest.cc:7280
Definition gtest_unittest.cc:6430
void TearDown() override
Definition gtest_unittest.cc:6433
void SetUp() override
Definition gtest_unittest.cc:6432
Definition gtest_unittest.cc:6884
void OnTestProgramStart(const UnitTest &) override
Definition gtest_unittest.cc:6890
void OnTestIterationStart(const UnitTest &, int) override
Definition gtest_unittest.cc:6898
void OnTestProgramEnd(const UnitTest &) override
Definition gtest_unittest.cc:6894
SequenceTestingListener(std::vector< std::string > *vector, const char *id)
Definition gtest_unittest.cc:6886
void OnTestIterationEnd(const UnitTest &, int) override
Definition gtest_unittest.cc:6903
Definition gtest_unittest.cc:6708
StaticAssertTypeEqTestHelper()
Definition gtest_unittest.cc:6710
Definition gtest_unittest.cc:6810
~TestListener() override
Definition gtest_unittest.cc:6816
void OnTestProgramStart(const UnitTest &) override
Definition gtest_unittest.cc:6821
TestListener(int *on_start_counter, bool *is_destroyed)
Definition gtest_unittest.cc:6813
TestListener()
Definition gtest_unittest.cc:6812
Definition gtest_unittest.cc:289
Definition googletest-output-test_.cc:733
Definition googletest-list-tests-unittest_.cc:108
Definition gtest_unittest.cc:6410
Definition gtest_unittest.cc:6405
Definition gtest_unittest.cc:6401
Definition gtest_unittest.cc:5171
MyTypeInNameSpace1(int an_x)
Definition gtest_unittest.cc:5173
Definition gtest_unittest.cc:5194
MyTypeInNameSpace2(int an_x)
Definition gtest_unittest.cc:5196
Definition value.hpp:12
Definition gtest_unittest.cc:5304
Definition gtest_unittest.cc:5310
Definition gtest_unittest.cc:5328
Definition gtest_unittest.cc:5319
Definition gtest_unittest.cc:6346
static void TearDownTestSuite()
Definition gtest_unittest.cc:6359
static void SetUpTestSuite()
Definition gtest_unittest.cc:6350
Definition gtest.h:993
Definition gtest.h:894
Definition gtest-message.h:101
std::string GetString() const
Definition gtest.cc:1301
Definition gtest_unittest.cc:5651
static void CheckFlags(const Flags &expected)
Definition gtest_unittest.cc:5686
void SetUp() override
Definition gtest_unittest.cc:5654
static void AssertStringArrayEq(int size1, CharType **array1, int size2, CharType **array2)
Definition gtest_unittest.cc:5676
static void TestParsingFlags(int argc1, const CharType **argv1, int argc2, const CharType **argv2, const Flags &expected, bool should_print_help)
Definition gtest_unittest.cc:5714
Definition gtest_unittest.cc:5346
static void SetUpTestCase()
Definition gtest_unittest.cc:5350
static int counter_
Definition gtest_unittest.cc:5388
void SetUp() override
Definition gtest_unittest.cc:5381
static const char * shared_resource_
Definition gtest_unittest.cc:5391
static void TearDownTestCase()
Definition gtest_unittest.cc:5367
Definition gtest_unittest.cc:5405
static int counter_
Definition gtest_unittest.cc:5447
static const char * shared_resource_
Definition gtest_unittest.cc:5450
static void TearDownTestSuite()
Definition gtest_unittest.cc:5426
void SetUp() override
Definition gtest_unittest.cc:5440
static void SetUpTestSuite()
Definition gtest_unittest.cc:5409
Definition gtest.h:926
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)=0
virtual void OnTestProgramStart(const UnitTest &unit_test)=0
virtual void OnTestIterationStart(const UnitTest &unit_test, int iteration)=0
virtual void OnTestProgramEnd(const UnitTest &unit_test)=0
Definition gtest.h:1023
TestEventListener * Release(TestEventListener *listener)
Definition gtest.cc:5095
void Append(TestEventListener *listener)
Definition gtest.cc:5088
void SuppressEventForwarding(bool)
Definition gtest.cc:5143
TestEventListener * default_result_printer() const
Definition gtest.h:1043
TestEventListener * default_xml_generator() const
Definition gtest.h:1054
Definition gtest_unittest.cc:5255
static const TestResult * GetTestResult(const TestInfo *test_info)
Definition gtest_unittest.cc:5268
static const TestInfo * GetTestInfo(const char *test_name)
Definition gtest_unittest.cc:5257
Definition gtest.h:534
const char * name() const
Definition gtest.h:549
const TestResult * result() const
Definition gtest.h:600
const char * test_suite_name() const
Definition gtest.h:541
Definition gtest.h:370
const char * value() const
Definition gtest.h:382
const char * key() const
Definition gtest.h:379
Definition gtest.h:400
int total_part_count() const
Definition gtest.cc:2447
const TestProperty & GetTestProperty(int i) const
Definition gtest.cc:2270
const TestPartResult & GetTestPartResult(int i) const
Definition gtest.cc:2262
bool Passed() const
Definition gtest.h:416
bool Failed() const
Definition gtest.cc:2418
int test_property_count() const
Definition gtest.cc:2452
Definition gtest.h:673
int total_test_count() const
Definition gtest.cc:2916
const TestResult & ad_hoc_test_result() const
Definition gtest.h:752
const TestInfo * GetTestInfo(int i) const
Definition gtest.cc:2948
Definition gtest.h:1708
Definition gtest.h:243
static bool HasFailure()
Definition gtest.h:284
static bool HasNonfatalFailure()
Definition gtest.cc:2705
Definition gtest.h:1114
const TestInfo * current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_)
Definition gtest.cc:5518
static UnitTest * GetInstance()
Definition gtest.cc:5156
const TestResult & ad_hoc_test_result() const
Definition gtest.cc:5275
Definition gtest.h:1600
Definition gtest-internal.h:1268
Definition gtest-internal.h:246
const Bits & bits() const
Definition gtest-internal.h:313
Definition gtest-internal-inl.h:140
Definition gtest-internal.h:1086
const_iterator begin() const
Definition gtest-internal.h:1114
const_iterator end() const
Definition gtest-internal.h:1115
size_t size() const
Definition gtest-internal.h:1113
Definition gtest-internal.h:855
static const uint32_t kMaxRange
Definition gtest-internal.h:857
Definition gtest-string.h:63
Definition gtest_unittest.cc:172
static bool EventForwardingEnabled(const TestEventListeners &listeners)
Definition gtest_unittest.cc:187
static TestEventListener * GetRepeater(TestEventListeners *listeners)
Definition gtest_unittest.cc:174
static void SetDefaultXmlGenerator(TestEventListeners *listeners, TestEventListener *listener)
Definition gtest_unittest.cc:182
static void SuppressEventForwarding(TestEventListeners *listeners)
Definition gtest_unittest.cc:191
static void SetDefaultResultPrinter(TestEventListeners *listeners, TestEventListener *listener)
Definition gtest_unittest.cc:178
Definition gtest-internal-inl.h:1041
static void ClearTestPartResults(TestResult *test_result)
Definition gtest-internal-inl.h:1049
static bool MatchesFilter(const std::string &name, const char *filter)
Definition gtest.cc:850
UnitTest unit_test_
Definition gtest_unittest.cc:205
void UnitTestRecordProperty(const char *key, const std::string &value)
Definition gtest_unittest.cc:201
UnitTestRecordPropertyTestHelper()
Definition gtest_unittest.cc:198
pRC::Float<> T
Definition externs_nonTT.hpp:1
int value
Definition gmock-actions_test.cc:1714
int i
Definition gmock-matchers-comparisons_test.cc:603
const double y
Definition gmock-matchers-containers_test.cc:377
int x
Definition gmock-matchers-containers_test.cc:376
const char * p
Definition gmock-matchers-containers_test.cc:379
char ch
Definition gmock-matchers-containers_test.cc:384
MockB b_
Definition gmock-spec-builders_test.cc:1330
MockA a_
Definition gmock-spec-builders_test.cc:1329
int * count
Definition gmock_stress_test.cc:90
FilePath testdata_path_
Definition googletest-filepath-test.cc:520
void TestEq1(int x)
Definition googletest-output-test_.cc:60
AnonymousEnum
Definition googletest-printers-test.cc:65
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex)
Definition gtest-death-test.h:337
#define GTEST_REMOVE_REFERENCE_AND_CONST_(T)
Definition gtest-internal.h:874
#define TEST_P(test_suite_name, test_name)
Definition gtest-param-test.h:450
#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name,...)
Definition gtest-param-test.h:496
#define GTEST_FLAG_PREFIX_
Definition gtest-port.h:331
#define GTEST_FLAG_PREFIX_UPPER_
Definition gtest-port.h:333
#define GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
Definition gtest-port.h:373
#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
Definition gtest-port.h:360
#define GTEST_REFERENCE_TO_CONST_(T)
Definition gtest-port.h:1116
#define GTEST_DISABLE_MSC_DEPRECATED_POP_()
Definition gtest-port.h:375
#define GTEST_FLAG_SET(name, value)
Definition gtest-port.h:2294
#define GTEST_DISABLE_MSC_WARNINGS_POP_()
Definition gtest-port.h:361
#define GTEST_CHECK_(condition)
Definition gtest-port.h:1078
#define GTEST_FLAG_GET(name)
Definition gtest-port.h:2293
#define EXPECT_FATAL_FAILURE(statement, substr)
Definition gtest-spi.h:149
#define EXPECT_NONFATAL_FAILURE(statement, substr)
Definition gtest-spi.h:217
#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr)
Definition gtest-spi.h:234
#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr)
Definition gtest-spi.h:167
#define REGISTER_TYPED_TEST_SUITE_P(SuiteName,...)
Definition gtest-typed-test.h:289
#define TYPED_TEST_SUITE_P(SuiteName)
Definition gtest-typed-test.h:259
#define TYPED_TEST_P(SuiteName, TestName)
Definition gtest-typed-test.h:270
#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types,...)
Definition gtest-typed-test.h:306
#define TYPED_TEST(CaseName, TestName)
Definition gtest-typed-test.h:197
#define TYPED_TEST_SUITE(CaseName, Types,...)
Definition gtest-typed-test.h:191
#define EXPECT_NO_FATAL_FAILURE(statement)
Definition gtest.h:2042
#define EXPECT_STRCASENE(s1, s2)
Definition gtest.h:1943
#define GTEST_ASSERT_GT(val1, val2)
Definition gtest.h:1891
#define TEST_F(test_fixture, test_name)
Definition gtest.h:2208
#define ASSERT_GT(val1, val2)
Definition gtest.h:1918
#define ASSERT_EQ(val1, val2)
Definition gtest.h:1898
#define GTEST_TEST(test_suite_name, test_name)
Definition gtest.h:2169
#define GTEST_SUCCEED()
Definition gtest.h:1758
#define EXPECT_NO_THROW(statement)
Definition gtest.h:1777
#define ASSERT_STRNE(s1, s2)
Definition gtest.h:1948
#define FAIL()
Definition gtest.h:1754
#define EXPECT_EQ(val1, val2)
Definition gtest.h:1868
#define ADD_FAILURE_AT(file, line)
Definition gtest.h:1739
#define ASSERT_FLOAT_EQ(val1, val2)
Definition gtest.h:1977
#define ASSERT_NO_FATAL_FAILURE(statement)
Definition gtest.h:2040
#define GTEST_ASSERT_GE(val1, val2)
Definition gtest.h:1889
#define ASSERT_STRCASEEQ(s1, s2)
Definition gtest.h:1950
#define GTEST_ASSERT_LT(val1, val2)
Definition gtest.h:1887
#define GTEST_FAIL()
Definition gtest.h:1744
#define ASSERT_DOUBLE_EQ(val1, val2)
Definition gtest.h:1981
#define EXPECT_NE(val1, val2)
Definition gtest.h:1870
#define GTEST_ASSERT_NE(val1, val2)
Definition gtest.h:1883
#define ASSERT_NEAR(val1, val2, abs_error)
Definition gtest.h:1989
#define EXPECT_STRCASEEQ(s1, s2)
Definition gtest.h:1941
#define ASSERT_STREQ(s1, s2)
Definition gtest.h:1946
#define SUCCEED()
Definition gtest.h:1763
#define ASSERT_LE(val1, val2)
Definition gtest.h:1906
#define EXPECT_THROW(statement, expected_exception)
Definition gtest.h:1775
#define ASSERT_FALSE(condition)
Definition gtest.h:1819
#define EXPECT_NEAR(val1, val2, abs_error)
Definition gtest.h:1985
#define ASSERT_NO_THROW(statement)
Definition gtest.h:1783
#define GTEST_ASSERT_EQ(val1, val2)
Definition gtest.h:1881
#define EXPECT_FLOAT_EQ(val1, val2)
Definition gtest.h:1969
#define EXPECT_ANY_THROW(statement)
Definition gtest.h:1779
#define ASSERT_NE(val1, val2)
Definition gtest.h:1902
#define EXPECT_GT(val1, val2)
Definition gtest.h:1878
#define EXPECT_DOUBLE_EQ(val1, val2)
Definition gtest.h:1973
#define TEST(test_suite_name, test_name)
Definition gtest.h:2176
#define EXPECT_GE(val1, val2)
Definition gtest.h:1876
#define GTEST_ASSERT_LE(val1, val2)
Definition gtest.h:1885
#define EXPECT_TRUE(condition)
Definition gtest.h:1807
#define ASSERT_STRCASENE(s1, s2)
Definition gtest.h:1952
#define GTEST_FAIL_AT(file, line)
Definition gtest.h:1747
#define EXPECT_STREQ(s1, s2)
Definition gtest.h:1937
#define ADD_FAILURE()
Definition gtest.h:1735
#define EXPECT_LE(val1, val2)
Definition gtest.h:1872
#define ASSERT_TRUE(condition)
Definition gtest.h:1815
#define EXPECT_FALSE(condition)
Definition gtest.h:1811
#define ASSERT_THROW(statement, expected_exception)
Definition gtest.h:1781
#define EXPECT_STRNE(s1, s2)
Definition gtest.h:1939
#define EXPECT_LT(val1, val2)
Definition gtest.h:1874
#define ASSERT_GE(val1, val2)
Definition gtest.h:1914
#define ASSERT_ANY_THROW(statement)
Definition gtest.h:1785
#define ASSERT_LT(val1, val2)
Definition gtest.h:1910
#define EXPECT_PRED_FORMAT1(pred_format, v1)
Definition gtest_pred_impl.h:108
#define EXPECT_PRED3(pred, v1, v2, v3)
Definition gtest_pred_impl.h:184
#define EXPECT_PRED2(pred, v1, v2)
Definition gtest_pred_impl.h:145
#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4)
Definition gtest_pred_impl.h:227
#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4)
Definition gtest_pred_impl.h:223
#define ASSERT_PRED_FORMAT1(pred_format, v1)
Definition gtest_pred_impl.h:111
#define ASSERT_PRED2(pred, v1, v2)
Definition gtest_pred_impl.h:149
#define EXPECT_PRED1(pred, v1)
Definition gtest_pred_impl.h:110
#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5)
Definition gtest_pred_impl.h:268
#define ASSERT_PRED1(pred, v1)
Definition gtest_pred_impl.h:113
#define ASSERT_PRED3(pred, v1, v2, v3)
Definition gtest_pred_impl.h:188
#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5)
Definition gtest_pred_impl.h:272
#define ASSERT_PRED_FORMAT2(pred_format, v1, v2)
Definition gtest_pred_impl.h:147
#define EXPECT_PRED_FORMAT2(pred_format, v1, v2)
Definition gtest_pred_impl.h:143
#define FRIEND_TEST(test_case_name, test_name)
Definition gtest_prod.h:57
void TestGTestReferenceToConst()
Definition gtest_unittest.cc:7266
#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help)
Definition gtest_unittest.cc:5759
auto * dynamic_test
Definition gtest_unittest.cc:7732
static void FailFatally()
Definition gtest_unittest.cc:6730
void operator<<(ConvertibleGlobalType &, int)
#define VERIFY_CODE_LOCATION
Definition gtest_unittest.cc:5292
int IntAlias
Definition gtest_unittest.cc:6719
static bool HasNonfatalFailureHelper()
Definition gtest_unittest.cc:6755
#define GTEST_USE_UNPROTECTED_COMMA_
Definition gtest_unittest.cc:1302
static bool HasFailureHelper()
Definition gtest_unittest.cc:6797
static bool dummy1 GTEST_ATTRIBUTE_UNUSED_
Definition gtest_unittest.cc:6701
void TestGTestRemoveReferenceAndConst()
Definition gtest_unittest.cc:7250
Definition googletest-output-test_.cc:471
output
Definition gmock_output_test.py:182
Types< int, long > NumericTypes
Definition gtest-typed-test_test.cc:154
Definition gtest_unittest.cc:6396
Definition gtest_unittest.cc:5170
std::ostream & operator<<(std::ostream &os, const MyTypeInNameSpace1 &val)
Definition gtest_unittest.cc:5175
Definition gtest_unittest.cc:5193
constexpr auto operator!=(GaussianDistribution< T > const &lhs, GaussianDistribution< T > const &rhs)
Definition gaussian.hpp:114
constexpr auto operator==(GaussianDistribution< T > const &lhs, GaussianDistribution< T > const &rhs)
Definition gaussian.hpp:96
GTEST_API_ std::vector< EditType > CalculateOptimalEdits(const std::vector< size_t > &left, const std::vector< size_t > &right)
Definition gtest.cc:1308
GTEST_API_ std::string CreateUnifiedDiff(const std::vector< std::string > &left, const std::vector< std::string > &right, size_t context=2)
Definition gtest.cc:1483
EditType
Definition gtest-internal.h:174
int RmDir(const char *dir)
Definition gtest-port.h:2027
FILE * FOpen(const char *path, const char *mode)
Definition gtest-port.h:2089
GTEST_API_ std::string WideStringToUtf8(const wchar_t *str, int num_chars)
Definition gtest.cc:2056
GTEST_API_ AssertionResult EqFailure(const char *expected_expression, const char *actual_expression, const std::string &expected_value, const std::string &actual_value, bool ignoring_case)
Definition gtest.cc:1593
void ShuffleRange(internal::Random *random, int begin, int end, std::vector< E > *v)
Definition gtest-internal-inl.h:304
GTEST_API_ bool ShouldShard(const char *total_shards_str, const char *shard_index_str, bool in_subprocess_for_death_test)
Definition gtest.cc:6017
int GetRandomSeedFromFlag(int32_t random_seed_flag)
Definition gtest-internal-inl.h:113
int CountIf(const Container &c, Predicate predicate)
Definition gtest-internal-inl.h:275
GTEST_API_ bool SkipPrefix(const char *prefix, const char **pstr)
Definition gtest.cc:6324
typename MakeIndexSequenceImpl< N >::type MakeIndexSequence
Definition gtest-internal.h:1175
const int kMaxRandomSeed
Definition gtest-internal-inl.h:83
GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id)
Definition gtest.cc:6079
GTEST_API_ void ParseGoogleTestFlagsOnly(int *argc, char **argv)
Definition gtest.cc:6685
bool AlwaysFalse()
Definition gtest-internal.h:829
void ForEach(const Container &c, Functor functor)
Definition gtest-internal-inl.h:287
std::string CanonicalizeForStdLibVersioning(std::string s)
Definition gtest-type-util.h:61
TypeId GetTypeId()
Definition gtest-internal.h:419
int GetNextRandomSeed(int seed)
Definition gtest-internal-inl.h:130
E GetElementOr(const std::vector< E > &v, int i, E default_value)
Definition gtest-internal-inl.h:294
constexpr BiggestInt kMaxBiggestInt
Definition gtest-port.h:2174
IsContainer IsContainerTest(int)
Definition gtest-internal.h:939
GTEST_API_ bool ParseFlag(const char *str, const char *flag, int32_t *value)
Definition gtest.cc:6392
void Shuffle(internal::Random *random, std::vector< E > *v)
Definition gtest-internal-inl.h:328
GTEST_API_ bool AlwaysTrue()
Definition gtest.cc:6312
GTEST_API_ bool g_help_flag
Definition gtest.cc:205
Iter ArrayAwareFind(Iter begin, Iter end, const Element &elem)
Definition gtest-internal.h:1034
class UnitTestImpl * GetUnitTestImpl()
Definition gtest-internal-inl.h:966
GTEST_API_ int32_t Int32FromEnvOrDie(const char *env_var, int32_t default_val)
Definition gtest.cc:6061
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms)
std::string StreamableToString(const T &streamable)
Definition gtest-message.h:243
GTEST_API_ int32_t Int32FromGTestEnv(const char *flag, int32_t default_val)
Definition gtest-port.cc:1338
char IsNotContainer
Definition gtest-internal.h:943
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty)
Definition gtest.cc:3238
GTEST_API_ const TypeId kTestTypeIdInGoogleTest
Definition gtest.cc:966
GTEST_API_ void CaptureStdout()
GTEST_API_ TypeId GetTestTypeId()
Definition gtest.cc:962
GTEST_API_ std::string CodePointToUtf8(uint32_t code_point)
Definition gtest.cc:1989
int IsContainer
Definition gtest-internal.h:932
GTEST_API_ std::string AppendUserMessage(const std::string &gtest_msg, const Message &user_msg)
Definition gtest.cc:2235
GTEST_API_ TimeInMillis GetTimeInMillis()
Definition gtest.cc:1174
GTEST_API_ std::string GetCapturedStdout()
bool ArrayEq(const T *lhs, size_t size, const U *rhs)
Definition gtest-internal.h:1024
void CopyArray(const T *from, size_t size, U *to)
Definition gtest-internal.h:1064
Definition gmock-actions.h:151
Environment * AddGlobalTestEnvironment(Environment *env)
Definition gtest.h:1330
GTEST_API_ AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
Definition gtest.cc:1845
GTEST_API_ AssertionResult FloatLE(const char *expr1, const char *expr2, float val1, float val2)
Definition gtest.cc:1714
GTEST_API_ AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
Definition gtest.cc:1835
AssertionResult AssertionFailure()
Definition gtest-assertion-result.cc:69
constexpr bool StaticAssertTypeEq() noexcept
Definition gtest.h:2139
TestInfo * RegisterTest(const char *test_suite_name, const char *test_name, const char *type_param, const char *value_param, const char *file, int line, Factory factory)
Definition gtest.h:2283
internal::TimeInMillis TimeInMillis
Definition gtest.h:364
GTEST_API_ std::string TempDir()
Definition gtest.cc:6850
internal::ValueArray< T... > Values(T... v)
Definition gtest-param-test.h:335
AssertionResult AssertionSuccess()
Definition gtest-assertion-result.cc:66
GTEST_API_ AssertionResult DoubleLE(const char *expr1, const char *expr2, double val1, double val2)
Definition gtest.cc:1721
const int kMaxStackTraceDepth
Definition gtest.h:172
Definition gtest_unittest.cc:7317
void hasher
Definition gtest_unittest.cc:7318
Definition gtest_pred_impl_unittest.cc:54
Definition gtest_unittest.cc:7300
const_iterator begin() const
Definition gtest_unittest.cc:7294
int * const_iterator
Definition gtest_unittest.cc:7295
Definition gtest_unittest.cc:7556
ConstructionCounting & operator=(const ConstructionCounting &)
Definition gtest_unittest.cc:7561
ConstructionCounting()
Definition gtest_unittest.cc:7557
static void Reset()
Definition gtest_unittest.cc:7570
static int dtor_calls
Definition gtest_unittest.cc:7580
static int move_ctor_calls
Definition gtest_unittest.cc:7582
~ConstructionCounting()
Definition gtest_unittest.cc:7558
ConstructionCounting(ConstructionCounting &&) noexcept
Definition gtest_unittest.cc:7560
ConstructionCounting & operator=(ConstructionCounting &&) noexcept
Definition gtest_unittest.cc:7565
static int copy_assignment_calls
Definition gtest_unittest.cc:7583
ConstructionCounting(const ConstructionCounting &)
Definition gtest_unittest.cc:7559
static int move_assignment_calls
Definition gtest_unittest.cc:7584
static int copy_ctor_calls
Definition gtest_unittest.cc:7581
static int default_ctor_calls
Definition gtest_unittest.cc:7579
Definition gtest_unittest.cc:76
Definition gtest_unittest.cc:5109
Definition gtest_unittest.cc:7182
std::string ShortDebugString() const
Definition gtest_unittest.cc:7184
std::string DebugString() const
Definition gtest_unittest.cc:7183
Definition gtest_unittest.cc:7187
Definition gtest_unittest.cc:7199
std::string DebugString()
Definition gtest_unittest.cc:7200
Definition gtest_unittest.cc:7194
std::string DebugString()
Definition gtest_unittest.cc:7195
std::string ShortDebugString() const
Definition gtest_unittest.cc:7196
Definition gtest_unittest.cc:7320
void hasher
Definition gtest_unittest.cc:7321
void reverse_iterator
Definition gtest_unittest.cc:7322
Definition gtest_unittest.cc:7189
int ShortDebugString() const
Definition gtest_unittest.cc:7191
std::string DebugString() const
Definition gtest_unittest.cc:7190
Definition gtest_unittest.cc:5469
bool catch_exceptions
Definition gtest_unittest.cc:5633
bool recreate_environments_when_repeating
Definition gtest_unittest.cc:5643
static Flags Shuffle(bool shuffle)
Definition gtest_unittest.cc:5600
static Flags CatchExceptions(bool catch_exceptions)
Definition gtest_unittest.cc:5510
static Flags RandomSeed(int32_t random_seed)
Definition gtest_unittest.cc:5574
static Flags Brief(bool brief)
Definition gtest_unittest.cc:5558
int32_t repeat
Definition gtest_unittest.cc:5642
bool list_tests
Definition gtest_unittest.cc:5637
Flags()
Definition gtest_unittest.cc:5471
static Flags DeathTestUseFork(bool death_test_use_fork)
Definition gtest_unittest.cc:5518
static Flags Output(const char *output)
Definition gtest_unittest.cc:5550
bool shuffle
Definition gtest_unittest.cc:5644
static Flags Repeat(int32_t repeat)
Definition gtest_unittest.cc:5582
static Flags BreakOnFailure(bool break_on_failure)
Definition gtest_unittest.cc:5502
static Flags RecreateEnvironmentsWhenRepeating(bool recreate_environments_when_repeating)
Definition gtest_unittest.cc:5590
static Flags FailFast(bool fail_fast)
Definition gtest_unittest.cc:5526
bool death_test_use_fork
Definition gtest_unittest.cc:5634
static Flags ListTests(bool list_tests)
Definition gtest_unittest.cc:5542
bool print_time
Definition gtest_unittest.cc:5640
int32_t random_seed
Definition gtest_unittest.cc:5641
static Flags AlsoRunDisabledTests(bool also_run_disabled_tests)
Definition gtest_unittest.cc:5494
const char * output
Definition gtest_unittest.cc:5638
bool also_run_disabled_tests
Definition gtest_unittest.cc:5631
static Flags StreamResultTo(const char *stream_result_to)
Definition gtest_unittest.cc:5616
bool fail_fast
Definition gtest_unittest.cc:5635
const char * filter
Definition gtest_unittest.cc:5636
static Flags StackTraceDepth(int32_t stack_trace_depth)
Definition gtest_unittest.cc:5608
const char * stream_result_to
Definition gtest_unittest.cc:5646
bool throw_on_failure
Definition gtest_unittest.cc:5647
bool break_on_failure
Definition gtest_unittest.cc:5632
bool brief
Definition gtest_unittest.cc:5639
static Flags ThrowOnFailure(bool throw_on_failure)
Definition gtest_unittest.cc:5624
int32_t stack_trace_depth
Definition gtest_unittest.cc:5645
static Flags PrintTime(bool print_time)
Definition gtest_unittest.cc:5566
static Flags Filter(const char *filter)
Definition gtest_unittest.cc:5534
Definition gtest-internal.h:1198
Definition gtest-internal.h:1204
Definition gtest-internal.h:1148
Definition gtest-internal.h:954
Definition gtest-type-util.h:190
Definition gtest-internal.h:1075
Definition gtest-internal.h:1074