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