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