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.
TEST(CommandLineFlagsTest,CanBeAccessedInCodeOnceGTestHIsIncluded)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.
Send(const std::string & message)85 void Send(const std::string& message) override { output_ += message; }
86
87 std::string output_;
88 };
89
StreamingListenerTest()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:
output()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
TEST_F(StreamingListenerTest,OnTestProgramEnd)105 TEST_F(StreamingListenerTest, OnTestProgramEnd) {
106 *output() = "";
107 streamer_.OnTestProgramEnd(unit_test_);
108 EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
109 }
110
TEST_F(StreamingListenerTest,OnTestIterationEnd)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
TEST_F(StreamingListenerTest,OnTestCaseStart)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
TEST_F(StreamingListenerTest,OnTestCaseEnd)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
TEST_F(StreamingListenerTest,OnTestStart)129 TEST_F(StreamingListenerTest, OnTestStart) {
130 *output() = "";
131 streamer_.OnTestStart(test_info_obj_);
132 EXPECT_EQ("event=TestStart&name=Bar\n", *output());
133 }
134
TEST_F(StreamingListenerTest,OnTestEnd)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
TEST_F(StreamingListenerTest,OnTestPartResult)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:
GetRepeater(TestEventListeners * listeners)158 static TestEventListener* GetRepeater(TestEventListeners* listeners) {
159 return listeners->repeater();
160 }
161
SetDefaultResultPrinter(TestEventListeners * listeners,TestEventListener * listener)162 static void SetDefaultResultPrinter(TestEventListeners* listeners,
163 TestEventListener* listener) {
164 listeners->SetDefaultResultPrinter(listener);
165 }
SetDefaultXmlGenerator(TestEventListeners * listeners,TestEventListener * listener)166 static void SetDefaultXmlGenerator(TestEventListeners* listeners,
167 TestEventListener* listener) {
168 listeners->SetDefaultXmlGenerator(listener);
169 }
170
EventForwardingEnabled(const TestEventListeners & listeners)171 static bool EventForwardingEnabled(const TestEventListeners& listeners) {
172 return listeners.EventForwardingEnabled();
173 }
174
SuppressEventForwarding(TestEventListeners * listeners)175 static void SuppressEventForwarding(TestEventListeners* listeners) {
176 listeners->SuppressEventForwarding();
177 }
178 };
179
180 class UnitTestRecordPropertyTestHelper : public Test {
181 protected:
UnitTestRecordPropertyTestHelper()182 UnitTestRecordPropertyTestHelper() {}
183
184 // Forwards to UnitTest::RecordProperty() to bypass access controls.
UnitTestRecordProperty(const char * key,const std::string & value)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
operator <<(::std::ostream & os,const TestingVector & vector)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
TEST(GetRandomSeedFromFlagTest,HandlesZero)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
TEST(GetRandomSeedFromFlagTest,PreservesValidSeed)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
TEST(GetRandomSeedFromFlagTest,NormalizesInvalidSeed)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
TEST(GetNextRandomSeedTest,WorksForValidInput)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
ClearCurrentTestPartResults()349 static void ClearCurrentTestPartResults() {
350 TestResultAccessor::ClearTestPartResults(
351 GetUnitTestImpl()->current_test_result());
352 }
353
354 // Tests GetTypeId.
355
TEST(GetTypeIdTest,ReturnsSameValueForSameType)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
TEST(GetTypeIdTest,ReturnsDifferentValuesForDifferentTypes)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.
TEST(GetTestTypeIdTest,ReturnsTheSameValueInsideOrOutsideOfGoogleTest)375 TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
376 EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
377 }
378
379 // Tests CanonicalizeForStdLibVersioning.
380
381 using ::testing::internal::CanonicalizeForStdLibVersioning;
382
TEST(CanonicalizeForStdLibVersioning,LeavesUnversionedNamesUnchanged)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
TEST(CanonicalizeForStdLibVersioning,ElidesDoubleUnderNames)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
TEST(FormatTimeInMillisAsSecondsTest,FormatsZero)406 TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
407 EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
408 }
409
TEST(FormatTimeInMillisAsSecondsTest,FormatsPositiveNumber)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
TEST(FormatTimeInMillisAsSecondsTest,FormatsNegativeNumber)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:
SetUp()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
TearDown()454 void TearDown() override {
455 SetTimeZone(saved_tz_);
456 free(const_cast<char*>(saved_tz_));
457 saved_tz_ = nullptr;
458 }
459
SetTimeZone(const char * time_zone)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
TEST_F(FormatEpochTimeInMillisAsIso8601Test,PrintsTwoDigitSegments)488 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
489 EXPECT_EQ("2011-10-31T18:52:42.000",
490 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
491 }
492
TEST_F(FormatEpochTimeInMillisAsIso8601Test,IncludesMillisecondsAfterDot)493 TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
494 EXPECT_EQ(
495 "2011-10-31T18:52:42.234",
496 FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
497 }
498
TEST_F(FormatEpochTimeInMillisAsIso8601Test,PrintsLeadingZeroes)499 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
500 EXPECT_EQ("2011-09-03T05:07:02.000",
501 FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
502 }
503
TEST_F(FormatEpochTimeInMillisAsIso8601Test,Prints24HourTime)504 TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
505 EXPECT_EQ("2011-09-28T17:08:22.000",
506 FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
507 }
508
TEST_F(FormatEpochTimeInMillisAsIso8601Test,PrintsEpochStart)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.
TEST(NullLiteralTest,LHSAllowsNullLiterals)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>
operator T__anona388e2a90111::ConvertToAll539 operator T() const { // NOLINT
540 return T();
541 }
542 };
543
544 struct ConvertToPointer {
545 template <class T>
operator T*__anona388e2a90111::ConvertToPointer546 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>
operator T__anona388e2a90111::ConvertToAllButNoPointers554 operator T() const { // NOLINT
555 return T();
556 }
557 };
558
559 struct MyType {};
operator ==(MyType const &,MyType const &)560 inline bool operator==(MyType const&, MyType const&) { return true; }
561
TEST(NullLiteralTest,ImplicitConversion)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
TEST(NullLiteralTest,NoConversionNoWarning)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.
TEST(CodePointToUtf8Test,CanEncodeNul)599 TEST(CodePointToUtf8Test, CanEncodeNul) {
600 EXPECT_EQ("", CodePointToUtf8(L'\0'));
601 }
602
603 // Tests that ASCII characters are encoded correctly.
TEST(CodePointToUtf8Test,CanEncodeAscii)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.
TEST(CodePointToUtf8Test,CanEncode8To11Bits)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.
TEST(CodePointToUtf8Test,CanEncode12To16Bits)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.
TEST(CodePointToUtf8Test,CanEncode17To21Bits)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.
TEST(CodePointToUtf8Test,CanEncodeInvalidCodePoint)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.
TEST(WideStringToUtf8Test,CanEncodeNul)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.
TEST(WideStringToUtf8Test,CanEncodeAscii)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.
TEST(WideStringToUtf8Test,CanEncode8To11Bits)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.
TEST(WideStringToUtf8Test,CanEncode12To16Bits)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.
TEST(WideStringToUtf8Test,StopsOnNulCharacter)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.
TEST(WideStringToUtf8Test,StopsWhenLengthLimitReached)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.
TEST(WideStringToUtf8Test,CanEncode17To21Bits)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.
TEST(WideStringToUtf8Test,CanEncodeInvalidCodePoint)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.
TEST(WideStringToUtf8Test,CanEncodeValidUtf16SUrrogatePairs)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.
TEST(WideStringToUtf8Test,CanEncodeInvalidUtf16SurrogatePair)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_
TEST(WideStringToUtf8Test,ConcatenatesCodepointsCorrectly)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
TEST(WideStringToUtf8Test,ConcatenatesCodepointsCorrectly)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
TEST(RandomDeathTest,GeneratesCrashesOnInvalidRange)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
TEST(RandomTest,GeneratesNumbersWithinRange)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
TEST(RandomTest,RepeatsWhenReseeded)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
IsPositive(int n)827 static bool IsPositive(int n) { return n > 0; }
828
TEST(ContainerUtilityTest,CountIf)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;
Accumulate(int n)846 static void Accumulate(int n) { g_sum += n; }
847
TEST(ContainerUtilityTest,ForEach)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().
TEST(ContainerUtilityTest,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
TEST(ContainerUtilityDeathTest,ShuffleRange)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
VectorShuffleTest()904 VectorShuffleTest() : random_(1) {
905 for (int i = 0; i < static_cast<int>(kVectorSize); i++) {
906 vector_.push_back(i);
907 }
908 }
909
VectorIsCorrupt(const TestingVector & vector)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
VectorIsNotCorrupt(const TestingVector & vector)929 static bool VectorIsNotCorrupt(const TestingVector& vector) {
930 return !VectorIsCorrupt(vector);
931 }
932
RangeIsShuffled(const TestingVector & vector,int begin,int end)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
RangeIsUnshuffled(const TestingVector & vector,int begin,int end)942 static bool RangeIsUnshuffled(
943 const TestingVector& vector, int begin, int end) {
944 return !RangeIsShuffled(vector, begin, end);
945 }
946
VectorIsShuffled(const TestingVector & vector)947 static bool VectorIsShuffled(const TestingVector& vector) {
948 return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
949 }
950
VectorIsUnshuffled(const TestingVector & vector)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
TEST_F(VectorShuffleTest,HandlesEmptyRange)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
TEST_F(VectorShuffleTest,HandlesRangeOfSizeOne)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
TEST_F(VectorShuffleTest,ShufflesEntireVector)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
TEST_F(VectorShuffleTest,ShufflesStartOfVector)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
TEST_F(VectorShuffleTest,ShufflesEndOfVector)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
TEST_F(VectorShuffleTest,ShufflesMiddleOfVector)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
TEST_F(VectorShuffleTest,ShufflesRepeatably)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
TEST(AssertHelperTest,AssertHelperIsSmall)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().
TEST(StringTest,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
TEST(StringTest,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().
TEST(StringTest,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
TEST(StringTest,AnsiAndUtf16Null)1113 TEST(StringTest, AnsiAndUtf16Null) {
1114 EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
1115 EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
1116 }
1117
TEST(StringTest,AnsiAndUtf16ConvertBasic)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
TEST(StringTest,AnsiAndUtf16ConvertPathChars)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.
TEST(TestPropertyTest,StringValue)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.
TEST(TestPropertyTest,ReplaceStringValue)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.
AddFatalFailure()1157 static void AddFatalFailure() {
1158 FAIL() << "Expected fatal failure.";
1159 }
1160
AddNonfatalFailure()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 };
AddFailure(FailureMode failure)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.
TEST_F(ScopedFakeTestPartResultReporterTest,InterceptsTestFailures)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
TEST_F(ScopedFakeTestPartResultReporterTest,DeprecatedConstructor)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:
AddFailureInOtherThread(FailureMode failure)1212 static void AddFailureInOtherThread(FailureMode failure) {
1213 ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
1214 thread.Join();
1215 }
1216 };
1217
TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,InterceptsTestFailuresInAllThreads)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
TEST_F(ExpectFatalFailureTest,CatchesFatalFaliure)1245 TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
1246 EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
1247 }
1248
TEST_F(ExpectFatalFailureTest,AcceptsStdStringObject)1249 TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
1250 EXPECT_FATAL_FAILURE(AddFatalFailure(),
1251 ::std::string("Expected fatal failure."));
1252 }
1253
TEST_F(ExpectFatalFailureTest,CatchesFatalFailureOnAllThreads)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
NonVoidFunction()1269 int NonVoidFunction() {
1270 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
1271 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
1272 return 0;
1273 }
1274
TEST_F(ExpectFatalFailureTest,CanBeUsedInNonVoidFunction)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
DoesNotAbortHelper(bool * aborted)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
TEST_F(ExpectFatalFailureTest,DoesNotAbort)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
TEST_F(ExpectFatalFailureTest,AcceptsMacroThatExpandsToUnprotectedComma)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
TEST_F(ExpectNonfatalFailureTest,CatchesNonfatalFailure)1326 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
1327 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1328 "Expected non-fatal failure.");
1329 }
1330
TEST_F(ExpectNonfatalFailureTest,AcceptsStdStringObject)1331 TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
1332 EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
1333 ::std::string("Expected non-fatal failure."));
1334 }
1335
TEST_F(ExpectNonfatalFailureTest,CatchesNonfatalFailureOnAllThreads)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.
TEST_F(ExpectNonfatalFailureTest,AcceptsMacroThatExpandsToUnprotectedComma)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
TEST_F(ExpectFailureWithThreadsTest,ExpectFatalFailureOnAllThreads)1363 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
1364 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
1365 "Expected fatal failure.");
1366 }
1367
TEST_F(ExpectFailureWithThreadsTest,ExpectNonFatalFailureOnAllThreads)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
TEST(TestPropertyTest,ConstructorWorks)1377 TEST(TestPropertyTest, ConstructorWorks) {
1378 const TestProperty property("key", "value");
1379 EXPECT_STREQ("key", property.key());
1380 EXPECT_STREQ("value", property.value());
1381 }
1382
TEST(TestPropertyTest,SetValue)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
SetUp()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
TearDown()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.
CompareTestPartResult(const TestPartResult & expected,const TestPartResult & actual)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().
TEST_F(TestResultTest,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().
TEST_F(TestResultTest,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().
TEST_F(TestResultTest,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
TEST_F(TestResultDeathTest,GetTestPartResult)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.
TEST(TestResultPropertyTest,NoPropertiesFoundWhenNoneAreAdded)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.
TEST(TestResultPropertyTest,OnePropertyFoundWhenAdded)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.
TEST(TestResultPropertyTest,MultiplePropertiesFoundWhenAdded)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.
TEST(TestResultPropertyTest,OverridesValuesForDuplicateKeys)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().
TEST(TestResultPropertyTest,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.
SetUpTestSuite()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.
TearDownTestSuite()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.
VerifyAndModifyFlags()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.
TEST_F(GTestFlagSaverTest,ModifyGTestFlags)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.
TEST_F(GTestFlagSaverTest,VerifyGTestFlags)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.
SetEnv(const char * name,const char * value)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.
TEST(Int32FromGTestEnvTest,ReturnsDefaultWhenVariableIsNotSet)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.
TEST(Int32FromGTestEnvTest,ReturnsDefaultWhenValueOverflows)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.
TEST(Int32FromGTestEnvTest,ReturnsDefaultWhenValueIsInvalid)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.
TEST(Int32FromGTestEnvTest,ParsesAndReturnsValidValue)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
TEST(ParseInt32FlagTest,ReturnsFalseForInvalidFlag)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.
TEST(ParseInt32FlagTest,ReturnsDefaultWhenValueOverflows)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.
TEST(ParseInt32FlagTest,ReturnsDefaultWhenValueIsInvalid)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.
TEST(ParseInt32FlagTest,ParsesAndReturnsValidValue)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
TEST(Int32FromEnvOrDieTest,ParsesAndReturnsValidValue)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.
TEST(Int32FromEnvOrDieDeathTest,AbortsOnFailure)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.
TEST(Int32FromEnvOrDieDeathTest,AbortsOnInt32Overflow)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.
TEST(ShouldRunTestOnShardTest,IsPartitionWhenThereIsOneShard)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:
SetUp()1875 void SetUp() override {
1876 index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
1877 total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
1878 }
1879
TearDown()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.
TEST_F(ShouldShardTest,ReturnsFalseWhenNeitherEnvVarIsSet)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.
TEST_F(ShouldShardTest,ReturnsFalseWhenTotalShardIsOne)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
TEST_F(ShouldShardTest,WorksWhenShardEnvVarsAreValid)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
TEST_F(ShouldShardDeathTest,AbortsWhenShardingEnvVarsAreInvalid)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.
TEST(ShouldRunTestOnShardTest,IsPartitionWhenThereAreFiveShards)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
TEST(UnitTestTest,CanGetOriginalWorkingDir)1995 TEST(UnitTestTest, CanGetOriginalWorkingDir) {
1996 ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr);
1997 EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
1998 }
1999
TEST(UnitTestTest,ReturnsPlausibleTimestamp)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.
ExpectNonFatalFailureRecordingPropertyWithReservedKey(const TestResult & test_result,const char * key)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
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(const char * key)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
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(const char * key)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
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(const char * key)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:
SetUpTestSuite()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.
TEST_F(UnitTestRecordPropertyTest,OnePropertyFoundWhenAdded)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.
TEST_F(UnitTestRecordPropertyTest,MultiplePropertiesFoundWhenAdded)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.
TEST_F(UnitTestRecordPropertyTest,OverridesValuesForDuplicateKeys)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
TEST_F(UnitTestRecordPropertyTest,AddFailureInsideTestsWhenUsingTestSuiteReservedKeys)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
TEST_F(UnitTestRecordPropertyTest,AddRecordWithReservedKeysGeneratesCorrectPropertyList)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:
TearDown()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.
IsEven(int n)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 {
operator ()__anona388e2a90111::IsEvenFunctor2186 bool operator()(int n) { return IsEven(n); }
2187 };
2188
2189 // A predicate-formatter function that asserts the argument is an even
2190 // number.
AssertIsEven(const char * expr,int n)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.
ResultIsEven(int n)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.
ResultIsEvenNoExplanation(int n)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 {
operator ()__anona388e2a90111::AssertIsEvenFunctor2223 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.
SumIsEven2(int n1,int n2)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 {
operator ()__anona388e2a90111::SumIsEven3Functor2236 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.
AssertSumIsEven4(const char * e1,const char * e2,const char * e3,const char * e4,int n1,int n2,int n3,int n4)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 {
operator ()__anona388e2a90111::AssertSumIsEven5Functor2261 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.
TEST(Pred1Test,WithoutFormat)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.
TEST(Pred1Test,WithFormat)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.
TEST(Pred1Test,SingleEvaluationOnFailure)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.
TEST(PredTest,WithoutFormat)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.
TEST(PredTest,WithFormat)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.
TEST(PredTest,SingleEvaluationOnFailure)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
TEST(PredTest,ExpectPredEvalFailure)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
IsPositive(double x)2427 bool IsPositive(double x) {
2428 return x > 0;
2429 }
2430
2431 template <typename T>
IsNegative(T x)2432 bool IsNegative(T x) {
2433 return x < 0;
2434 }
2435
2436 template <typename T1, typename T2>
GreaterThan(T1 x1,T2 x2)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.
TEST(PredicateAssertionTest,AcceptsOverloadedFunction)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.
TEST(PredicateAssertionTest,AcceptsTemplateFunction)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
IsPositiveFormat(const char *,int n)2462 AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
2463 return n > 0 ? AssertionSuccess() :
2464 AssertionFailure(Message() << "Failure");
2465 }
2466
IsPositiveFormat(const char *,double x)2467 AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
2468 return x > 0 ? AssertionSuccess() :
2469 AssertionFailure(Message() << "Failure");
2470 }
2471
2472 template <typename T>
IsNegativeFormat(const char *,T x)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>
EqualsFormat(const char *,const char *,const T1 & x1,const T2 & x2)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.
TEST(PredicateFormatAssertionTest,AcceptsOverloadedFunction)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.
TEST(PredicateFormatAssertionTest,AcceptsTemplateFunction)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.
TEST(StringAssertionTest,ASSERT_STREQ)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.
TEST(StringAssertionTest,ASSERT_STREQ_Null)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.
TEST(StringAssertionTest,ASSERT_STREQ_Null2)2522 TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
2523 EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null");
2524 }
2525
2526 // Tests ASSERT_STRNE.
TEST(StringAssertionTest,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.
TEST(StringAssertionTest,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.
TEST(StringAssertionTest,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.
TEST(StringAssertionTest,STREQ_Wide)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.
TEST(StringAssertionTest,STRNE_Wide)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*.
TEST(IsSubstringTest,ReturnsCorrectResultForCString)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*.
TEST(IsSubstringTest,ReturnsCorrectResultForWideCString)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*.
TEST(IsSubstringTest,GeneratesCorrectMessageForCString)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.
TEST(IsSubstringTest,ReturnsCorrectResultsForStdString)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.
TEST(IsSubstringTest,ReturnsCorrectResultForStdWstring)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.
TEST(IsSubstringTest,GeneratesCorrectMessageForWstring)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*.
TEST(IsNotSubstringTest,ReturnsCorrectResultForCString)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*.
TEST(IsNotSubstringTest,ReturnsCorrectResultForWideCString)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*.
TEST(IsNotSubstringTest,GeneratesCorrectMessageForWideCString)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.
TEST(IsNotSubstringTest,ReturnsCorrectResultsForStdString)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.
TEST(IsNotSubstringTest,GeneratesCorrectMessageForStdString)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.
TEST(IsNotSubstringTest,ReturnsCorrectResultForStdWstring)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
SetUp()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
TestSize()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.
TEST_F(FloatTest,Size)2828 TEST_F(FloatTest, Size) {
2829 TestSize();
2830 }
2831
2832 // Tests comparing with +0 and -0.
TEST_F(FloatTest,Zeros)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.
TEST_F(FloatTest,AlmostZeros)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.
TEST_F(FloatTest,SmallDiff)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.
TEST_F(FloatTest,LargeDiff)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.
TEST_F(FloatTest,Infinity)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.
TEST_F(FloatTest,NaN)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.
TEST_F(FloatTest,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.
TEST_F(FloatTest,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.
TEST_F(FloatTest,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.
TEST_F(FloatTest,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.
TEST_F(FloatTest,FloatLESucceeds)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.
TEST_F(FloatTest,FloatLEFails)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.
TEST_F(DoubleTest,Size)2985 TEST_F(DoubleTest, Size) {
2986 TestSize();
2987 }
2988
2989 // Tests comparing with +0 and -0.
TEST_F(DoubleTest,Zeros)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.
TEST_F(DoubleTest,AlmostZeros)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.
TEST_F(DoubleTest,SmallDiff)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.
TEST_F(DoubleTest,LargeDiff)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.
TEST_F(DoubleTest,Infinity)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.
TEST_F(DoubleTest,NaN)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.
TEST_F(DoubleTest,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.
TEST_F(DoubleTest,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.
TEST_F(DoubleTest,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.
TEST_F(DoubleTest,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.
TEST_F(DoubleTest,DoubleLESucceeds)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.
TEST_F(DoubleTest,DoubleLEFails)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.
TEST(DisabledTest,DISABLED_TestShouldNotRun)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.
TEST(DisabledTest,NotDISABLED_TestShouldRun)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.
TEST(DISABLED_TestSuite,TestShouldNotRun)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.
TEST(DISABLED_TestSuite,DISABLED_TestShouldNotRun)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:
SetUpTestSuite()3169 static void SetUpTestSuite() {
3170 FAIL() << "Unexpected failure: All tests disabled in test case. "
3171 "SetUpTestSuite() should not be called.";
3172 }
3173
TearDownTestSuite()3174 static void TearDownTestSuite() {
3175 FAIL() << "Unexpected failure: All tests disabled in test case. "
3176 "TearDownTestSuite() should not be called.";
3177 }
3178 };
3179
TEST_F(DisabledTestsTest,DISABLED_TestShouldNotRun_1)3180 TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
3181 FAIL() << "Unexpected failure: Disabled test should not be run.";
3182 }
3183
TEST_F(DisabledTestsTest,DISABLED_TestShouldNotRun_2)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 #if GTEST_HAS_TYPED_TEST
3191
3192 template <typename T>
3193 class TypedTest : public Test {
3194 };
3195
3196 typedef testing::Types<int, double> NumericTypes;
3197 TYPED_TEST_SUITE(TypedTest, NumericTypes);
3198
TYPED_TEST(TypedTest,DISABLED_ShouldNotRun)3199 TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
3200 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3201 }
3202
3203 template <typename T>
3204 class DISABLED_TypedTest : public Test {
3205 };
3206
3207 TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
3208
TYPED_TEST(DISABLED_TypedTest,ShouldNotRun)3209 TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
3210 FAIL() << "Unexpected failure: Disabled typed test should not run.";
3211 }
3212
3213 #endif // GTEST_HAS_TYPED_TEST
3214
3215 // Tests that disabled type-parameterized tests aren't run.
3216
3217 #if GTEST_HAS_TYPED_TEST_P
3218
3219 template <typename T>
3220 class TypedTestP : public Test {
3221 };
3222
3223 TYPED_TEST_SUITE_P(TypedTestP);
3224
TYPED_TEST_P(TypedTestP,DISABLED_ShouldNotRun)3225 TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
3226 FAIL() << "Unexpected failure: "
3227 << "Disabled type-parameterized test should not run.";
3228 }
3229
3230 REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
3231
3232 INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);
3233
3234 template <typename T>
3235 class DISABLED_TypedTestP : public Test {
3236 };
3237
3238 TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
3239
TYPED_TEST_P(DISABLED_TypedTestP,ShouldNotRun)3240 TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
3241 FAIL() << "Unexpected failure: "
3242 << "Disabled type-parameterized test should not run.";
3243 }
3244
3245 REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
3246
3247 INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
3248
3249 #endif // GTEST_HAS_TYPED_TEST_P
3250
3251 // Tests that assertion macros evaluate their arguments exactly once.
3252
3253 class SingleEvaluationTest : public Test {
3254 public: // Must be public and not protected due to a bug in g++ 3.4.2.
3255 // This helper function is needed by the FailedASSERT_STREQ test
3256 // below. It's public to work around C++Builder's bug with scoping local
3257 // classes.
CompareAndIncrementCharPtrs()3258 static void CompareAndIncrementCharPtrs() {
3259 ASSERT_STREQ(p1_++, p2_++);
3260 }
3261
3262 // This helper function is needed by the FailedASSERT_NE test below. It's
3263 // public to work around C++Builder's bug with scoping local classes.
CompareAndIncrementInts()3264 static void CompareAndIncrementInts() {
3265 ASSERT_NE(a_++, b_++);
3266 }
3267
3268 protected:
SingleEvaluationTest()3269 SingleEvaluationTest() {
3270 p1_ = s1_;
3271 p2_ = s2_;
3272 a_ = 0;
3273 b_ = 0;
3274 }
3275
3276 static const char* const s1_;
3277 static const char* const s2_;
3278 static const char* p1_;
3279 static const char* p2_;
3280
3281 static int a_;
3282 static int b_;
3283 };
3284
3285 const char* const SingleEvaluationTest::s1_ = "01234";
3286 const char* const SingleEvaluationTest::s2_ = "abcde";
3287 const char* SingleEvaluationTest::p1_;
3288 const char* SingleEvaluationTest::p2_;
3289 int SingleEvaluationTest::a_;
3290 int SingleEvaluationTest::b_;
3291
3292 // Tests that when ASSERT_STREQ fails, it evaluates its arguments
3293 // exactly once.
TEST_F(SingleEvaluationTest,FailedASSERT_STREQ)3294 TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
3295 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
3296 "p2_++");
3297 EXPECT_EQ(s1_ + 1, p1_);
3298 EXPECT_EQ(s2_ + 1, p2_);
3299 }
3300
3301 // Tests that string assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest,ASSERT_STR)3302 TEST_F(SingleEvaluationTest, ASSERT_STR) {
3303 // successful EXPECT_STRNE
3304 EXPECT_STRNE(p1_++, p2_++);
3305 EXPECT_EQ(s1_ + 1, p1_);
3306 EXPECT_EQ(s2_ + 1, p2_);
3307
3308 // failed EXPECT_STRCASEEQ
3309 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
3310 "Ignoring case");
3311 EXPECT_EQ(s1_ + 2, p1_);
3312 EXPECT_EQ(s2_ + 2, p2_);
3313 }
3314
3315 // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
3316 // once.
TEST_F(SingleEvaluationTest,FailedASSERT_NE)3317 TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
3318 EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
3319 "(a_++) != (b_++)");
3320 EXPECT_EQ(1, a_);
3321 EXPECT_EQ(1, b_);
3322 }
3323
3324 // Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest,OtherCases)3325 TEST_F(SingleEvaluationTest, OtherCases) {
3326 // successful EXPECT_TRUE
3327 EXPECT_TRUE(0 == a_++); // NOLINT
3328 EXPECT_EQ(1, a_);
3329
3330 // failed EXPECT_TRUE
3331 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
3332 EXPECT_EQ(2, a_);
3333
3334 // successful EXPECT_GT
3335 EXPECT_GT(a_++, b_++);
3336 EXPECT_EQ(3, a_);
3337 EXPECT_EQ(1, b_);
3338
3339 // failed EXPECT_LT
3340 EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
3341 EXPECT_EQ(4, a_);
3342 EXPECT_EQ(2, b_);
3343
3344 // successful ASSERT_TRUE
3345 ASSERT_TRUE(0 < a_++); // NOLINT
3346 EXPECT_EQ(5, a_);
3347
3348 // successful ASSERT_GT
3349 ASSERT_GT(a_++, b_++);
3350 EXPECT_EQ(6, a_);
3351 EXPECT_EQ(3, b_);
3352 }
3353
3354 #if GTEST_HAS_EXCEPTIONS
3355
3356 #if GTEST_HAS_RTTI
3357
3358 #ifdef _MSC_VER
3359 #define ERROR_DESC "class std::runtime_error"
3360 #else
3361 #define ERROR_DESC "std::runtime_error"
3362 #endif
3363
3364 #else // GTEST_HAS_RTTI
3365
3366 #define ERROR_DESC "an std::exception-derived error"
3367
3368 #endif // GTEST_HAS_RTTI
3369
ThrowAnInteger()3370 void ThrowAnInteger() {
3371 throw 1;
3372 }
ThrowRuntimeError(const char * what)3373 void ThrowRuntimeError(const char* what) {
3374 throw std::runtime_error(what);
3375 }
3376
3377 // Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest,ExceptionTests)3378 TEST_F(SingleEvaluationTest, ExceptionTests) {
3379 // successful EXPECT_THROW
3380 EXPECT_THROW({ // NOLINT
3381 a_++;
3382 ThrowAnInteger();
3383 }, int);
3384 EXPECT_EQ(1, a_);
3385
3386 // failed EXPECT_THROW, throws different
3387 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3388 a_++;
3389 ThrowAnInteger();
3390 }, bool), "throws a different type");
3391 EXPECT_EQ(2, a_);
3392
3393 // failed EXPECT_THROW, throws runtime error
3394 EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
3395 a_++;
3396 ThrowRuntimeError("A description");
3397 }, bool), "throws " ERROR_DESC " with description \"A description\"");
3398 EXPECT_EQ(3, a_);
3399
3400 // failed EXPECT_THROW, throws nothing
3401 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
3402 EXPECT_EQ(4, a_);
3403
3404 // successful EXPECT_NO_THROW
3405 EXPECT_NO_THROW(a_++);
3406 EXPECT_EQ(5, a_);
3407
3408 // failed EXPECT_NO_THROW
3409 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
3410 a_++;
3411 ThrowAnInteger();
3412 }), "it throws");
3413 EXPECT_EQ(6, a_);
3414
3415 // successful EXPECT_ANY_THROW
3416 EXPECT_ANY_THROW({ // NOLINT
3417 a_++;
3418 ThrowAnInteger();
3419 });
3420 EXPECT_EQ(7, a_);
3421
3422 // failed EXPECT_ANY_THROW
3423 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
3424 EXPECT_EQ(8, a_);
3425 }
3426
3427 #endif // GTEST_HAS_EXCEPTIONS
3428
3429 // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
3430 class NoFatalFailureTest : public Test {
3431 protected:
Succeeds()3432 void Succeeds() {}
FailsNonFatal()3433 void FailsNonFatal() {
3434 ADD_FAILURE() << "some non-fatal failure";
3435 }
Fails()3436 void Fails() {
3437 FAIL() << "some fatal failure";
3438 }
3439
DoAssertNoFatalFailureOnFails()3440 void DoAssertNoFatalFailureOnFails() {
3441 ASSERT_NO_FATAL_FAILURE(Fails());
3442 ADD_FAILURE() << "should not reach here.";
3443 }
3444
DoExpectNoFatalFailureOnFails()3445 void DoExpectNoFatalFailureOnFails() {
3446 EXPECT_NO_FATAL_FAILURE(Fails());
3447 ADD_FAILURE() << "other failure";
3448 }
3449 };
3450
TEST_F(NoFatalFailureTest,NoFailure)3451 TEST_F(NoFatalFailureTest, NoFailure) {
3452 EXPECT_NO_FATAL_FAILURE(Succeeds());
3453 ASSERT_NO_FATAL_FAILURE(Succeeds());
3454 }
3455
TEST_F(NoFatalFailureTest,NonFatalIsNoFailure)3456 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
3457 EXPECT_NONFATAL_FAILURE(
3458 EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
3459 "some non-fatal failure");
3460 EXPECT_NONFATAL_FAILURE(
3461 ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
3462 "some non-fatal failure");
3463 }
3464
TEST_F(NoFatalFailureTest,AssertNoFatalFailureOnFatalFailure)3465 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
3466 TestPartResultArray gtest_failures;
3467 {
3468 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3469 DoAssertNoFatalFailureOnFails();
3470 }
3471 ASSERT_EQ(2, gtest_failures.size());
3472 EXPECT_EQ(TestPartResult::kFatalFailure,
3473 gtest_failures.GetTestPartResult(0).type());
3474 EXPECT_EQ(TestPartResult::kFatalFailure,
3475 gtest_failures.GetTestPartResult(1).type());
3476 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3477 gtest_failures.GetTestPartResult(0).message());
3478 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3479 gtest_failures.GetTestPartResult(1).message());
3480 }
3481
TEST_F(NoFatalFailureTest,ExpectNoFatalFailureOnFatalFailure)3482 TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
3483 TestPartResultArray gtest_failures;
3484 {
3485 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3486 DoExpectNoFatalFailureOnFails();
3487 }
3488 ASSERT_EQ(3, gtest_failures.size());
3489 EXPECT_EQ(TestPartResult::kFatalFailure,
3490 gtest_failures.GetTestPartResult(0).type());
3491 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3492 gtest_failures.GetTestPartResult(1).type());
3493 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3494 gtest_failures.GetTestPartResult(2).type());
3495 EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
3496 gtest_failures.GetTestPartResult(0).message());
3497 EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
3498 gtest_failures.GetTestPartResult(1).message());
3499 EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
3500 gtest_failures.GetTestPartResult(2).message());
3501 }
3502
TEST_F(NoFatalFailureTest,MessageIsStreamable)3503 TEST_F(NoFatalFailureTest, MessageIsStreamable) {
3504 TestPartResultArray gtest_failures;
3505 {
3506 ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
3507 EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
3508 }
3509 ASSERT_EQ(2, gtest_failures.size());
3510 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3511 gtest_failures.GetTestPartResult(0).type());
3512 EXPECT_EQ(TestPartResult::kNonFatalFailure,
3513 gtest_failures.GetTestPartResult(1).type());
3514 EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
3515 gtest_failures.GetTestPartResult(0).message());
3516 EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
3517 gtest_failures.GetTestPartResult(1).message());
3518 }
3519
3520 // Tests non-string assertions.
3521
EditsToString(const std::vector<EditType> & edits)3522 std::string EditsToString(const std::vector<EditType>& edits) {
3523 std::string out;
3524 for (size_t i = 0; i < edits.size(); ++i) {
3525 static const char kEdits[] = " +-/";
3526 out.append(1, kEdits[edits[i]]);
3527 }
3528 return out;
3529 }
3530
CharsToIndices(const std::string & str)3531 std::vector<size_t> CharsToIndices(const std::string& str) {
3532 std::vector<size_t> out;
3533 for (size_t i = 0; i < str.size(); ++i) {
3534 out.push_back(static_cast<size_t>(str[i]));
3535 }
3536 return out;
3537 }
3538
CharsToLines(const std::string & str)3539 std::vector<std::string> CharsToLines(const std::string& str) {
3540 std::vector<std::string> out;
3541 for (size_t i = 0; i < str.size(); ++i) {
3542 out.push_back(str.substr(i, 1));
3543 }
3544 return out;
3545 }
3546
TEST(EditDistance,TestSuites)3547 TEST(EditDistance, TestSuites) {
3548 struct Case {
3549 int line;
3550 const char* left;
3551 const char* right;
3552 const char* expected_edits;
3553 const char* expected_diff;
3554 };
3555 static const Case kCases[] = {
3556 // No change.
3557 {__LINE__, "A", "A", " ", ""},
3558 {__LINE__, "ABCDE", "ABCDE", " ", ""},
3559 // Simple adds.
3560 {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
3561 {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
3562 // Simple removes.
3563 {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
3564 {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
3565 // Simple replaces.
3566 {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
3567 {__LINE__, "ABCD", "abcd", "////",
3568 "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
3569 // Path finding.
3570 {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
3571 "@@ -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"},
3572 {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
3573 "@@ -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"},
3574 {__LINE__, "ABCDE", "BCDCD", "- +/",
3575 "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
3576 {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
3577 "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
3578 "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
3579 {}};
3580 for (const Case* c = kCases; c->left; ++c) {
3581 EXPECT_TRUE(c->expected_edits ==
3582 EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
3583 CharsToIndices(c->right))))
3584 << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
3585 << EditsToString(CalculateOptimalEdits(
3586 CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
3587 EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
3588 CharsToLines(c->right)))
3589 << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
3590 << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
3591 << ">";
3592 }
3593 }
3594
3595 // Tests EqFailure(), used for implementing *EQ* assertions.
TEST(AssertionTest,EqFailure)3596 TEST(AssertionTest, EqFailure) {
3597 const std::string foo_val("5"), bar_val("6");
3598 const std::string msg1(
3599 EqFailure("foo", "bar", foo_val, bar_val, false)
3600 .failure_message());
3601 EXPECT_STREQ(
3602 "Expected equality of these values:\n"
3603 " foo\n"
3604 " Which is: 5\n"
3605 " bar\n"
3606 " Which is: 6",
3607 msg1.c_str());
3608
3609 const std::string msg2(
3610 EqFailure("foo", "6", foo_val, bar_val, false)
3611 .failure_message());
3612 EXPECT_STREQ(
3613 "Expected equality of these values:\n"
3614 " foo\n"
3615 " Which is: 5\n"
3616 " 6",
3617 msg2.c_str());
3618
3619 const std::string msg3(
3620 EqFailure("5", "bar", foo_val, bar_val, false)
3621 .failure_message());
3622 EXPECT_STREQ(
3623 "Expected equality of these values:\n"
3624 " 5\n"
3625 " bar\n"
3626 " Which is: 6",
3627 msg3.c_str());
3628
3629 const std::string msg4(
3630 EqFailure("5", "6", foo_val, bar_val, false).failure_message());
3631 EXPECT_STREQ(
3632 "Expected equality of these values:\n"
3633 " 5\n"
3634 " 6",
3635 msg4.c_str());
3636
3637 const std::string msg5(
3638 EqFailure("foo", "bar",
3639 std::string("\"x\""), std::string("\"y\""),
3640 true).failure_message());
3641 EXPECT_STREQ(
3642 "Expected equality of these values:\n"
3643 " foo\n"
3644 " Which is: \"x\"\n"
3645 " bar\n"
3646 " Which is: \"y\"\n"
3647 "Ignoring case",
3648 msg5.c_str());
3649 }
3650
TEST(AssertionTest,EqFailureWithDiff)3651 TEST(AssertionTest, EqFailureWithDiff) {
3652 const std::string left(
3653 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
3654 const std::string right(
3655 "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
3656 const std::string msg1(
3657 EqFailure("left", "right", left, right, false).failure_message());
3658 EXPECT_STREQ(
3659 "Expected equality of these values:\n"
3660 " left\n"
3661 " Which is: "
3662 "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
3663 " right\n"
3664 " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
3665 "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
3666 "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
3667 msg1.c_str());
3668 }
3669
3670 // Tests AppendUserMessage(), used for implementing the *EQ* macros.
TEST(AssertionTest,AppendUserMessage)3671 TEST(AssertionTest, AppendUserMessage) {
3672 const std::string foo("foo");
3673
3674 Message msg;
3675 EXPECT_STREQ("foo",
3676 AppendUserMessage(foo, msg).c_str());
3677
3678 msg << "bar";
3679 EXPECT_STREQ("foo\nbar",
3680 AppendUserMessage(foo, msg).c_str());
3681 }
3682
3683 #ifdef __BORLANDC__
3684 // Silences warnings: "Condition is always true", "Unreachable code"
3685 # pragma option push -w-ccc -w-rch
3686 #endif
3687
3688 // Tests ASSERT_TRUE.
TEST(AssertionTest,ASSERT_TRUE)3689 TEST(AssertionTest, ASSERT_TRUE) {
3690 ASSERT_TRUE(2 > 1); // NOLINT
3691 EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
3692 "2 < 1");
3693 }
3694
3695 // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
TEST(AssertionTest,AssertTrueWithAssertionResult)3696 TEST(AssertionTest, AssertTrueWithAssertionResult) {
3697 ASSERT_TRUE(ResultIsEven(2));
3698 #ifndef __BORLANDC__
3699 // ICE's in C++Builder.
3700 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
3701 "Value of: ResultIsEven(3)\n"
3702 " Actual: false (3 is odd)\n"
3703 "Expected: true");
3704 #endif
3705 ASSERT_TRUE(ResultIsEvenNoExplanation(2));
3706 EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
3707 "Value of: ResultIsEvenNoExplanation(3)\n"
3708 " Actual: false (3 is odd)\n"
3709 "Expected: true");
3710 }
3711
3712 // Tests ASSERT_FALSE.
TEST(AssertionTest,ASSERT_FALSE)3713 TEST(AssertionTest, ASSERT_FALSE) {
3714 ASSERT_FALSE(2 < 1); // NOLINT
3715 EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
3716 "Value of: 2 > 1\n"
3717 " Actual: true\n"
3718 "Expected: false");
3719 }
3720
3721 // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
TEST(AssertionTest,AssertFalseWithAssertionResult)3722 TEST(AssertionTest, AssertFalseWithAssertionResult) {
3723 ASSERT_FALSE(ResultIsEven(3));
3724 #ifndef __BORLANDC__
3725 // ICE's in C++Builder.
3726 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
3727 "Value of: ResultIsEven(2)\n"
3728 " Actual: true (2 is even)\n"
3729 "Expected: false");
3730 #endif
3731 ASSERT_FALSE(ResultIsEvenNoExplanation(3));
3732 EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
3733 "Value of: ResultIsEvenNoExplanation(2)\n"
3734 " Actual: true\n"
3735 "Expected: false");
3736 }
3737
3738 #ifdef __BORLANDC__
3739 // Restores warnings after previous "#pragma option push" suppressed them
3740 # pragma option pop
3741 #endif
3742
3743 // Tests using ASSERT_EQ on double values. The purpose is to make
3744 // sure that the specialization we did for integer and anonymous enums
3745 // isn't used for double arguments.
TEST(ExpectTest,ASSERT_EQ_Double)3746 TEST(ExpectTest, ASSERT_EQ_Double) {
3747 // A success.
3748 ASSERT_EQ(5.6, 5.6);
3749
3750 // A failure.
3751 EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
3752 "5.1");
3753 }
3754
3755 // Tests ASSERT_EQ.
TEST(AssertionTest,ASSERT_EQ)3756 TEST(AssertionTest, ASSERT_EQ) {
3757 ASSERT_EQ(5, 2 + 3);
3758 EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
3759 "Expected equality of these values:\n"
3760 " 5\n"
3761 " 2*3\n"
3762 " Which is: 6");
3763 }
3764
3765 // Tests ASSERT_EQ(NULL, pointer).
TEST(AssertionTest,ASSERT_EQ_NULL)3766 TEST(AssertionTest, ASSERT_EQ_NULL) {
3767 // A success.
3768 const char* p = nullptr;
3769 ASSERT_EQ(nullptr, p);
3770
3771 // A failure.
3772 static int n = 0;
3773 EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:");
3774 }
3775
3776 // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
3777 // treated as a null pointer by the compiler, we need to make sure
3778 // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
3779 // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest,ASSERT_EQ_0)3780 TEST(ExpectTest, ASSERT_EQ_0) {
3781 int n = 0;
3782
3783 // A success.
3784 ASSERT_EQ(0, n);
3785
3786 // A failure.
3787 EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
3788 " 0\n 5.6");
3789 }
3790
3791 // Tests ASSERT_NE.
TEST(AssertionTest,ASSERT_NE)3792 TEST(AssertionTest, ASSERT_NE) {
3793 ASSERT_NE(6, 7);
3794 EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
3795 "Expected: ('a') != ('a'), "
3796 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
3797 }
3798
3799 // Tests ASSERT_LE.
TEST(AssertionTest,ASSERT_LE)3800 TEST(AssertionTest, ASSERT_LE) {
3801 ASSERT_LE(2, 3);
3802 ASSERT_LE(2, 2);
3803 EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
3804 "Expected: (2) <= (0), actual: 2 vs 0");
3805 }
3806
3807 // Tests ASSERT_LT.
TEST(AssertionTest,ASSERT_LT)3808 TEST(AssertionTest, ASSERT_LT) {
3809 ASSERT_LT(2, 3);
3810 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
3811 "Expected: (2) < (2), actual: 2 vs 2");
3812 }
3813
3814 // Tests ASSERT_GE.
TEST(AssertionTest,ASSERT_GE)3815 TEST(AssertionTest, ASSERT_GE) {
3816 ASSERT_GE(2, 1);
3817 ASSERT_GE(2, 2);
3818 EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
3819 "Expected: (2) >= (3), actual: 2 vs 3");
3820 }
3821
3822 // Tests ASSERT_GT.
TEST(AssertionTest,ASSERT_GT)3823 TEST(AssertionTest, ASSERT_GT) {
3824 ASSERT_GT(2, 1);
3825 EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
3826 "Expected: (2) > (2), actual: 2 vs 2");
3827 }
3828
3829 #if GTEST_HAS_EXCEPTIONS
3830
ThrowNothing()3831 void ThrowNothing() {}
3832
3833 // Tests ASSERT_THROW.
TEST(AssertionTest,ASSERT_THROW)3834 TEST(AssertionTest, ASSERT_THROW) {
3835 ASSERT_THROW(ThrowAnInteger(), int);
3836
3837 # ifndef __BORLANDC__
3838
3839 // ICE's in C++Builder 2007 and 2009.
3840 EXPECT_FATAL_FAILURE(
3841 ASSERT_THROW(ThrowAnInteger(), bool),
3842 "Expected: ThrowAnInteger() throws an exception of type bool.\n"
3843 " Actual: it throws a different type.");
3844 EXPECT_FATAL_FAILURE(
3845 ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
3846 "Expected: ThrowRuntimeError(\"A description\") "
3847 "throws an exception of type std::logic_error.\n "
3848 "Actual: it throws " ERROR_DESC " "
3849 "with description \"A description\".");
3850 # endif
3851
3852 EXPECT_FATAL_FAILURE(
3853 ASSERT_THROW(ThrowNothing(), bool),
3854 "Expected: ThrowNothing() throws an exception of type bool.\n"
3855 " Actual: it throws nothing.");
3856 }
3857
3858 // Tests ASSERT_NO_THROW.
TEST(AssertionTest,ASSERT_NO_THROW)3859 TEST(AssertionTest, ASSERT_NO_THROW) {
3860 ASSERT_NO_THROW(ThrowNothing());
3861 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
3862 "Expected: ThrowAnInteger() doesn't throw an exception."
3863 "\n Actual: it throws.");
3864 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
3865 "Expected: ThrowRuntimeError(\"A description\") "
3866 "doesn't throw an exception.\n "
3867 "Actual: it throws " ERROR_DESC " "
3868 "with description \"A description\".");
3869 }
3870
3871 // Tests ASSERT_ANY_THROW.
TEST(AssertionTest,ASSERT_ANY_THROW)3872 TEST(AssertionTest, ASSERT_ANY_THROW) {
3873 ASSERT_ANY_THROW(ThrowAnInteger());
3874 EXPECT_FATAL_FAILURE(
3875 ASSERT_ANY_THROW(ThrowNothing()),
3876 "Expected: ThrowNothing() throws an exception.\n"
3877 " Actual: it doesn't.");
3878 }
3879
3880 #endif // GTEST_HAS_EXCEPTIONS
3881
3882 // Makes sure we deal with the precedence of <<. This test should
3883 // compile.
TEST(AssertionTest,AssertPrecedence)3884 TEST(AssertionTest, AssertPrecedence) {
3885 ASSERT_EQ(1 < 2, true);
3886 bool false_value = false;
3887 ASSERT_EQ(true && false_value, false);
3888 }
3889
3890 // A subroutine used by the following test.
TestEq1(int x)3891 void TestEq1(int x) {
3892 ASSERT_EQ(1, x);
3893 }
3894
3895 // Tests calling a test subroutine that's not part of a fixture.
TEST(AssertionTest,NonFixtureSubroutine)3896 TEST(AssertionTest, NonFixtureSubroutine) {
3897 EXPECT_FATAL_FAILURE(TestEq1(2),
3898 " x\n Which is: 2");
3899 }
3900
3901 // An uncopyable class.
3902 class Uncopyable {
3903 public:
Uncopyable(int a_value)3904 explicit Uncopyable(int a_value) : value_(a_value) {}
3905
value() const3906 int value() const { return value_; }
operator ==(const Uncopyable & rhs) const3907 bool operator==(const Uncopyable& rhs) const {
3908 return value() == rhs.value();
3909 }
3910 private:
3911 // This constructor deliberately has no implementation, as we don't
3912 // want this class to be copyable.
3913 Uncopyable(const Uncopyable&); // NOLINT
3914
3915 int value_;
3916 };
3917
operator <<(::std::ostream & os,const Uncopyable & value)3918 ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
3919 return os << value.value();
3920 }
3921
3922
IsPositiveUncopyable(const Uncopyable & x)3923 bool IsPositiveUncopyable(const Uncopyable& x) {
3924 return x.value() > 0;
3925 }
3926
3927 // A subroutine used by the following test.
TestAssertNonPositive()3928 void TestAssertNonPositive() {
3929 Uncopyable y(-1);
3930 ASSERT_PRED1(IsPositiveUncopyable, y);
3931 }
3932 // A subroutine used by the following test.
TestAssertEqualsUncopyable()3933 void TestAssertEqualsUncopyable() {
3934 Uncopyable x(5);
3935 Uncopyable y(-1);
3936 ASSERT_EQ(x, y);
3937 }
3938
3939 // Tests that uncopyable objects can be used in assertions.
TEST(AssertionTest,AssertWorksWithUncopyableObject)3940 TEST(AssertionTest, AssertWorksWithUncopyableObject) {
3941 Uncopyable x(5);
3942 ASSERT_PRED1(IsPositiveUncopyable, x);
3943 ASSERT_EQ(x, x);
3944 EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
3945 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3946 EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
3947 "Expected equality of these values:\n"
3948 " x\n Which is: 5\n y\n Which is: -1");
3949 }
3950
3951 // Tests that uncopyable objects can be used in expects.
TEST(AssertionTest,ExpectWorksWithUncopyableObject)3952 TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
3953 Uncopyable x(5);
3954 EXPECT_PRED1(IsPositiveUncopyable, x);
3955 Uncopyable y(-1);
3956 EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
3957 "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
3958 EXPECT_EQ(x, x);
3959 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
3960 "Expected equality of these values:\n"
3961 " x\n Which is: 5\n y\n Which is: -1");
3962 }
3963
3964 enum NamedEnum {
3965 kE1 = 0,
3966 kE2 = 1
3967 };
3968
TEST(AssertionTest,NamedEnum)3969 TEST(AssertionTest, NamedEnum) {
3970 EXPECT_EQ(kE1, kE1);
3971 EXPECT_LT(kE1, kE2);
3972 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
3973 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
3974 }
3975
3976 // Sun Studio and HP aCC2reject this code.
3977 #if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
3978
3979 // Tests using assertions with anonymous enums.
3980 enum {
3981 kCaseA = -1,
3982
3983 # if GTEST_OS_LINUX
3984
3985 // We want to test the case where the size of the anonymous enum is
3986 // larger than sizeof(int), to make sure our implementation of the
3987 // assertions doesn't truncate the enums. However, MSVC
3988 // (incorrectly) doesn't allow an enum value to exceed the range of
3989 // an int, so this has to be conditionally compiled.
3990 //
3991 // On Linux, kCaseB and kCaseA have the same value when truncated to
3992 // int size. We want to test whether this will confuse the
3993 // assertions.
3994 kCaseB = testing::internal::kMaxBiggestInt,
3995
3996 # else
3997
3998 kCaseB = INT_MAX,
3999
4000 # endif // GTEST_OS_LINUX
4001
4002 kCaseC = 42
4003 };
4004
TEST(AssertionTest,AnonymousEnum)4005 TEST(AssertionTest, AnonymousEnum) {
4006 # if GTEST_OS_LINUX
4007
4008 EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
4009
4010 # endif // GTEST_OS_LINUX
4011
4012 EXPECT_EQ(kCaseA, kCaseA);
4013 EXPECT_NE(kCaseA, kCaseB);
4014 EXPECT_LT(kCaseA, kCaseB);
4015 EXPECT_LE(kCaseA, kCaseB);
4016 EXPECT_GT(kCaseB, kCaseA);
4017 EXPECT_GE(kCaseA, kCaseA);
4018 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
4019 "(kCaseA) >= (kCaseB)");
4020 EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
4021 "-1 vs 42");
4022
4023 ASSERT_EQ(kCaseA, kCaseA);
4024 ASSERT_NE(kCaseA, kCaseB);
4025 ASSERT_LT(kCaseA, kCaseB);
4026 ASSERT_LE(kCaseA, kCaseB);
4027 ASSERT_GT(kCaseB, kCaseA);
4028 ASSERT_GE(kCaseA, kCaseA);
4029
4030 # ifndef __BORLANDC__
4031
4032 // ICE's in C++Builder.
4033 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
4034 " kCaseB\n Which is: ");
4035 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
4036 "\n Which is: 42");
4037 # endif
4038
4039 EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
4040 "\n Which is: -1");
4041 }
4042
4043 #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
4044
4045 #if GTEST_OS_WINDOWS
4046
UnexpectedHRESULTFailure()4047 static HRESULT UnexpectedHRESULTFailure() {
4048 return E_UNEXPECTED;
4049 }
4050
OkHRESULTSuccess()4051 static HRESULT OkHRESULTSuccess() {
4052 return S_OK;
4053 }
4054
FalseHRESULTSuccess()4055 static HRESULT FalseHRESULTSuccess() {
4056 return S_FALSE;
4057 }
4058
4059 // HRESULT assertion tests test both zero and non-zero
4060 // success codes as well as failure message for each.
4061 //
4062 // Windows CE doesn't support message texts.
TEST(HRESULTAssertionTest,EXPECT_HRESULT_SUCCEEDED)4063 TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
4064 EXPECT_HRESULT_SUCCEEDED(S_OK);
4065 EXPECT_HRESULT_SUCCEEDED(S_FALSE);
4066
4067 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4068 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4069 " Actual: 0x8000FFFF");
4070 }
4071
TEST(HRESULTAssertionTest,ASSERT_HRESULT_SUCCEEDED)4072 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
4073 ASSERT_HRESULT_SUCCEEDED(S_OK);
4074 ASSERT_HRESULT_SUCCEEDED(S_FALSE);
4075
4076 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
4077 "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
4078 " Actual: 0x8000FFFF");
4079 }
4080
TEST(HRESULTAssertionTest,EXPECT_HRESULT_FAILED)4081 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
4082 EXPECT_HRESULT_FAILED(E_UNEXPECTED);
4083
4084 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
4085 "Expected: (OkHRESULTSuccess()) fails.\n"
4086 " Actual: 0x0");
4087 EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
4088 "Expected: (FalseHRESULTSuccess()) fails.\n"
4089 " Actual: 0x1");
4090 }
4091
TEST(HRESULTAssertionTest,ASSERT_HRESULT_FAILED)4092 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
4093 ASSERT_HRESULT_FAILED(E_UNEXPECTED);
4094
4095 # ifndef __BORLANDC__
4096
4097 // ICE's in C++Builder 2007 and 2009.
4098 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
4099 "Expected: (OkHRESULTSuccess()) fails.\n"
4100 " Actual: 0x0");
4101 # endif
4102
4103 EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
4104 "Expected: (FalseHRESULTSuccess()) fails.\n"
4105 " Actual: 0x1");
4106 }
4107
4108 // Tests that streaming to the HRESULT macros works.
TEST(HRESULTAssertionTest,Streaming)4109 TEST(HRESULTAssertionTest, Streaming) {
4110 EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4111 ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
4112 EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4113 ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
4114
4115 EXPECT_NONFATAL_FAILURE(
4116 EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4117 "expected failure");
4118
4119 # ifndef __BORLANDC__
4120
4121 // ICE's in C++Builder 2007 and 2009.
4122 EXPECT_FATAL_FAILURE(
4123 ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
4124 "expected failure");
4125 # endif
4126
4127 EXPECT_NONFATAL_FAILURE(
4128 EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
4129 "expected failure");
4130
4131 EXPECT_FATAL_FAILURE(
4132 ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
4133 "expected failure");
4134 }
4135
4136 #endif // GTEST_OS_WINDOWS
4137
4138 // The following code intentionally tests a suboptimal syntax.
4139 #ifdef __GNUC__
4140 #pragma GCC diagnostic push
4141 #pragma GCC diagnostic ignored "-Wdangling-else"
4142 #pragma GCC diagnostic ignored "-Wempty-body"
4143 #pragma GCC diagnostic ignored "-Wpragmas"
4144 #endif
4145 // Tests that the assertion macros behave like single statements.
TEST(AssertionSyntaxTest,BasicAssertionsBehavesLikeSingleStatement)4146 TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
4147 if (AlwaysFalse())
4148 ASSERT_TRUE(false) << "This should never be executed; "
4149 "It's a compilation test only.";
4150
4151 if (AlwaysTrue())
4152 EXPECT_FALSE(false);
4153 else
4154 ; // NOLINT
4155
4156 if (AlwaysFalse())
4157 ASSERT_LT(1, 3);
4158
4159 if (AlwaysFalse())
4160 ; // NOLINT
4161 else
4162 EXPECT_GT(3, 2) << "";
4163 }
4164 #ifdef __GNUC__
4165 #pragma GCC diagnostic pop
4166 #endif
4167
4168 #if GTEST_HAS_EXCEPTIONS
4169 // Tests that the compiler will not complain about unreachable code in the
4170 // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
TEST(ExpectThrowTest,DoesNotGenerateUnreachableCodeWarning)4171 TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
4172 int n = 0;
4173
4174 EXPECT_THROW(throw 1, int);
4175 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
4176 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
4177 EXPECT_NO_THROW(n++);
4178 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
4179 EXPECT_ANY_THROW(throw 1);
4180 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
4181 }
4182
TEST(ExpectThrowTest,DoesNotGenerateDuplicateCatchClauseWarning)4183 TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
4184 EXPECT_THROW(throw std::exception(), std::exception);
4185 }
4186
4187 // The following code intentionally tests a suboptimal syntax.
4188 #ifdef __GNUC__
4189 #pragma GCC diagnostic push
4190 #pragma GCC diagnostic ignored "-Wdangling-else"
4191 #pragma GCC diagnostic ignored "-Wempty-body"
4192 #pragma GCC diagnostic ignored "-Wpragmas"
4193 #endif
TEST(AssertionSyntaxTest,ExceptionAssertionsBehavesLikeSingleStatement)4194 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
4195 if (AlwaysFalse())
4196 EXPECT_THROW(ThrowNothing(), bool);
4197
4198 if (AlwaysTrue())
4199 EXPECT_THROW(ThrowAnInteger(), int);
4200 else
4201 ; // NOLINT
4202
4203 if (AlwaysFalse())
4204 EXPECT_NO_THROW(ThrowAnInteger());
4205
4206 if (AlwaysTrue())
4207 EXPECT_NO_THROW(ThrowNothing());
4208 else
4209 ; // NOLINT
4210
4211 if (AlwaysFalse())
4212 EXPECT_ANY_THROW(ThrowNothing());
4213
4214 if (AlwaysTrue())
4215 EXPECT_ANY_THROW(ThrowAnInteger());
4216 else
4217 ; // NOLINT
4218 }
4219 #ifdef __GNUC__
4220 #pragma GCC diagnostic pop
4221 #endif
4222
4223 #endif // GTEST_HAS_EXCEPTIONS
4224
4225 // The following code intentionally tests a suboptimal syntax.
4226 #ifdef __GNUC__
4227 #pragma GCC diagnostic push
4228 #pragma GCC diagnostic ignored "-Wdangling-else"
4229 #pragma GCC diagnostic ignored "-Wempty-body"
4230 #pragma GCC diagnostic ignored "-Wpragmas"
4231 #endif
TEST(AssertionSyntaxTest,NoFatalFailureAssertionsBehavesLikeSingleStatement)4232 TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
4233 if (AlwaysFalse())
4234 EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
4235 << "It's a compilation test only.";
4236 else
4237 ; // NOLINT
4238
4239 if (AlwaysFalse())
4240 ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
4241 else
4242 ; // NOLINT
4243
4244 if (AlwaysTrue())
4245 EXPECT_NO_FATAL_FAILURE(SUCCEED());
4246 else
4247 ; // NOLINT
4248
4249 if (AlwaysFalse())
4250 ; // NOLINT
4251 else
4252 ASSERT_NO_FATAL_FAILURE(SUCCEED());
4253 }
4254 #ifdef __GNUC__
4255 #pragma GCC diagnostic pop
4256 #endif
4257
4258 // Tests that the assertion macros work well with switch statements.
TEST(AssertionSyntaxTest,WorksWithSwitch)4259 TEST(AssertionSyntaxTest, WorksWithSwitch) {
4260 switch (0) {
4261 case 1:
4262 break;
4263 default:
4264 ASSERT_TRUE(true);
4265 }
4266
4267 switch (0)
4268 case 0:
4269 EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
4270
4271 // Binary assertions are implemented using a different code path
4272 // than the Boolean assertions. Hence we test them separately.
4273 switch (0) {
4274 case 1:
4275 default:
4276 ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
4277 }
4278
4279 switch (0)
4280 case 0:
4281 EXPECT_NE(1, 2);
4282 }
4283
4284 #if GTEST_HAS_EXCEPTIONS
4285
ThrowAString()4286 void ThrowAString() {
4287 throw "std::string";
4288 }
4289
4290 // Test that the exception assertion macros compile and work with const
4291 // type qualifier.
TEST(AssertionSyntaxTest,WorksWithConst)4292 TEST(AssertionSyntaxTest, WorksWithConst) {
4293 ASSERT_THROW(ThrowAString(), const char*);
4294
4295 EXPECT_THROW(ThrowAString(), const char*);
4296 }
4297
4298 #endif // GTEST_HAS_EXCEPTIONS
4299
4300 } // namespace
4301
4302 namespace testing {
4303
4304 // Tests that Google Test tracks SUCCEED*.
TEST(SuccessfulAssertionTest,SUCCEED)4305 TEST(SuccessfulAssertionTest, SUCCEED) {
4306 SUCCEED();
4307 SUCCEED() << "OK";
4308 EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
4309 }
4310
4311 // Tests that Google Test doesn't track successful EXPECT_*.
TEST(SuccessfulAssertionTest,EXPECT)4312 TEST(SuccessfulAssertionTest, EXPECT) {
4313 EXPECT_TRUE(true);
4314 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4315 }
4316
4317 // Tests that Google Test doesn't track successful EXPECT_STR*.
TEST(SuccessfulAssertionTest,EXPECT_STR)4318 TEST(SuccessfulAssertionTest, EXPECT_STR) {
4319 EXPECT_STREQ("", "");
4320 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4321 }
4322
4323 // Tests that Google Test doesn't track successful ASSERT_*.
TEST(SuccessfulAssertionTest,ASSERT)4324 TEST(SuccessfulAssertionTest, ASSERT) {
4325 ASSERT_TRUE(true);
4326 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4327 }
4328
4329 // Tests that Google Test doesn't track successful ASSERT_STR*.
TEST(SuccessfulAssertionTest,ASSERT_STR)4330 TEST(SuccessfulAssertionTest, ASSERT_STR) {
4331 ASSERT_STREQ("", "");
4332 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
4333 }
4334
4335 } // namespace testing
4336
4337 namespace {
4338
4339 // Tests the message streaming variation of assertions.
4340
TEST(AssertionWithMessageTest,EXPECT)4341 TEST(AssertionWithMessageTest, EXPECT) {
4342 EXPECT_EQ(1, 1) << "This should succeed.";
4343 EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
4344 "Expected failure #1");
4345 EXPECT_LE(1, 2) << "This should succeed.";
4346 EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
4347 "Expected failure #2.");
4348 EXPECT_GE(1, 0) << "This should succeed.";
4349 EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
4350 "Expected failure #3.");
4351
4352 EXPECT_STREQ("1", "1") << "This should succeed.";
4353 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
4354 "Expected failure #4.");
4355 EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
4356 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
4357 "Expected failure #5.");
4358
4359 EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
4360 EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
4361 "Expected failure #6.");
4362 EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
4363 }
4364
TEST(AssertionWithMessageTest,ASSERT)4365 TEST(AssertionWithMessageTest, ASSERT) {
4366 ASSERT_EQ(1, 1) << "This should succeed.";
4367 ASSERT_NE(1, 2) << "This should succeed.";
4368 ASSERT_LE(1, 2) << "This should succeed.";
4369 ASSERT_LT(1, 2) << "This should succeed.";
4370 ASSERT_GE(1, 0) << "This should succeed.";
4371 EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
4372 "Expected failure.");
4373 }
4374
TEST(AssertionWithMessageTest,ASSERT_STR)4375 TEST(AssertionWithMessageTest, ASSERT_STR) {
4376 ASSERT_STREQ("1", "1") << "This should succeed.";
4377 ASSERT_STRNE("1", "2") << "This should succeed.";
4378 ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
4379 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
4380 "Expected failure.");
4381 }
4382
TEST(AssertionWithMessageTest,ASSERT_FLOATING)4383 TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
4384 ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
4385 ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
4386 EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT
4387 "Expect failure.");
4388 }
4389
4390 // Tests using ASSERT_FALSE with a streamed message.
TEST(AssertionWithMessageTest,ASSERT_FALSE)4391 TEST(AssertionWithMessageTest, ASSERT_FALSE) {
4392 ASSERT_FALSE(false) << "This shouldn't fail.";
4393 EXPECT_FATAL_FAILURE({ // NOLINT
4394 ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
4395 << " evaluates to " << true;
4396 }, "Expected failure");
4397 }
4398
4399 // Tests using FAIL with a streamed message.
TEST(AssertionWithMessageTest,FAIL)4400 TEST(AssertionWithMessageTest, FAIL) {
4401 EXPECT_FATAL_FAILURE(FAIL() << 0,
4402 "0");
4403 }
4404
4405 // Tests using SUCCEED with a streamed message.
TEST(AssertionWithMessageTest,SUCCEED)4406 TEST(AssertionWithMessageTest, SUCCEED) {
4407 SUCCEED() << "Success == " << 1;
4408 }
4409
4410 // Tests using ASSERT_TRUE with a streamed message.
TEST(AssertionWithMessageTest,ASSERT_TRUE)4411 TEST(AssertionWithMessageTest, ASSERT_TRUE) {
4412 ASSERT_TRUE(true) << "This should succeed.";
4413 ASSERT_TRUE(true) << true;
4414 EXPECT_FATAL_FAILURE(
4415 { // NOLINT
4416 ASSERT_TRUE(false) << static_cast<const char*>(nullptr)
4417 << static_cast<char*>(nullptr);
4418 },
4419 "(null)(null)");
4420 }
4421
4422 #if GTEST_OS_WINDOWS
4423 // Tests using wide strings in assertion messages.
TEST(AssertionWithMessageTest,WideStringMessage)4424 TEST(AssertionWithMessageTest, WideStringMessage) {
4425 EXPECT_NONFATAL_FAILURE({ // NOLINT
4426 EXPECT_TRUE(false) << L"This failure is expected.\x8119";
4427 }, "This failure is expected.");
4428 EXPECT_FATAL_FAILURE({ // NOLINT
4429 ASSERT_EQ(1, 2) << "This failure is "
4430 << L"expected too.\x8120";
4431 }, "This failure is expected too.");
4432 }
4433 #endif // GTEST_OS_WINDOWS
4434
4435 // Tests EXPECT_TRUE.
TEST(ExpectTest,EXPECT_TRUE)4436 TEST(ExpectTest, EXPECT_TRUE) {
4437 EXPECT_TRUE(true) << "Intentional success";
4438 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
4439 "Intentional failure #1.");
4440 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
4441 "Intentional failure #2.");
4442 EXPECT_TRUE(2 > 1); // NOLINT
4443 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
4444 "Value of: 2 < 1\n"
4445 " Actual: false\n"
4446 "Expected: true");
4447 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
4448 "2 > 3");
4449 }
4450
4451 // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
TEST(ExpectTest,ExpectTrueWithAssertionResult)4452 TEST(ExpectTest, ExpectTrueWithAssertionResult) {
4453 EXPECT_TRUE(ResultIsEven(2));
4454 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
4455 "Value of: ResultIsEven(3)\n"
4456 " Actual: false (3 is odd)\n"
4457 "Expected: true");
4458 EXPECT_TRUE(ResultIsEvenNoExplanation(2));
4459 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
4460 "Value of: ResultIsEvenNoExplanation(3)\n"
4461 " Actual: false (3 is odd)\n"
4462 "Expected: true");
4463 }
4464
4465 // Tests EXPECT_FALSE with a streamed message.
TEST(ExpectTest,EXPECT_FALSE)4466 TEST(ExpectTest, EXPECT_FALSE) {
4467 EXPECT_FALSE(2 < 1); // NOLINT
4468 EXPECT_FALSE(false) << "Intentional success";
4469 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
4470 "Intentional failure #1.");
4471 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
4472 "Intentional failure #2.");
4473 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
4474 "Value of: 2 > 1\n"
4475 " Actual: true\n"
4476 "Expected: false");
4477 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
4478 "2 < 3");
4479 }
4480
4481 // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
TEST(ExpectTest,ExpectFalseWithAssertionResult)4482 TEST(ExpectTest, ExpectFalseWithAssertionResult) {
4483 EXPECT_FALSE(ResultIsEven(3));
4484 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
4485 "Value of: ResultIsEven(2)\n"
4486 " Actual: true (2 is even)\n"
4487 "Expected: false");
4488 EXPECT_FALSE(ResultIsEvenNoExplanation(3));
4489 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
4490 "Value of: ResultIsEvenNoExplanation(2)\n"
4491 " Actual: true\n"
4492 "Expected: false");
4493 }
4494
4495 #ifdef __BORLANDC__
4496 // Restores warnings after previous "#pragma option push" suppressed them
4497 # pragma option pop
4498 #endif
4499
4500 // Tests EXPECT_EQ.
TEST(ExpectTest,EXPECT_EQ)4501 TEST(ExpectTest, EXPECT_EQ) {
4502 EXPECT_EQ(5, 2 + 3);
4503 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
4504 "Expected equality of these values:\n"
4505 " 5\n"
4506 " 2*3\n"
4507 " Which is: 6");
4508 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
4509 "2 - 3");
4510 }
4511
4512 // Tests using EXPECT_EQ on double values. The purpose is to make
4513 // sure that the specialization we did for integer and anonymous enums
4514 // isn't used for double arguments.
TEST(ExpectTest,EXPECT_EQ_Double)4515 TEST(ExpectTest, EXPECT_EQ_Double) {
4516 // A success.
4517 EXPECT_EQ(5.6, 5.6);
4518
4519 // A failure.
4520 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
4521 "5.1");
4522 }
4523
4524 // Tests EXPECT_EQ(NULL, pointer).
TEST(ExpectTest,EXPECT_EQ_NULL)4525 TEST(ExpectTest, EXPECT_EQ_NULL) {
4526 // A success.
4527 const char* p = nullptr;
4528 EXPECT_EQ(nullptr, p);
4529
4530 // A failure.
4531 int n = 0;
4532 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:");
4533 }
4534
4535 // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
4536 // treated as a null pointer by the compiler, we need to make sure
4537 // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
4538 // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest,EXPECT_EQ_0)4539 TEST(ExpectTest, EXPECT_EQ_0) {
4540 int n = 0;
4541
4542 // A success.
4543 EXPECT_EQ(0, n);
4544
4545 // A failure.
4546 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
4547 " 0\n 5.6");
4548 }
4549
4550 // Tests EXPECT_NE.
TEST(ExpectTest,EXPECT_NE)4551 TEST(ExpectTest, EXPECT_NE) {
4552 EXPECT_NE(6, 7);
4553
4554 EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
4555 "Expected: ('a') != ('a'), "
4556 "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
4557 EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
4558 "2");
4559 char* const p0 = nullptr;
4560 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
4561 "p0");
4562 // Only way to get the Nokia compiler to compile the cast
4563 // is to have a separate void* variable first. Putting
4564 // the two casts on the same line doesn't work, neither does
4565 // a direct C-style to char*.
4566 void* pv1 = (void*)0x1234; // NOLINT
4567 char* const p1 = reinterpret_cast<char*>(pv1);
4568 EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
4569 "p1");
4570 }
4571
4572 // Tests EXPECT_LE.
TEST(ExpectTest,EXPECT_LE)4573 TEST(ExpectTest, EXPECT_LE) {
4574 EXPECT_LE(2, 3);
4575 EXPECT_LE(2, 2);
4576 EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
4577 "Expected: (2) <= (0), actual: 2 vs 0");
4578 EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
4579 "(1.1) <= (0.9)");
4580 }
4581
4582 // Tests EXPECT_LT.
TEST(ExpectTest,EXPECT_LT)4583 TEST(ExpectTest, EXPECT_LT) {
4584 EXPECT_LT(2, 3);
4585 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
4586 "Expected: (2) < (2), actual: 2 vs 2");
4587 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
4588 "(2) < (1)");
4589 }
4590
4591 // Tests EXPECT_GE.
TEST(ExpectTest,EXPECT_GE)4592 TEST(ExpectTest, EXPECT_GE) {
4593 EXPECT_GE(2, 1);
4594 EXPECT_GE(2, 2);
4595 EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
4596 "Expected: (2) >= (3), actual: 2 vs 3");
4597 EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
4598 "(0.9) >= (1.1)");
4599 }
4600
4601 // Tests EXPECT_GT.
TEST(ExpectTest,EXPECT_GT)4602 TEST(ExpectTest, EXPECT_GT) {
4603 EXPECT_GT(2, 1);
4604 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
4605 "Expected: (2) > (2), actual: 2 vs 2");
4606 EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
4607 "(2) > (3)");
4608 }
4609
4610 #if GTEST_HAS_EXCEPTIONS
4611
4612 // Tests EXPECT_THROW.
TEST(ExpectTest,EXPECT_THROW)4613 TEST(ExpectTest, EXPECT_THROW) {
4614 EXPECT_THROW(ThrowAnInteger(), int);
4615 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
4616 "Expected: ThrowAnInteger() throws an exception of "
4617 "type bool.\n Actual: it throws a different type.");
4618 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"),
4619 std::logic_error),
4620 "Expected: ThrowRuntimeError(\"A description\") "
4621 "throws an exception of type std::logic_error.\n "
4622 "Actual: it throws " ERROR_DESC " "
4623 "with description \"A description\".");
4624 EXPECT_NONFATAL_FAILURE(
4625 EXPECT_THROW(ThrowNothing(), bool),
4626 "Expected: ThrowNothing() throws an exception of type bool.\n"
4627 " Actual: it throws nothing.");
4628 }
4629
4630 // Tests EXPECT_NO_THROW.
TEST(ExpectTest,EXPECT_NO_THROW)4631 TEST(ExpectTest, EXPECT_NO_THROW) {
4632 EXPECT_NO_THROW(ThrowNothing());
4633 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
4634 "Expected: ThrowAnInteger() doesn't throw an "
4635 "exception.\n Actual: it throws.");
4636 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
4637 "Expected: ThrowRuntimeError(\"A description\") "
4638 "doesn't throw an exception.\n "
4639 "Actual: it throws " ERROR_DESC " "
4640 "with description \"A description\".");
4641 }
4642
4643 // Tests EXPECT_ANY_THROW.
TEST(ExpectTest,EXPECT_ANY_THROW)4644 TEST(ExpectTest, EXPECT_ANY_THROW) {
4645 EXPECT_ANY_THROW(ThrowAnInteger());
4646 EXPECT_NONFATAL_FAILURE(
4647 EXPECT_ANY_THROW(ThrowNothing()),
4648 "Expected: ThrowNothing() throws an exception.\n"
4649 " Actual: it doesn't.");
4650 }
4651
4652 #endif // GTEST_HAS_EXCEPTIONS
4653
4654 // Make sure we deal with the precedence of <<.
TEST(ExpectTest,ExpectPrecedence)4655 TEST(ExpectTest, ExpectPrecedence) {
4656 EXPECT_EQ(1 < 2, true);
4657 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
4658 " true && false\n Which is: false");
4659 }
4660
4661
4662 // Tests the StreamableToString() function.
4663
4664 // Tests using StreamableToString() on a scalar.
TEST(StreamableToStringTest,Scalar)4665 TEST(StreamableToStringTest, Scalar) {
4666 EXPECT_STREQ("5", StreamableToString(5).c_str());
4667 }
4668
4669 // Tests using StreamableToString() on a non-char pointer.
TEST(StreamableToStringTest,Pointer)4670 TEST(StreamableToStringTest, Pointer) {
4671 int n = 0;
4672 int* p = &n;
4673 EXPECT_STRNE("(null)", StreamableToString(p).c_str());
4674 }
4675
4676 // Tests using StreamableToString() on a NULL non-char pointer.
TEST(StreamableToStringTest,NullPointer)4677 TEST(StreamableToStringTest, NullPointer) {
4678 int* p = nullptr;
4679 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4680 }
4681
4682 // Tests using StreamableToString() on a C string.
TEST(StreamableToStringTest,CString)4683 TEST(StreamableToStringTest, CString) {
4684 EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
4685 }
4686
4687 // Tests using StreamableToString() on a NULL C string.
TEST(StreamableToStringTest,NullCString)4688 TEST(StreamableToStringTest, NullCString) {
4689 char* p = nullptr;
4690 EXPECT_STREQ("(null)", StreamableToString(p).c_str());
4691 }
4692
4693 // Tests using streamable values as assertion messages.
4694
4695 // Tests using std::string as an assertion message.
TEST(StreamableTest,string)4696 TEST(StreamableTest, string) {
4697 static const std::string str(
4698 "This failure message is a std::string, and is expected.");
4699 EXPECT_FATAL_FAILURE(FAIL() << str,
4700 str.c_str());
4701 }
4702
4703 // Tests that we can output strings containing embedded NULs.
4704 // Limited to Linux because we can only do this with std::string's.
TEST(StreamableTest,stringWithEmbeddedNUL)4705 TEST(StreamableTest, stringWithEmbeddedNUL) {
4706 static const char char_array_with_nul[] =
4707 "Here's a NUL\0 and some more string";
4708 static const std::string string_with_nul(char_array_with_nul,
4709 sizeof(char_array_with_nul)
4710 - 1); // drops the trailing NUL
4711 EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
4712 "Here's a NUL\\0 and some more string");
4713 }
4714
4715 // Tests that we can output a NUL char.
TEST(StreamableTest,NULChar)4716 TEST(StreamableTest, NULChar) {
4717 EXPECT_FATAL_FAILURE({ // NOLINT
4718 FAIL() << "A NUL" << '\0' << " and some more string";
4719 }, "A NUL\\0 and some more string");
4720 }
4721
4722 // Tests using int as an assertion message.
TEST(StreamableTest,int)4723 TEST(StreamableTest, int) {
4724 EXPECT_FATAL_FAILURE(FAIL() << 900913,
4725 "900913");
4726 }
4727
4728 // Tests using NULL char pointer as an assertion message.
4729 //
4730 // In MSVC, streaming a NULL char * causes access violation. Google Test
4731 // implemented a workaround (substituting "(null)" for NULL). This
4732 // tests whether the workaround works.
TEST(StreamableTest,NullCharPtr)4733 TEST(StreamableTest, NullCharPtr) {
4734 EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)");
4735 }
4736
4737 // Tests that basic IO manipulators (endl, ends, and flush) can be
4738 // streamed to testing::Message.
TEST(StreamableTest,BasicIoManip)4739 TEST(StreamableTest, BasicIoManip) {
4740 EXPECT_FATAL_FAILURE({ // NOLINT
4741 FAIL() << "Line 1." << std::endl
4742 << "A NUL char " << std::ends << std::flush << " in line 2.";
4743 }, "Line 1.\nA NUL char \\0 in line 2.");
4744 }
4745
4746 // Tests the macros that haven't been covered so far.
4747
AddFailureHelper(bool * aborted)4748 void AddFailureHelper(bool* aborted) {
4749 *aborted = true;
4750 ADD_FAILURE() << "Intentional failure.";
4751 *aborted = false;
4752 }
4753
4754 // Tests ADD_FAILURE.
TEST(MacroTest,ADD_FAILURE)4755 TEST(MacroTest, ADD_FAILURE) {
4756 bool aborted = true;
4757 EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
4758 "Intentional failure.");
4759 EXPECT_FALSE(aborted);
4760 }
4761
4762 // Tests ADD_FAILURE_AT.
TEST(MacroTest,ADD_FAILURE_AT)4763 TEST(MacroTest, ADD_FAILURE_AT) {
4764 // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
4765 // the failure message contains the user-streamed part.
4766 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4767
4768 // Verifies that the user-streamed part is optional.
4769 EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
4770
4771 // Unfortunately, we cannot verify that the failure message contains
4772 // the right file path and line number the same way, as
4773 // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
4774 // line number. Instead, we do that in googletest-output-test_.cc.
4775 }
4776
4777 // Tests FAIL.
TEST(MacroTest,FAIL)4778 TEST(MacroTest, FAIL) {
4779 EXPECT_FATAL_FAILURE(FAIL(),
4780 "Failed");
4781 EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
4782 "Intentional failure.");
4783 }
4784
4785 // Tests GTEST_FAIL_AT.
TEST(MacroTest,GTEST_FAIL_AT)4786 TEST(MacroTest, GTEST_FAIL_AT) {
4787 // Verifies that GTEST_FAIL_AT does generate a fatal failure and
4788 // the failure message contains the user-streamed part.
4789 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!");
4790
4791 // Verifies that the user-streamed part is optional.
4792 EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed");
4793
4794 // See the ADD_FAIL_AT test above to see how we test that the failure message
4795 // contains the right filename and line number -- the same applies here.
4796 }
4797
4798 // Tests SUCCEED
TEST(MacroTest,SUCCEED)4799 TEST(MacroTest, SUCCEED) {
4800 SUCCEED();
4801 SUCCEED() << "Explicit success.";
4802 }
4803
4804 // Tests for EXPECT_EQ() and ASSERT_EQ().
4805 //
4806 // These tests fail *intentionally*, s.t. the failure messages can be
4807 // generated and tested.
4808 //
4809 // We have different tests for different argument types.
4810
4811 // Tests using bool values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,Bool)4812 TEST(EqAssertionTest, Bool) {
4813 EXPECT_EQ(true, true);
4814 EXPECT_FATAL_FAILURE({
4815 bool false_value = false;
4816 ASSERT_EQ(false_value, true);
4817 }, " false_value\n Which is: false\n true");
4818 }
4819
4820 // Tests using int values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,Int)4821 TEST(EqAssertionTest, Int) {
4822 ASSERT_EQ(32, 32);
4823 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
4824 " 32\n 33");
4825 }
4826
4827 // Tests using time_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,Time_T)4828 TEST(EqAssertionTest, Time_T) {
4829 EXPECT_EQ(static_cast<time_t>(0),
4830 static_cast<time_t>(0));
4831 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
4832 static_cast<time_t>(1234)),
4833 "1234");
4834 }
4835
4836 // Tests using char values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,Char)4837 TEST(EqAssertionTest, Char) {
4838 ASSERT_EQ('z', 'z');
4839 const char ch = 'b';
4840 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
4841 " ch\n Which is: 'b'");
4842 EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
4843 " ch\n Which is: 'b'");
4844 }
4845
4846 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,WideChar)4847 TEST(EqAssertionTest, WideChar) {
4848 EXPECT_EQ(L'b', L'b');
4849
4850 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
4851 "Expected equality of these values:\n"
4852 " L'\0'\n"
4853 " Which is: L'\0' (0, 0x0)\n"
4854 " L'x'\n"
4855 " Which is: L'x' (120, 0x78)");
4856
4857 static wchar_t wchar;
4858 wchar = L'b';
4859 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
4860 "wchar");
4861 wchar = 0x8119;
4862 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
4863 " wchar\n Which is: L'");
4864 }
4865
4866 // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,StdString)4867 TEST(EqAssertionTest, StdString) {
4868 // Compares a const char* to an std::string that has identical
4869 // content.
4870 ASSERT_EQ("Test", ::std::string("Test"));
4871
4872 // Compares two identical std::strings.
4873 static const ::std::string str1("A * in the middle");
4874 static const ::std::string str2(str1);
4875 EXPECT_EQ(str1, str2);
4876
4877 // Compares a const char* to an std::string that has different
4878 // content
4879 EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
4880 "\"test\"");
4881
4882 // Compares an std::string to a char* that has different content.
4883 char* const p1 = const_cast<char*>("foo");
4884 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
4885 "p1");
4886
4887 // Compares two std::strings that have different contents, one of
4888 // which having a NUL character in the middle. This should fail.
4889 static ::std::string str3(str1);
4890 str3.at(2) = '\0';
4891 EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
4892 " str3\n Which is: \"A \\0 in the middle\"");
4893 }
4894
4895 #if GTEST_HAS_STD_WSTRING
4896
4897 // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,StdWideString)4898 TEST(EqAssertionTest, StdWideString) {
4899 // Compares two identical std::wstrings.
4900 const ::std::wstring wstr1(L"A * in the middle");
4901 const ::std::wstring wstr2(wstr1);
4902 ASSERT_EQ(wstr1, wstr2);
4903
4904 // Compares an std::wstring to a const wchar_t* that has identical
4905 // content.
4906 const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
4907 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
4908
4909 // Compares an std::wstring to a const wchar_t* that has different
4910 // content.
4911 const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
4912 EXPECT_NONFATAL_FAILURE({ // NOLINT
4913 EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
4914 }, "kTestX8120");
4915
4916 // Compares two std::wstrings that have different contents, one of
4917 // which having a NUL character in the middle.
4918 ::std::wstring wstr3(wstr1);
4919 wstr3.at(2) = L'\0';
4920 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
4921 "wstr3");
4922
4923 // Compares a wchar_t* to an std::wstring that has different
4924 // content.
4925 EXPECT_FATAL_FAILURE({ // NOLINT
4926 ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
4927 }, "");
4928 }
4929
4930 #endif // GTEST_HAS_STD_WSTRING
4931
4932 // Tests using char pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,CharPointer)4933 TEST(EqAssertionTest, CharPointer) {
4934 char* const p0 = nullptr;
4935 // Only way to get the Nokia compiler to compile the cast
4936 // is to have a separate void* variable first. Putting
4937 // the two casts on the same line doesn't work, neither does
4938 // a direct C-style to char*.
4939 void* pv1 = (void*)0x1234; // NOLINT
4940 void* pv2 = (void*)0xABC0; // NOLINT
4941 char* const p1 = reinterpret_cast<char*>(pv1);
4942 char* const p2 = reinterpret_cast<char*>(pv2);
4943 ASSERT_EQ(p1, p1);
4944
4945 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4946 " p2\n Which is:");
4947 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4948 " p2\n Which is:");
4949 EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
4950 reinterpret_cast<char*>(0xABC0)),
4951 "ABC0");
4952 }
4953
4954 // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,WideCharPointer)4955 TEST(EqAssertionTest, WideCharPointer) {
4956 wchar_t* const p0 = nullptr;
4957 // Only way to get the Nokia compiler to compile the cast
4958 // is to have a separate void* variable first. Putting
4959 // the two casts on the same line doesn't work, neither does
4960 // a direct C-style to char*.
4961 void* pv1 = (void*)0x1234; // NOLINT
4962 void* pv2 = (void*)0xABC0; // NOLINT
4963 wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
4964 wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
4965 EXPECT_EQ(p0, p0);
4966
4967 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
4968 " p2\n Which is:");
4969 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
4970 " p2\n Which is:");
4971 void* pv3 = (void*)0x1234; // NOLINT
4972 void* pv4 = (void*)0xABC0; // NOLINT
4973 const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
4974 const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
4975 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
4976 "p4");
4977 }
4978
4979 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest,OtherPointer)4980 TEST(EqAssertionTest, OtherPointer) {
4981 ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));
4982 EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),
4983 reinterpret_cast<const int*>(0x1234)),
4984 "0x1234");
4985 }
4986
4987 // A class that supports binary comparison operators but not streaming.
4988 class UnprintableChar {
4989 public:
UnprintableChar(char ch)4990 explicit UnprintableChar(char ch) : char_(ch) {}
4991
operator ==(const UnprintableChar & rhs) const4992 bool operator==(const UnprintableChar& rhs) const {
4993 return char_ == rhs.char_;
4994 }
operator !=(const UnprintableChar & rhs) const4995 bool operator!=(const UnprintableChar& rhs) const {
4996 return char_ != rhs.char_;
4997 }
operator <(const UnprintableChar & rhs) const4998 bool operator<(const UnprintableChar& rhs) const {
4999 return char_ < rhs.char_;
5000 }
operator <=(const UnprintableChar & rhs) const5001 bool operator<=(const UnprintableChar& rhs) const {
5002 return char_ <= rhs.char_;
5003 }
operator >(const UnprintableChar & rhs) const5004 bool operator>(const UnprintableChar& rhs) const {
5005 return char_ > rhs.char_;
5006 }
operator >=(const UnprintableChar & rhs) const5007 bool operator>=(const UnprintableChar& rhs) const {
5008 return char_ >= rhs.char_;
5009 }
5010
5011 private:
5012 char char_;
5013 };
5014
5015 // Tests that ASSERT_EQ() and friends don't require the arguments to
5016 // be printable.
TEST(ComparisonAssertionTest,AcceptsUnprintableArgs)5017 TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
5018 const UnprintableChar x('x'), y('y');
5019 ASSERT_EQ(x, x);
5020 EXPECT_NE(x, y);
5021 ASSERT_LT(x, y);
5022 EXPECT_LE(x, y);
5023 ASSERT_GT(y, x);
5024 EXPECT_GE(x, x);
5025
5026 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
5027 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
5028 EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
5029 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
5030 EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
5031
5032 // Code tested by EXPECT_FATAL_FAILURE cannot reference local
5033 // variables, so we have to write UnprintableChar('x') instead of x.
5034 #ifndef __BORLANDC__
5035 // ICE's in C++Builder.
5036 EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
5037 "1-byte object <78>");
5038 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
5039 "1-byte object <78>");
5040 #endif
5041 EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
5042 "1-byte object <79>");
5043 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
5044 "1-byte object <78>");
5045 EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
5046 "1-byte object <79>");
5047 }
5048
5049 // Tests the FRIEND_TEST macro.
5050
5051 // This class has a private member we want to test. We will test it
5052 // both in a TEST and in a TEST_F.
5053 class Foo {
5054 public:
Foo()5055 Foo() {}
5056
5057 private:
Bar() const5058 int Bar() const { return 1; }
5059
5060 // Declares the friend tests that can access the private member
5061 // Bar().
5062 FRIEND_TEST(FRIEND_TEST_Test, TEST);
5063 FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
5064 };
5065
5066 // Tests that the FRIEND_TEST declaration allows a TEST to access a
5067 // class's private members. This should compile.
TEST(FRIEND_TEST_Test,TEST)5068 TEST(FRIEND_TEST_Test, TEST) {
5069 ASSERT_EQ(1, Foo().Bar());
5070 }
5071
5072 // The fixture needed to test using FRIEND_TEST with TEST_F.
5073 class FRIEND_TEST_Test2 : public Test {
5074 protected:
5075 Foo foo;
5076 };
5077
5078 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
5079 // class's private members. This should compile.
TEST_F(FRIEND_TEST_Test2,TEST_F)5080 TEST_F(FRIEND_TEST_Test2, TEST_F) {
5081 ASSERT_EQ(1, foo.Bar());
5082 }
5083
5084 // Tests the life cycle of Test objects.
5085
5086 // The test fixture for testing the life cycle of Test objects.
5087 //
5088 // This class counts the number of live test objects that uses this
5089 // fixture.
5090 class TestLifeCycleTest : public Test {
5091 protected:
5092 // Constructor. Increments the number of test objects that uses
5093 // this fixture.
TestLifeCycleTest()5094 TestLifeCycleTest() { count_++; }
5095
5096 // Destructor. Decrements the number of test objects that uses this
5097 // fixture.
~TestLifeCycleTest()5098 ~TestLifeCycleTest() override { count_--; }
5099
5100 // Returns the number of live test objects that uses this fixture.
count() const5101 int count() const { return count_; }
5102
5103 private:
5104 static int count_;
5105 };
5106
5107 int TestLifeCycleTest::count_ = 0;
5108
5109 // Tests the life cycle of test objects.
TEST_F(TestLifeCycleTest,Test1)5110 TEST_F(TestLifeCycleTest, Test1) {
5111 // There should be only one test object in this test case that's
5112 // currently alive.
5113 ASSERT_EQ(1, count());
5114 }
5115
5116 // Tests the life cycle of test objects.
TEST_F(TestLifeCycleTest,Test2)5117 TEST_F(TestLifeCycleTest, Test2) {
5118 // After Test1 is done and Test2 is started, there should still be
5119 // only one live test object, as the object for Test1 should've been
5120 // deleted.
5121 ASSERT_EQ(1, count());
5122 }
5123
5124 } // namespace
5125
5126 // Tests that the copy constructor works when it is NOT optimized away by
5127 // the compiler.
TEST(AssertionResultTest,CopyConstructorWorksWhenNotOptimied)5128 TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
5129 // Checks that the copy constructor doesn't try to dereference NULL pointers
5130 // in the source object.
5131 AssertionResult r1 = AssertionSuccess();
5132 AssertionResult r2 = r1;
5133 // The following line is added to prevent the compiler from optimizing
5134 // away the constructor call.
5135 r1 << "abc";
5136
5137 AssertionResult r3 = r1;
5138 EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
5139 EXPECT_STREQ("abc", r1.message());
5140 }
5141
5142 // Tests that AssertionSuccess and AssertionFailure construct
5143 // AssertionResult objects as expected.
TEST(AssertionResultTest,ConstructionWorks)5144 TEST(AssertionResultTest, ConstructionWorks) {
5145 AssertionResult r1 = AssertionSuccess();
5146 EXPECT_TRUE(r1);
5147 EXPECT_STREQ("", r1.message());
5148
5149 AssertionResult r2 = AssertionSuccess() << "abc";
5150 EXPECT_TRUE(r2);
5151 EXPECT_STREQ("abc", r2.message());
5152
5153 AssertionResult r3 = AssertionFailure();
5154 EXPECT_FALSE(r3);
5155 EXPECT_STREQ("", r3.message());
5156
5157 AssertionResult r4 = AssertionFailure() << "def";
5158 EXPECT_FALSE(r4);
5159 EXPECT_STREQ("def", r4.message());
5160
5161 AssertionResult r5 = AssertionFailure(Message() << "ghi");
5162 EXPECT_FALSE(r5);
5163 EXPECT_STREQ("ghi", r5.message());
5164 }
5165
5166 // Tests that the negation flips the predicate result but keeps the message.
TEST(AssertionResultTest,NegationWorks)5167 TEST(AssertionResultTest, NegationWorks) {
5168 AssertionResult r1 = AssertionSuccess() << "abc";
5169 EXPECT_FALSE(!r1);
5170 EXPECT_STREQ("abc", (!r1).message());
5171
5172 AssertionResult r2 = AssertionFailure() << "def";
5173 EXPECT_TRUE(!r2);
5174 EXPECT_STREQ("def", (!r2).message());
5175 }
5176
TEST(AssertionResultTest,StreamingWorks)5177 TEST(AssertionResultTest, StreamingWorks) {
5178 AssertionResult r = AssertionSuccess();
5179 r << "abc" << 'd' << 0 << true;
5180 EXPECT_STREQ("abcd0true", r.message());
5181 }
5182
TEST(AssertionResultTest,CanStreamOstreamManipulators)5183 TEST(AssertionResultTest, CanStreamOstreamManipulators) {
5184 AssertionResult r = AssertionSuccess();
5185 r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
5186 EXPECT_STREQ("Data\n\\0Will be visible", r.message());
5187 }
5188
5189 // The next test uses explicit conversion operators
5190
TEST(AssertionResultTest,ConstructibleFromContextuallyConvertibleToBool)5191 TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
5192 struct ExplicitlyConvertibleToBool {
5193 explicit operator bool() const { return value; }
5194 bool value;
5195 };
5196 ExplicitlyConvertibleToBool v1 = {false};
5197 ExplicitlyConvertibleToBool v2 = {true};
5198 EXPECT_FALSE(v1);
5199 EXPECT_TRUE(v2);
5200 }
5201
5202 struct ConvertibleToAssertionResult {
operator AssertionResultConvertibleToAssertionResult5203 operator AssertionResult() const { return AssertionResult(true); }
5204 };
5205
TEST(AssertionResultTest,ConstructibleFromImplicitlyConvertible)5206 TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
5207 ConvertibleToAssertionResult obj;
5208 EXPECT_TRUE(obj);
5209 }
5210
5211 // Tests streaming a user type whose definition and operator << are
5212 // both in the global namespace.
5213 class Base {
5214 public:
Base(int an_x)5215 explicit Base(int an_x) : x_(an_x) {}
x() const5216 int x() const { return x_; }
5217 private:
5218 int x_;
5219 };
operator <<(std::ostream & os,const Base & val)5220 std::ostream& operator<<(std::ostream& os,
5221 const Base& val) {
5222 return os << val.x();
5223 }
operator <<(std::ostream & os,const Base * pointer)5224 std::ostream& operator<<(std::ostream& os,
5225 const Base* pointer) {
5226 return os << "(" << pointer->x() << ")";
5227 }
5228
TEST(MessageTest,CanStreamUserTypeInGlobalNameSpace)5229 TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
5230 Message msg;
5231 Base a(1);
5232
5233 msg << a << &a; // Uses ::operator<<.
5234 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5235 }
5236
5237 // Tests streaming a user type whose definition and operator<< are
5238 // both in an unnamed namespace.
5239 namespace {
5240 class MyTypeInUnnamedNameSpace : public Base {
5241 public:
MyTypeInUnnamedNameSpace(int an_x)5242 explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
5243 };
operator <<(std::ostream & os,const MyTypeInUnnamedNameSpace & val)5244 std::ostream& operator<<(std::ostream& os,
5245 const MyTypeInUnnamedNameSpace& val) {
5246 return os << val.x();
5247 }
operator <<(std::ostream & os,const MyTypeInUnnamedNameSpace * pointer)5248 std::ostream& operator<<(std::ostream& os,
5249 const MyTypeInUnnamedNameSpace* pointer) {
5250 return os << "(" << pointer->x() << ")";
5251 }
5252 } // namespace
5253
TEST(MessageTest,CanStreamUserTypeInUnnamedNameSpace)5254 TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
5255 Message msg;
5256 MyTypeInUnnamedNameSpace a(1);
5257
5258 msg << a << &a; // Uses <unnamed_namespace>::operator<<.
5259 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5260 }
5261
5262 // Tests streaming a user type whose definition and operator<< are
5263 // both in a user namespace.
5264 namespace namespace1 {
5265 class MyTypeInNameSpace1 : public Base {
5266 public:
MyTypeInNameSpace1(int an_x)5267 explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
5268 };
operator <<(std::ostream & os,const MyTypeInNameSpace1 & val)5269 std::ostream& operator<<(std::ostream& os,
5270 const MyTypeInNameSpace1& val) {
5271 return os << val.x();
5272 }
operator <<(std::ostream & os,const MyTypeInNameSpace1 * pointer)5273 std::ostream& operator<<(std::ostream& os,
5274 const MyTypeInNameSpace1* pointer) {
5275 return os << "(" << pointer->x() << ")";
5276 }
5277 } // namespace namespace1
5278
TEST(MessageTest,CanStreamUserTypeInUserNameSpace)5279 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
5280 Message msg;
5281 namespace1::MyTypeInNameSpace1 a(1);
5282
5283 msg << a << &a; // Uses namespace1::operator<<.
5284 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5285 }
5286
5287 // Tests streaming a user type whose definition is in a user namespace
5288 // but whose operator<< is in the global namespace.
5289 namespace namespace2 {
5290 class MyTypeInNameSpace2 : public ::Base {
5291 public:
MyTypeInNameSpace2(int an_x)5292 explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
5293 };
5294 } // namespace namespace2
operator <<(std::ostream & os,const namespace2::MyTypeInNameSpace2 & val)5295 std::ostream& operator<<(std::ostream& os,
5296 const namespace2::MyTypeInNameSpace2& val) {
5297 return os << val.x();
5298 }
operator <<(std::ostream & os,const namespace2::MyTypeInNameSpace2 * pointer)5299 std::ostream& operator<<(std::ostream& os,
5300 const namespace2::MyTypeInNameSpace2* pointer) {
5301 return os << "(" << pointer->x() << ")";
5302 }
5303
TEST(MessageTest,CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal)5304 TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
5305 Message msg;
5306 namespace2::MyTypeInNameSpace2 a(1);
5307
5308 msg << a << &a; // Uses ::operator<<.
5309 EXPECT_STREQ("1(1)", msg.GetString().c_str());
5310 }
5311
5312 // Tests streaming NULL pointers to testing::Message.
TEST(MessageTest,NullPointers)5313 TEST(MessageTest, NullPointers) {
5314 Message msg;
5315 char* const p1 = nullptr;
5316 unsigned char* const p2 = nullptr;
5317 int* p3 = nullptr;
5318 double* p4 = nullptr;
5319 bool* p5 = nullptr;
5320 Message* p6 = nullptr;
5321
5322 msg << p1 << p2 << p3 << p4 << p5 << p6;
5323 ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
5324 msg.GetString().c_str());
5325 }
5326
5327 // Tests streaming wide strings to testing::Message.
TEST(MessageTest,WideStrings)5328 TEST(MessageTest, WideStrings) {
5329 // Streams a NULL of type const wchar_t*.
5330 const wchar_t* const_wstr = nullptr;
5331 EXPECT_STREQ("(null)",
5332 (Message() << const_wstr).GetString().c_str());
5333
5334 // Streams a NULL of type wchar_t*.
5335 wchar_t* wstr = nullptr;
5336 EXPECT_STREQ("(null)",
5337 (Message() << wstr).GetString().c_str());
5338
5339 // Streams a non-NULL of type const wchar_t*.
5340 const_wstr = L"abc\x8119";
5341 EXPECT_STREQ("abc\xe8\x84\x99",
5342 (Message() << const_wstr).GetString().c_str());
5343
5344 // Streams a non-NULL of type wchar_t*.
5345 wstr = const_cast<wchar_t*>(const_wstr);
5346 EXPECT_STREQ("abc\xe8\x84\x99",
5347 (Message() << wstr).GetString().c_str());
5348 }
5349
5350
5351 // This line tests that we can define tests in the testing namespace.
5352 namespace testing {
5353
5354 // Tests the TestInfo class.
5355
5356 class TestInfoTest : public Test {
5357 protected:
GetTestInfo(const char * test_name)5358 static const TestInfo* GetTestInfo(const char* test_name) {
5359 const TestSuite* const test_suite =
5360 GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr);
5361
5362 for (int i = 0; i < test_suite->total_test_count(); ++i) {
5363 const TestInfo* const test_info = test_suite->GetTestInfo(i);
5364 if (strcmp(test_name, test_info->name()) == 0)
5365 return test_info;
5366 }
5367 return nullptr;
5368 }
5369
GetTestResult(const TestInfo * test_info)5370 static const TestResult* GetTestResult(
5371 const TestInfo* test_info) {
5372 return test_info->result();
5373 }
5374 };
5375
5376 // Tests TestInfo::test_case_name() and TestInfo::name().
TEST_F(TestInfoTest,Names)5377 TEST_F(TestInfoTest, Names) {
5378 const TestInfo* const test_info = GetTestInfo("Names");
5379
5380 ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
5381 ASSERT_STREQ("Names", test_info->name());
5382 }
5383
5384 // Tests TestInfo::result().
TEST_F(TestInfoTest,result)5385 TEST_F(TestInfoTest, result) {
5386 const TestInfo* const test_info = GetTestInfo("result");
5387
5388 // Initially, there is no TestPartResult for this test.
5389 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5390
5391 // After the previous assertion, there is still none.
5392 ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
5393 }
5394
5395 #define VERIFY_CODE_LOCATION \
5396 const int expected_line = __LINE__ - 1; \
5397 const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
5398 ASSERT_TRUE(test_info); \
5399 EXPECT_STREQ(__FILE__, test_info->file()); \
5400 EXPECT_EQ(expected_line, test_info->line())
5401
TEST(CodeLocationForTEST,Verify)5402 TEST(CodeLocationForTEST, Verify) {
5403 VERIFY_CODE_LOCATION;
5404 }
5405
5406 class CodeLocationForTESTF : public Test {
5407 };
5408
TEST_F(CodeLocationForTESTF,Verify)5409 TEST_F(CodeLocationForTESTF, Verify) {
5410 VERIFY_CODE_LOCATION;
5411 }
5412
5413 class CodeLocationForTESTP : public TestWithParam<int> {
5414 };
5415
TEST_P(CodeLocationForTESTP,Verify)5416 TEST_P(CodeLocationForTESTP, Verify) {
5417 VERIFY_CODE_LOCATION;
5418 }
5419
5420 INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
5421
5422 template <typename T>
5423 class CodeLocationForTYPEDTEST : public Test {
5424 };
5425
5426 TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);
5427
TYPED_TEST(CodeLocationForTYPEDTEST,Verify)5428 TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
5429 VERIFY_CODE_LOCATION;
5430 }
5431
5432 template <typename T>
5433 class CodeLocationForTYPEDTESTP : public Test {
5434 };
5435
5436 TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
5437
TYPED_TEST_P(CodeLocationForTYPEDTESTP,Verify)5438 TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
5439 VERIFY_CODE_LOCATION;
5440 }
5441
5442 REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
5443
5444 INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
5445
5446 #undef VERIFY_CODE_LOCATION
5447
5448 // Tests setting up and tearing down a test case.
5449 // Legacy API is deprecated but still available
5450 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5451 class SetUpTestCaseTest : public Test {
5452 protected:
5453 // This will be called once before the first test in this test case
5454 // is run.
SetUpTestCase()5455 static void SetUpTestCase() {
5456 printf("Setting up the test case . . .\n");
5457
5458 // Initializes some shared resource. In this simple example, we
5459 // just create a C string. More complex stuff can be done if
5460 // desired.
5461 shared_resource_ = "123";
5462
5463 // Increments the number of test cases that have been set up.
5464 counter_++;
5465
5466 // SetUpTestCase() should be called only once.
5467 EXPECT_EQ(1, counter_);
5468 }
5469
5470 // This will be called once after the last test in this test case is
5471 // run.
TearDownTestCase()5472 static void TearDownTestCase() {
5473 printf("Tearing down the test case . . .\n");
5474
5475 // Decrements the number of test cases that have been set up.
5476 counter_--;
5477
5478 // TearDownTestCase() should be called only once.
5479 EXPECT_EQ(0, counter_);
5480
5481 // Cleans up the shared resource.
5482 shared_resource_ = nullptr;
5483 }
5484
5485 // This will be called before each test in this test case.
SetUp()5486 void SetUp() override {
5487 // SetUpTestCase() should be called only once, so counter_ should
5488 // always be 1.
5489 EXPECT_EQ(1, counter_);
5490 }
5491
5492 // Number of test cases that have been set up.
5493 static int counter_;
5494
5495 // Some resource to be shared by all tests in this test case.
5496 static const char* shared_resource_;
5497 };
5498
5499 int SetUpTestCaseTest::counter_ = 0;
5500 const char* SetUpTestCaseTest::shared_resource_ = nullptr;
5501
5502 // A test that uses the shared resource.
TEST_F(SetUpTestCaseTest,Test1)5503 TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
5504
5505 // Another test that uses the shared resource.
TEST_F(SetUpTestCaseTest,Test2)5506 TEST_F(SetUpTestCaseTest, Test2) {
5507 EXPECT_STREQ("123", shared_resource_);
5508 }
5509 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5510
5511 // Tests SetupTestSuite/TearDown TestSuite
5512 class SetUpTestSuiteTest : public Test {
5513 protected:
5514 // This will be called once before the first test in this test case
5515 // is run.
SetUpTestSuite()5516 static void SetUpTestSuite() {
5517 printf("Setting up the test suite . . .\n");
5518
5519 // Initializes some shared resource. In this simple example, we
5520 // just create a C string. More complex stuff can be done if
5521 // desired.
5522 shared_resource_ = "123";
5523
5524 // Increments the number of test cases that have been set up.
5525 counter_++;
5526
5527 // SetUpTestSuite() should be called only once.
5528 EXPECT_EQ(1, counter_);
5529 }
5530
5531 // This will be called once after the last test in this test case is
5532 // run.
TearDownTestSuite()5533 static void TearDownTestSuite() {
5534 printf("Tearing down the test suite . . .\n");
5535
5536 // Decrements the number of test suites that have been set up.
5537 counter_--;
5538
5539 // TearDownTestSuite() should be called only once.
5540 EXPECT_EQ(0, counter_);
5541
5542 // Cleans up the shared resource.
5543 shared_resource_ = nullptr;
5544 }
5545
5546 // This will be called before each test in this test case.
SetUp()5547 void SetUp() override {
5548 // SetUpTestSuite() should be called only once, so counter_ should
5549 // always be 1.
5550 EXPECT_EQ(1, counter_);
5551 }
5552
5553 // Number of test suites that have been set up.
5554 static int counter_;
5555
5556 // Some resource to be shared by all tests in this test case.
5557 static const char* shared_resource_;
5558 };
5559
5560 int SetUpTestSuiteTest::counter_ = 0;
5561 const char* SetUpTestSuiteTest::shared_resource_ = nullptr;
5562
5563 // A test that uses the shared resource.
TEST_F(SetUpTestSuiteTest,TestSetupTestSuite1)5564 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) {
5565 EXPECT_STRNE(nullptr, shared_resource_);
5566 }
5567
5568 // Another test that uses the shared resource.
TEST_F(SetUpTestSuiteTest,TestSetupTestSuite2)5569 TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
5570 EXPECT_STREQ("123", shared_resource_);
5571 }
5572
5573 // The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.
5574
5575 // The Flags struct stores a copy of all Google Test flags.
5576 struct Flags {
5577 // Constructs a Flags struct where each flag has its default value.
Flagstesting::Flags5578 Flags()
5579 : also_run_disabled_tests(false),
5580 break_on_failure(false),
5581 catch_exceptions(false),
5582 death_test_use_fork(false),
5583 fail_fast(false),
5584 filter(""),
5585 list_tests(false),
5586 output(""),
5587 brief(false),
5588 print_time(true),
5589 random_seed(0),
5590 repeat(1),
5591 shuffle(false),
5592 stack_trace_depth(kMaxStackTraceDepth),
5593 stream_result_to(""),
5594 throw_on_failure(false) {}
5595
5596 // Factory methods.
5597
5598 // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
5599 // the given value.
AlsoRunDisabledTeststesting::Flags5600 static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
5601 Flags flags;
5602 flags.also_run_disabled_tests = also_run_disabled_tests;
5603 return flags;
5604 }
5605
5606 // Creates a Flags struct where the gtest_break_on_failure flag has
5607 // the given value.
BreakOnFailuretesting::Flags5608 static Flags BreakOnFailure(bool break_on_failure) {
5609 Flags flags;
5610 flags.break_on_failure = break_on_failure;
5611 return flags;
5612 }
5613
5614 // Creates a Flags struct where the gtest_catch_exceptions flag has
5615 // the given value.
CatchExceptionstesting::Flags5616 static Flags CatchExceptions(bool catch_exceptions) {
5617 Flags flags;
5618 flags.catch_exceptions = catch_exceptions;
5619 return flags;
5620 }
5621
5622 // Creates a Flags struct where the gtest_death_test_use_fork flag has
5623 // the given value.
DeathTestUseForktesting::Flags5624 static Flags DeathTestUseFork(bool death_test_use_fork) {
5625 Flags flags;
5626 flags.death_test_use_fork = death_test_use_fork;
5627 return flags;
5628 }
5629
5630 // Creates a Flags struct where the gtest_fail_fast flag has
5631 // the given value.
FailFasttesting::Flags5632 static Flags FailFast(bool fail_fast) {
5633 Flags flags;
5634 flags.fail_fast = fail_fast;
5635 return flags;
5636 }
5637
5638 // Creates a Flags struct where the gtest_filter flag has the given
5639 // value.
Filtertesting::Flags5640 static Flags Filter(const char* filter) {
5641 Flags flags;
5642 flags.filter = filter;
5643 return flags;
5644 }
5645
5646 // Creates a Flags struct where the gtest_list_tests flag has the
5647 // given value.
ListTeststesting::Flags5648 static Flags ListTests(bool list_tests) {
5649 Flags flags;
5650 flags.list_tests = list_tests;
5651 return flags;
5652 }
5653
5654 // Creates a Flags struct where the gtest_output flag has the given
5655 // value.
Outputtesting::Flags5656 static Flags Output(const char* output) {
5657 Flags flags;
5658 flags.output = output;
5659 return flags;
5660 }
5661
5662 // Creates a Flags struct where the gtest_brief flag has the given
5663 // value.
Brieftesting::Flags5664 static Flags Brief(bool brief) {
5665 Flags flags;
5666 flags.brief = brief;
5667 return flags;
5668 }
5669
5670 // Creates a Flags struct where the gtest_print_time flag has the given
5671 // value.
PrintTimetesting::Flags5672 static Flags PrintTime(bool print_time) {
5673 Flags flags;
5674 flags.print_time = print_time;
5675 return flags;
5676 }
5677
5678 // Creates a Flags struct where the gtest_random_seed flag has the given
5679 // value.
RandomSeedtesting::Flags5680 static Flags RandomSeed(int32_t random_seed) {
5681 Flags flags;
5682 flags.random_seed = random_seed;
5683 return flags;
5684 }
5685
5686 // Creates a Flags struct where the gtest_repeat flag has the given
5687 // value.
Repeattesting::Flags5688 static Flags Repeat(int32_t repeat) {
5689 Flags flags;
5690 flags.repeat = repeat;
5691 return flags;
5692 }
5693
5694 // Creates a Flags struct where the gtest_shuffle flag has the given
5695 // value.
Shuffletesting::Flags5696 static Flags Shuffle(bool shuffle) {
5697 Flags flags;
5698 flags.shuffle = shuffle;
5699 return flags;
5700 }
5701
5702 // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
5703 // the given value.
StackTraceDepthtesting::Flags5704 static Flags StackTraceDepth(int32_t stack_trace_depth) {
5705 Flags flags;
5706 flags.stack_trace_depth = stack_trace_depth;
5707 return flags;
5708 }
5709
5710 // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
5711 // the given value.
StreamResultTotesting::Flags5712 static Flags StreamResultTo(const char* stream_result_to) {
5713 Flags flags;
5714 flags.stream_result_to = stream_result_to;
5715 return flags;
5716 }
5717
5718 // Creates a Flags struct where the gtest_throw_on_failure flag has
5719 // the given value.
ThrowOnFailuretesting::Flags5720 static Flags ThrowOnFailure(bool throw_on_failure) {
5721 Flags flags;
5722 flags.throw_on_failure = throw_on_failure;
5723 return flags;
5724 }
5725
5726 // These fields store the flag values.
5727 bool also_run_disabled_tests;
5728 bool break_on_failure;
5729 bool catch_exceptions;
5730 bool death_test_use_fork;
5731 bool fail_fast;
5732 const char* filter;
5733 bool list_tests;
5734 const char* output;
5735 bool brief;
5736 bool print_time;
5737 int32_t random_seed;
5738 int32_t repeat;
5739 bool shuffle;
5740 int32_t stack_trace_depth;
5741 const char* stream_result_to;
5742 bool throw_on_failure;
5743 };
5744
5745 // Fixture for testing ParseGoogleTestFlagsOnly().
5746 class ParseFlagsTest : public Test {
5747 protected:
5748 // Clears the flags before each test.
SetUp()5749 void SetUp() override {
5750 GTEST_FLAG(also_run_disabled_tests) = false;
5751 GTEST_FLAG(break_on_failure) = false;
5752 GTEST_FLAG(catch_exceptions) = false;
5753 GTEST_FLAG(death_test_use_fork) = false;
5754 GTEST_FLAG(fail_fast) = false;
5755 GTEST_FLAG(filter) = "";
5756 GTEST_FLAG(list_tests) = false;
5757 GTEST_FLAG(output) = "";
5758 GTEST_FLAG(brief) = false;
5759 GTEST_FLAG(print_time) = true;
5760 GTEST_FLAG(random_seed) = 0;
5761 GTEST_FLAG(repeat) = 1;
5762 GTEST_FLAG(shuffle) = false;
5763 GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
5764 GTEST_FLAG(stream_result_to) = "";
5765 GTEST_FLAG(throw_on_failure) = false;
5766 }
5767
5768 // Asserts that two narrow or wide string arrays are equal.
5769 template <typename CharType>
AssertStringArrayEq(int size1,CharType ** array1,int size2,CharType ** array2)5770 static void AssertStringArrayEq(int size1, CharType** array1, int size2,
5771 CharType** array2) {
5772 ASSERT_EQ(size1, size2) << " Array sizes different.";
5773
5774 for (int i = 0; i != size1; i++) {
5775 ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
5776 }
5777 }
5778
5779 // Verifies that the flag values match the expected values.
CheckFlags(const Flags & expected)5780 static void CheckFlags(const Flags& expected) {
5781 EXPECT_EQ(expected.also_run_disabled_tests,
5782 GTEST_FLAG(also_run_disabled_tests));
5783 EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
5784 EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
5785 EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
5786 EXPECT_EQ(expected.fail_fast, GTEST_FLAG(fail_fast));
5787 EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
5788 EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
5789 EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
5790 EXPECT_EQ(expected.brief, GTEST_FLAG(brief));
5791 EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
5792 EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
5793 EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
5794 EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
5795 EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
5796 EXPECT_STREQ(expected.stream_result_to,
5797 GTEST_FLAG(stream_result_to).c_str());
5798 EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
5799 }
5800
5801 // Parses a command line (specified by argc1 and argv1), then
5802 // verifies that the flag values are expected and that the
5803 // recognized flags are removed from the command line.
5804 template <typename CharType>
TestParsingFlags(int argc1,const CharType ** argv1,int argc2,const CharType ** argv2,const Flags & expected,bool should_print_help)5805 static void TestParsingFlags(int argc1, const CharType** argv1,
5806 int argc2, const CharType** argv2,
5807 const Flags& expected, bool should_print_help) {
5808 const bool saved_help_flag = ::testing::internal::g_help_flag;
5809 ::testing::internal::g_help_flag = false;
5810
5811 # if GTEST_HAS_STREAM_REDIRECTION
5812 CaptureStdout();
5813 # endif
5814
5815 // Parses the command line.
5816 internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
5817
5818 # if GTEST_HAS_STREAM_REDIRECTION
5819 const std::string captured_stdout = GetCapturedStdout();
5820 # endif
5821
5822 // Verifies the flag values.
5823 CheckFlags(expected);
5824
5825 // Verifies that the recognized flags are removed from the command
5826 // line.
5827 AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
5828
5829 // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
5830 // help message for the flags it recognizes.
5831 EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
5832
5833 # if GTEST_HAS_STREAM_REDIRECTION
5834 const char* const expected_help_fragment =
5835 "This program contains tests written using";
5836 if (should_print_help) {
5837 EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
5838 } else {
5839 EXPECT_PRED_FORMAT2(IsNotSubstring,
5840 expected_help_fragment, captured_stdout);
5841 }
5842 # endif // GTEST_HAS_STREAM_REDIRECTION
5843
5844 ::testing::internal::g_help_flag = saved_help_flag;
5845 }
5846
5847 // This macro wraps TestParsingFlags s.t. the user doesn't need
5848 // to specify the array sizes.
5849
5850 # define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
5851 TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
5852 sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
5853 expected, should_print_help)
5854 };
5855
5856 // Tests parsing an empty command line.
TEST_F(ParseFlagsTest,Empty)5857 TEST_F(ParseFlagsTest, Empty) {
5858 const char* argv[] = {nullptr};
5859
5860 const char* argv2[] = {nullptr};
5861
5862 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5863 }
5864
5865 // Tests parsing a command line that has no flag.
TEST_F(ParseFlagsTest,NoFlag)5866 TEST_F(ParseFlagsTest, NoFlag) {
5867 const char* argv[] = {"foo.exe", nullptr};
5868
5869 const char* argv2[] = {"foo.exe", nullptr};
5870
5871 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
5872 }
5873
5874 // Tests parsing --gtest_fail_fast.
TEST_F(ParseFlagsTest,FailFast)5875 TEST_F(ParseFlagsTest, FailFast) {
5876 const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
5877
5878 const char* argv2[] = {"foo.exe", nullptr};
5879
5880 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
5881 }
5882
5883 // Tests parsing a bad --gtest_filter flag.
TEST_F(ParseFlagsTest,FilterBad)5884 TEST_F(ParseFlagsTest, FilterBad) {
5885 const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
5886
5887 const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
5888
5889 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
5890 }
5891
5892 // Tests parsing an empty --gtest_filter flag.
TEST_F(ParseFlagsTest,FilterEmpty)5893 TEST_F(ParseFlagsTest, FilterEmpty) {
5894 const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
5895
5896 const char* argv2[] = {"foo.exe", nullptr};
5897
5898 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
5899 }
5900
5901 // Tests parsing a non-empty --gtest_filter flag.
TEST_F(ParseFlagsTest,FilterNonEmpty)5902 TEST_F(ParseFlagsTest, FilterNonEmpty) {
5903 const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr};
5904
5905 const char* argv2[] = {"foo.exe", nullptr};
5906
5907 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
5908 }
5909
5910 // Tests parsing --gtest_break_on_failure.
TEST_F(ParseFlagsTest,BreakOnFailureWithoutValue)5911 TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {
5912 const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr};
5913
5914 const char* argv2[] = {"foo.exe", nullptr};
5915
5916 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5917 }
5918
5919 // Tests parsing --gtest_break_on_failure=0.
TEST_F(ParseFlagsTest,BreakOnFailureFalse_0)5920 TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {
5921 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr};
5922
5923 const char* argv2[] = {"foo.exe", nullptr};
5924
5925 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5926 }
5927
5928 // Tests parsing --gtest_break_on_failure=f.
TEST_F(ParseFlagsTest,BreakOnFailureFalse_f)5929 TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {
5930 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr};
5931
5932 const char* argv2[] = {"foo.exe", nullptr};
5933
5934 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5935 }
5936
5937 // Tests parsing --gtest_break_on_failure=F.
TEST_F(ParseFlagsTest,BreakOnFailureFalse_F)5938 TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {
5939 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr};
5940
5941 const char* argv2[] = {"foo.exe", nullptr};
5942
5943 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
5944 }
5945
5946 // Tests parsing a --gtest_break_on_failure flag that has a "true"
5947 // definition.
TEST_F(ParseFlagsTest,BreakOnFailureTrue)5948 TEST_F(ParseFlagsTest, BreakOnFailureTrue) {
5949 const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr};
5950
5951 const char* argv2[] = {"foo.exe", nullptr};
5952
5953 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
5954 }
5955
5956 // Tests parsing --gtest_catch_exceptions.
TEST_F(ParseFlagsTest,CatchExceptions)5957 TEST_F(ParseFlagsTest, CatchExceptions) {
5958 const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr};
5959
5960 const char* argv2[] = {"foo.exe", nullptr};
5961
5962 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
5963 }
5964
5965 // Tests parsing --gtest_death_test_use_fork.
TEST_F(ParseFlagsTest,DeathTestUseFork)5966 TEST_F(ParseFlagsTest, DeathTestUseFork) {
5967 const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr};
5968
5969 const char* argv2[] = {"foo.exe", nullptr};
5970
5971 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
5972 }
5973
5974 // Tests having the same flag twice with different values. The
5975 // expected behavior is that the one coming last takes precedence.
TEST_F(ParseFlagsTest,DuplicatedFlags)5976 TEST_F(ParseFlagsTest, DuplicatedFlags) {
5977 const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b",
5978 nullptr};
5979
5980 const char* argv2[] = {"foo.exe", nullptr};
5981
5982 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
5983 }
5984
5985 // Tests having an unrecognized flag on the command line.
TEST_F(ParseFlagsTest,UnrecognizedFlag)5986 TEST_F(ParseFlagsTest, UnrecognizedFlag) {
5987 const char* argv[] = {"foo.exe", "--gtest_break_on_failure",
5988 "bar", // Unrecognized by Google Test.
5989 "--gtest_filter=b", nullptr};
5990
5991 const char* argv2[] = {"foo.exe", "bar", nullptr};
5992
5993 Flags flags;
5994 flags.break_on_failure = true;
5995 flags.filter = "b";
5996 GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
5997 }
5998
5999 // Tests having a --gtest_list_tests flag
TEST_F(ParseFlagsTest,ListTestsFlag)6000 TEST_F(ParseFlagsTest, ListTestsFlag) {
6001 const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr};
6002
6003 const char* argv2[] = {"foo.exe", nullptr};
6004
6005 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
6006 }
6007
6008 // Tests having a --gtest_list_tests flag with a "true" value
TEST_F(ParseFlagsTest,ListTestsTrue)6009 TEST_F(ParseFlagsTest, ListTestsTrue) {
6010 const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr};
6011
6012 const char* argv2[] = {"foo.exe", nullptr};
6013
6014 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
6015 }
6016
6017 // Tests having a --gtest_list_tests flag with a "false" value
TEST_F(ParseFlagsTest,ListTestsFalse)6018 TEST_F(ParseFlagsTest, ListTestsFalse) {
6019 const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr};
6020
6021 const char* argv2[] = {"foo.exe", nullptr};
6022
6023 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6024 }
6025
6026 // Tests parsing --gtest_list_tests=f.
TEST_F(ParseFlagsTest,ListTestsFalse_f)6027 TEST_F(ParseFlagsTest, ListTestsFalse_f) {
6028 const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr};
6029
6030 const char* argv2[] = {"foo.exe", nullptr};
6031
6032 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6033 }
6034
6035 // Tests parsing --gtest_list_tests=F.
TEST_F(ParseFlagsTest,ListTestsFalse_F)6036 TEST_F(ParseFlagsTest, ListTestsFalse_F) {
6037 const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr};
6038
6039 const char* argv2[] = {"foo.exe", nullptr};
6040
6041 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
6042 }
6043
6044 // Tests parsing --gtest_output (invalid).
TEST_F(ParseFlagsTest,OutputEmpty)6045 TEST_F(ParseFlagsTest, OutputEmpty) {
6046 const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
6047
6048 const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
6049
6050 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
6051 }
6052
6053 // Tests parsing --gtest_output=xml
TEST_F(ParseFlagsTest,OutputXml)6054 TEST_F(ParseFlagsTest, OutputXml) {
6055 const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
6056
6057 const char* argv2[] = {"foo.exe", nullptr};
6058
6059 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
6060 }
6061
6062 // Tests parsing --gtest_output=xml:file
TEST_F(ParseFlagsTest,OutputXmlFile)6063 TEST_F(ParseFlagsTest, OutputXmlFile) {
6064 const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr};
6065
6066 const char* argv2[] = {"foo.exe", nullptr};
6067
6068 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
6069 }
6070
6071 // Tests parsing --gtest_output=xml:directory/path/
TEST_F(ParseFlagsTest,OutputXmlDirectory)6072 TEST_F(ParseFlagsTest, OutputXmlDirectory) {
6073 const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/",
6074 nullptr};
6075
6076 const char* argv2[] = {"foo.exe", nullptr};
6077
6078 GTEST_TEST_PARSING_FLAGS_(argv, argv2,
6079 Flags::Output("xml:directory/path/"), false);
6080 }
6081
6082 // Tests having a --gtest_brief flag
TEST_F(ParseFlagsTest,BriefFlag)6083 TEST_F(ParseFlagsTest, BriefFlag) {
6084 const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
6085
6086 const char* argv2[] = {"foo.exe", nullptr};
6087
6088 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
6089 }
6090
6091 // Tests having a --gtest_brief flag with a "true" value
TEST_F(ParseFlagsTest,BriefFlagTrue)6092 TEST_F(ParseFlagsTest, BriefFlagTrue) {
6093 const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
6094
6095 const char* argv2[] = {"foo.exe", nullptr};
6096
6097 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
6098 }
6099
6100 // Tests having a --gtest_brief flag with a "false" value
TEST_F(ParseFlagsTest,BriefFlagFalse)6101 TEST_F(ParseFlagsTest, BriefFlagFalse) {
6102 const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
6103
6104 const char* argv2[] = {"foo.exe", nullptr};
6105
6106 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
6107 }
6108
6109 // Tests having a --gtest_print_time flag
TEST_F(ParseFlagsTest,PrintTimeFlag)6110 TEST_F(ParseFlagsTest, PrintTimeFlag) {
6111 const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
6112
6113 const char* argv2[] = {"foo.exe", nullptr};
6114
6115 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6116 }
6117
6118 // Tests having a --gtest_print_time flag with a "true" value
TEST_F(ParseFlagsTest,PrintTimeTrue)6119 TEST_F(ParseFlagsTest, PrintTimeTrue) {
6120 const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr};
6121
6122 const char* argv2[] = {"foo.exe", nullptr};
6123
6124 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
6125 }
6126
6127 // Tests having a --gtest_print_time flag with a "false" value
TEST_F(ParseFlagsTest,PrintTimeFalse)6128 TEST_F(ParseFlagsTest, PrintTimeFalse) {
6129 const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr};
6130
6131 const char* argv2[] = {"foo.exe", nullptr};
6132
6133 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6134 }
6135
6136 // Tests parsing --gtest_print_time=f.
TEST_F(ParseFlagsTest,PrintTimeFalse_f)6137 TEST_F(ParseFlagsTest, PrintTimeFalse_f) {
6138 const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr};
6139
6140 const char* argv2[] = {"foo.exe", nullptr};
6141
6142 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6143 }
6144
6145 // Tests parsing --gtest_print_time=F.
TEST_F(ParseFlagsTest,PrintTimeFalse_F)6146 TEST_F(ParseFlagsTest, PrintTimeFalse_F) {
6147 const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr};
6148
6149 const char* argv2[] = {"foo.exe", nullptr};
6150
6151 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
6152 }
6153
6154 // Tests parsing --gtest_random_seed=number
TEST_F(ParseFlagsTest,RandomSeed)6155 TEST_F(ParseFlagsTest, RandomSeed) {
6156 const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr};
6157
6158 const char* argv2[] = {"foo.exe", nullptr};
6159
6160 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
6161 }
6162
6163 // Tests parsing --gtest_repeat=number
TEST_F(ParseFlagsTest,Repeat)6164 TEST_F(ParseFlagsTest, Repeat) {
6165 const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr};
6166
6167 const char* argv2[] = {"foo.exe", nullptr};
6168
6169 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
6170 }
6171
6172 // Tests having a --gtest_also_run_disabled_tests flag
TEST_F(ParseFlagsTest,AlsoRunDisabledTestsFlag)6173 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
6174 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
6175
6176 const char* argv2[] = {"foo.exe", nullptr};
6177
6178 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
6179 false);
6180 }
6181
6182 // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
TEST_F(ParseFlagsTest,AlsoRunDisabledTestsTrue)6183 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {
6184 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1",
6185 nullptr};
6186
6187 const char* argv2[] = {"foo.exe", nullptr};
6188
6189 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
6190 false);
6191 }
6192
6193 // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
TEST_F(ParseFlagsTest,AlsoRunDisabledTestsFalse)6194 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {
6195 const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0",
6196 nullptr};
6197
6198 const char* argv2[] = {"foo.exe", nullptr};
6199
6200 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false),
6201 false);
6202 }
6203
6204 // Tests parsing --gtest_shuffle.
TEST_F(ParseFlagsTest,ShuffleWithoutValue)6205 TEST_F(ParseFlagsTest, ShuffleWithoutValue) {
6206 const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr};
6207
6208 const char* argv2[] = {"foo.exe", nullptr};
6209
6210 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6211 }
6212
6213 // Tests parsing --gtest_shuffle=0.
TEST_F(ParseFlagsTest,ShuffleFalse_0)6214 TEST_F(ParseFlagsTest, ShuffleFalse_0) {
6215 const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr};
6216
6217 const char* argv2[] = {"foo.exe", nullptr};
6218
6219 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
6220 }
6221
6222 // Tests parsing a --gtest_shuffle flag that has a "true" definition.
TEST_F(ParseFlagsTest,ShuffleTrue)6223 TEST_F(ParseFlagsTest, ShuffleTrue) {
6224 const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr};
6225
6226 const char* argv2[] = {"foo.exe", nullptr};
6227
6228 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
6229 }
6230
6231 // Tests parsing --gtest_stack_trace_depth=number.
TEST_F(ParseFlagsTest,StackTraceDepth)6232 TEST_F(ParseFlagsTest, StackTraceDepth) {
6233 const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr};
6234
6235 const char* argv2[] = {"foo.exe", nullptr};
6236
6237 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
6238 }
6239
TEST_F(ParseFlagsTest,StreamResultTo)6240 TEST_F(ParseFlagsTest, StreamResultTo) {
6241 const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234",
6242 nullptr};
6243
6244 const char* argv2[] = {"foo.exe", nullptr};
6245
6246 GTEST_TEST_PARSING_FLAGS_(
6247 argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
6248 }
6249
6250 // Tests parsing --gtest_throw_on_failure.
TEST_F(ParseFlagsTest,ThrowOnFailureWithoutValue)6251 TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
6252 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr};
6253
6254 const char* argv2[] = {"foo.exe", nullptr};
6255
6256 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6257 }
6258
6259 // Tests parsing --gtest_throw_on_failure=0.
TEST_F(ParseFlagsTest,ThrowOnFailureFalse_0)6260 TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {
6261 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr};
6262
6263 const char* argv2[] = {"foo.exe", nullptr};
6264
6265 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
6266 }
6267
6268 // Tests parsing a --gtest_throw_on_failure flag that has a "true"
6269 // definition.
TEST_F(ParseFlagsTest,ThrowOnFailureTrue)6270 TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
6271 const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr};
6272
6273 const char* argv2[] = {"foo.exe", nullptr};
6274
6275 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
6276 }
6277
6278 # if GTEST_OS_WINDOWS
6279 // Tests parsing wide strings.
TEST_F(ParseFlagsTest,WideStrings)6280 TEST_F(ParseFlagsTest, WideStrings) {
6281 const wchar_t* argv[] = {
6282 L"foo.exe",
6283 L"--gtest_filter=Foo*",
6284 L"--gtest_list_tests=1",
6285 L"--gtest_break_on_failure",
6286 L"--non_gtest_flag",
6287 NULL
6288 };
6289
6290 const wchar_t* argv2[] = {
6291 L"foo.exe",
6292 L"--non_gtest_flag",
6293 NULL
6294 };
6295
6296 Flags expected_flags;
6297 expected_flags.break_on_failure = true;
6298 expected_flags.filter = "Foo*";
6299 expected_flags.list_tests = true;
6300
6301 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6302 }
6303 # endif // GTEST_OS_WINDOWS
6304
6305 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6306 class FlagfileTest : public ParseFlagsTest {
6307 public:
SetUp()6308 void SetUp() override {
6309 ParseFlagsTest::SetUp();
6310
6311 testdata_path_.Set(internal::FilePath(
6312 testing::TempDir() + internal::GetCurrentExecutableName().string() +
6313 "_flagfile_test"));
6314 testing::internal::posix::RmDir(testdata_path_.c_str());
6315 EXPECT_TRUE(testdata_path_.CreateFolder());
6316 }
6317
TearDown()6318 void TearDown() override {
6319 testing::internal::posix::RmDir(testdata_path_.c_str());
6320 ParseFlagsTest::TearDown();
6321 }
6322
CreateFlagfile(const char * contents)6323 internal::FilePath CreateFlagfile(const char* contents) {
6324 internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
6325 testdata_path_, internal::FilePath("unique"), "txt"));
6326 FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
6327 fprintf(f, "%s", contents);
6328 fclose(f);
6329 return file_path;
6330 }
6331
6332 private:
6333 internal::FilePath testdata_path_;
6334 };
6335
6336 // Tests an empty flagfile.
TEST_F(FlagfileTest,Empty)6337 TEST_F(FlagfileTest, Empty) {
6338 internal::FilePath flagfile_path(CreateFlagfile(""));
6339 std::string flagfile_flag =
6340 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6341
6342 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6343
6344 const char* argv2[] = {"foo.exe", nullptr};
6345
6346 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
6347 }
6348
6349 // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
TEST_F(FlagfileTest,FilterNonEmpty)6350 TEST_F(FlagfileTest, FilterNonEmpty) {
6351 internal::FilePath flagfile_path(CreateFlagfile(
6352 "--" GTEST_FLAG_PREFIX_ "filter=abc"));
6353 std::string flagfile_flag =
6354 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6355
6356 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6357
6358 const char* argv2[] = {"foo.exe", nullptr};
6359
6360 GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
6361 }
6362
6363 // Tests passing several flags via --gtest_flagfile.
TEST_F(FlagfileTest,SeveralFlags)6364 TEST_F(FlagfileTest, SeveralFlags) {
6365 internal::FilePath flagfile_path(CreateFlagfile(
6366 "--" GTEST_FLAG_PREFIX_ "filter=abc\n"
6367 "--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
6368 "--" GTEST_FLAG_PREFIX_ "list_tests"));
6369 std::string flagfile_flag =
6370 std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
6371
6372 const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
6373
6374 const char* argv2[] = {"foo.exe", nullptr};
6375
6376 Flags expected_flags;
6377 expected_flags.break_on_failure = true;
6378 expected_flags.filter = "abc";
6379 expected_flags.list_tests = true;
6380
6381 GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
6382 }
6383 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6384
6385 // Tests current_test_info() in UnitTest.
6386 class CurrentTestInfoTest : public Test {
6387 protected:
6388 // Tests that current_test_info() returns NULL before the first test in
6389 // the test case is run.
SetUpTestSuite()6390 static void SetUpTestSuite() {
6391 // There should be no tests running at this point.
6392 const TestInfo* test_info =
6393 UnitTest::GetInstance()->current_test_info();
6394 EXPECT_TRUE(test_info == nullptr)
6395 << "There should be no tests running at this point.";
6396 }
6397
6398 // Tests that current_test_info() returns NULL after the last test in
6399 // the test case has run.
TearDownTestSuite()6400 static void TearDownTestSuite() {
6401 const TestInfo* test_info =
6402 UnitTest::GetInstance()->current_test_info();
6403 EXPECT_TRUE(test_info == nullptr)
6404 << "There should be no tests running at this point.";
6405 }
6406 };
6407
6408 // Tests that current_test_info() returns TestInfo for currently running
6409 // test by checking the expected test name against the actual one.
TEST_F(CurrentTestInfoTest,WorksForFirstTestInATestSuite)6410 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
6411 const TestInfo* test_info =
6412 UnitTest::GetInstance()->current_test_info();
6413 ASSERT_TRUE(nullptr != test_info)
6414 << "There is a test running so we should have a valid TestInfo.";
6415 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6416 << "Expected the name of the currently running test suite.";
6417 EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
6418 << "Expected the name of the currently running test.";
6419 }
6420
6421 // Tests that current_test_info() returns TestInfo for currently running
6422 // test by checking the expected test name against the actual one. We
6423 // use this test to see that the TestInfo object actually changed from
6424 // the previous invocation.
TEST_F(CurrentTestInfoTest,WorksForSecondTestInATestSuite)6425 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
6426 const TestInfo* test_info =
6427 UnitTest::GetInstance()->current_test_info();
6428 ASSERT_TRUE(nullptr != test_info)
6429 << "There is a test running so we should have a valid TestInfo.";
6430 EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
6431 << "Expected the name of the currently running test suite.";
6432 EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
6433 << "Expected the name of the currently running test.";
6434 }
6435
6436 } // namespace testing
6437
6438
6439 // These two lines test that we can define tests in a namespace that
6440 // has the name "testing" and is nested in another namespace.
6441 namespace my_namespace {
6442 namespace testing {
6443
6444 // Makes sure that TEST knows to use ::testing::Test instead of
6445 // ::my_namespace::testing::Test.
6446 class Test {};
6447
6448 // Makes sure that an assertion knows to use ::testing::Message instead of
6449 // ::my_namespace::testing::Message.
6450 class Message {};
6451
6452 // Makes sure that an assertion knows to use
6453 // ::testing::AssertionResult instead of
6454 // ::my_namespace::testing::AssertionResult.
6455 class AssertionResult {};
6456
6457 // Tests that an assertion that should succeed works as expected.
TEST(NestedTestingNamespaceTest,Success)6458 TEST(NestedTestingNamespaceTest, Success) {
6459 EXPECT_EQ(1, 1) << "This shouldn't fail.";
6460 }
6461
6462 // Tests that an assertion that should fail works as expected.
TEST(NestedTestingNamespaceTest,Failure)6463 TEST(NestedTestingNamespaceTest, Failure) {
6464 EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
6465 "This failure is expected.");
6466 }
6467
6468 } // namespace testing
6469 } // namespace my_namespace
6470
6471 // Tests that one can call superclass SetUp and TearDown methods--
6472 // that is, that they are not private.
6473 // No tests are based on this fixture; the test "passes" if it compiles
6474 // successfully.
6475 class ProtectedFixtureMethodsTest : public Test {
6476 protected:
SetUp()6477 void SetUp() override { Test::SetUp(); }
TearDown()6478 void TearDown() override { Test::TearDown(); }
6479 };
6480
6481 // StreamingAssertionsTest tests the streaming versions of a representative
6482 // sample of assertions.
TEST(StreamingAssertionsTest,Unconditional)6483 TEST(StreamingAssertionsTest, Unconditional) {
6484 SUCCEED() << "expected success";
6485 EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
6486 "expected failure");
6487 EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
6488 "expected failure");
6489 }
6490
6491 #ifdef __BORLANDC__
6492 // Silences warnings: "Condition is always true", "Unreachable code"
6493 # pragma option push -w-ccc -w-rch
6494 #endif
6495
TEST(StreamingAssertionsTest,Truth)6496 TEST(StreamingAssertionsTest, Truth) {
6497 EXPECT_TRUE(true) << "unexpected failure";
6498 ASSERT_TRUE(true) << "unexpected failure";
6499 EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
6500 "expected failure");
6501 EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
6502 "expected failure");
6503 }
6504
TEST(StreamingAssertionsTest,Truth2)6505 TEST(StreamingAssertionsTest, Truth2) {
6506 EXPECT_FALSE(false) << "unexpected failure";
6507 ASSERT_FALSE(false) << "unexpected failure";
6508 EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
6509 "expected failure");
6510 EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
6511 "expected failure");
6512 }
6513
6514 #ifdef __BORLANDC__
6515 // Restores warnings after previous "#pragma option push" suppressed them
6516 # pragma option pop
6517 #endif
6518
TEST(StreamingAssertionsTest,IntegerEquals)6519 TEST(StreamingAssertionsTest, IntegerEquals) {
6520 EXPECT_EQ(1, 1) << "unexpected failure";
6521 ASSERT_EQ(1, 1) << "unexpected failure";
6522 EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
6523 "expected failure");
6524 EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
6525 "expected failure");
6526 }
6527
TEST(StreamingAssertionsTest,IntegerLessThan)6528 TEST(StreamingAssertionsTest, IntegerLessThan) {
6529 EXPECT_LT(1, 2) << "unexpected failure";
6530 ASSERT_LT(1, 2) << "unexpected failure";
6531 EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
6532 "expected failure");
6533 EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
6534 "expected failure");
6535 }
6536
TEST(StreamingAssertionsTest,StringsEqual)6537 TEST(StreamingAssertionsTest, StringsEqual) {
6538 EXPECT_STREQ("foo", "foo") << "unexpected failure";
6539 ASSERT_STREQ("foo", "foo") << "unexpected failure";
6540 EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
6541 "expected failure");
6542 EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
6543 "expected failure");
6544 }
6545
TEST(StreamingAssertionsTest,StringsNotEqual)6546 TEST(StreamingAssertionsTest, StringsNotEqual) {
6547 EXPECT_STRNE("foo", "bar") << "unexpected failure";
6548 ASSERT_STRNE("foo", "bar") << "unexpected failure";
6549 EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
6550 "expected failure");
6551 EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
6552 "expected failure");
6553 }
6554
TEST(StreamingAssertionsTest,StringsEqualIgnoringCase)6555 TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
6556 EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6557 ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
6558 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
6559 "expected failure");
6560 EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
6561 "expected failure");
6562 }
6563
TEST(StreamingAssertionsTest,StringNotEqualIgnoringCase)6564 TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
6565 EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
6566 ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
6567 EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
6568 "expected failure");
6569 EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
6570 "expected failure");
6571 }
6572
TEST(StreamingAssertionsTest,FloatingPointEquals)6573 TEST(StreamingAssertionsTest, FloatingPointEquals) {
6574 EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6575 ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
6576 EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6577 "expected failure");
6578 EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
6579 "expected failure");
6580 }
6581
6582 #if GTEST_HAS_EXCEPTIONS
6583
TEST(StreamingAssertionsTest,Throw)6584 TEST(StreamingAssertionsTest, Throw) {
6585 EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6586 ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
6587 EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
6588 "expected failure", "expected failure");
6589 EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
6590 "expected failure", "expected failure");
6591 }
6592
TEST(StreamingAssertionsTest,NoThrow)6593 TEST(StreamingAssertionsTest, NoThrow) {
6594 EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
6595 ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
6596 EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
6597 "expected failure", "expected failure");
6598 EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
6599 "expected failure", "expected failure");
6600 }
6601
TEST(StreamingAssertionsTest,AnyThrow)6602 TEST(StreamingAssertionsTest, AnyThrow) {
6603 EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6604 ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
6605 EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
6606 "expected failure", "expected failure");
6607 EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
6608 "expected failure", "expected failure");
6609 }
6610
6611 #endif // GTEST_HAS_EXCEPTIONS
6612
6613 // Tests that Google Test correctly decides whether to use colors in the output.
6614
TEST(ColoredOutputTest,UsesColorsWhenGTestColorFlagIsYes)6615 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
6616 GTEST_FLAG(color) = "yes";
6617
6618 SetEnv("TERM", "xterm"); // TERM supports colors.
6619 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6620 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6621
6622 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6623 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6624 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6625 }
6626
TEST(ColoredOutputTest,UsesColorsWhenGTestColorFlagIsAliasOfYes)6627 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
6628 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6629
6630 GTEST_FLAG(color) = "True";
6631 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6632
6633 GTEST_FLAG(color) = "t";
6634 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6635
6636 GTEST_FLAG(color) = "1";
6637 EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
6638 }
6639
TEST(ColoredOutputTest,UsesNoColorWhenGTestColorFlagIsNo)6640 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
6641 GTEST_FLAG(color) = "no";
6642
6643 SetEnv("TERM", "xterm"); // TERM supports colors.
6644 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6645 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6646
6647 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6648 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6649 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6650 }
6651
TEST(ColoredOutputTest,UsesNoColorWhenGTestColorFlagIsInvalid)6652 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
6653 SetEnv("TERM", "xterm"); // TERM supports colors.
6654
6655 GTEST_FLAG(color) = "F";
6656 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6657
6658 GTEST_FLAG(color) = "0";
6659 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6660
6661 GTEST_FLAG(color) = "unknown";
6662 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6663 }
6664
TEST(ColoredOutputTest,UsesColorsWhenStdoutIsTty)6665 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
6666 GTEST_FLAG(color) = "auto";
6667
6668 SetEnv("TERM", "xterm"); // TERM supports colors.
6669 EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
6670 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6671 }
6672
TEST(ColoredOutputTest,UsesColorsWhenTermSupportsColors)6673 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
6674 GTEST_FLAG(color) = "auto";
6675
6676 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
6677 // On Windows, we ignore the TERM variable as it's usually not set.
6678
6679 SetEnv("TERM", "dumb");
6680 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6681
6682 SetEnv("TERM", "");
6683 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6684
6685 SetEnv("TERM", "xterm");
6686 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6687 #else
6688 // On non-Windows platforms, we rely on TERM to determine if the
6689 // terminal supports colors.
6690
6691 SetEnv("TERM", "dumb"); // TERM doesn't support colors.
6692 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6693
6694 SetEnv("TERM", "emacs"); // TERM doesn't support colors.
6695 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6696
6697 SetEnv("TERM", "vt100"); // TERM doesn't support colors.
6698 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6699
6700 SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
6701 EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
6702
6703 SetEnv("TERM", "xterm"); // TERM supports colors.
6704 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6705
6706 SetEnv("TERM", "xterm-color"); // TERM supports colors.
6707 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6708
6709 SetEnv("TERM", "xterm-256color"); // TERM supports colors.
6710 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6711
6712 SetEnv("TERM", "screen"); // TERM supports colors.
6713 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6714
6715 SetEnv("TERM", "screen-256color"); // TERM supports colors.
6716 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6717
6718 SetEnv("TERM", "tmux"); // TERM supports colors.
6719 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6720
6721 SetEnv("TERM", "tmux-256color"); // TERM supports colors.
6722 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6723
6724 SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
6725 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6726
6727 SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
6728 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6729
6730 SetEnv("TERM", "linux"); // TERM supports colors.
6731 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6732
6733 SetEnv("TERM", "cygwin"); // TERM supports colors.
6734 EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
6735 #endif // GTEST_OS_WINDOWS
6736 }
6737
6738 // Verifies that StaticAssertTypeEq works in a namespace scope.
6739
6740 static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
6741 static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
6742 StaticAssertTypeEq<const int, const int>();
6743
6744 // Verifies that StaticAssertTypeEq works in a class.
6745
6746 template <typename T>
6747 class StaticAssertTypeEqTestHelper {
6748 public:
StaticAssertTypeEqTestHelper()6749 StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
6750 };
6751
TEST(StaticAssertTypeEqTest,WorksInClass)6752 TEST(StaticAssertTypeEqTest, WorksInClass) {
6753 StaticAssertTypeEqTestHelper<bool>();
6754 }
6755
6756 // Verifies that StaticAssertTypeEq works inside a function.
6757
6758 typedef int IntAlias;
6759
TEST(StaticAssertTypeEqTest,CompilesForEqualTypes)6760 TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
6761 StaticAssertTypeEq<int, IntAlias>();
6762 StaticAssertTypeEq<int*, IntAlias*>();
6763 }
6764
TEST(HasNonfatalFailureTest,ReturnsFalseWhenThereIsNoFailure)6765 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6766 EXPECT_FALSE(HasNonfatalFailure());
6767 }
6768
FailFatally()6769 static void FailFatally() { FAIL(); }
6770
TEST(HasNonfatalFailureTest,ReturnsFalseWhenThereIsOnlyFatalFailure)6771 TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
6772 FailFatally();
6773 const bool has_nonfatal_failure = HasNonfatalFailure();
6774 ClearCurrentTestPartResults();
6775 EXPECT_FALSE(has_nonfatal_failure);
6776 }
6777
TEST(HasNonfatalFailureTest,ReturnsTrueWhenThereIsNonfatalFailure)6778 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6779 ADD_FAILURE();
6780 const bool has_nonfatal_failure = HasNonfatalFailure();
6781 ClearCurrentTestPartResults();
6782 EXPECT_TRUE(has_nonfatal_failure);
6783 }
6784
TEST(HasNonfatalFailureTest,ReturnsTrueWhenThereAreFatalAndNonfatalFailures)6785 TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6786 FailFatally();
6787 ADD_FAILURE();
6788 const bool has_nonfatal_failure = HasNonfatalFailure();
6789 ClearCurrentTestPartResults();
6790 EXPECT_TRUE(has_nonfatal_failure);
6791 }
6792
6793 // A wrapper for calling HasNonfatalFailure outside of a test body.
HasNonfatalFailureHelper()6794 static bool HasNonfatalFailureHelper() {
6795 return testing::Test::HasNonfatalFailure();
6796 }
6797
TEST(HasNonfatalFailureTest,WorksOutsideOfTestBody)6798 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
6799 EXPECT_FALSE(HasNonfatalFailureHelper());
6800 }
6801
TEST(HasNonfatalFailureTest,WorksOutsideOfTestBody2)6802 TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
6803 ADD_FAILURE();
6804 const bool has_nonfatal_failure = HasNonfatalFailureHelper();
6805 ClearCurrentTestPartResults();
6806 EXPECT_TRUE(has_nonfatal_failure);
6807 }
6808
TEST(HasFailureTest,ReturnsFalseWhenThereIsNoFailure)6809 TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
6810 EXPECT_FALSE(HasFailure());
6811 }
6812
TEST(HasFailureTest,ReturnsTrueWhenThereIsFatalFailure)6813 TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
6814 FailFatally();
6815 const bool has_failure = HasFailure();
6816 ClearCurrentTestPartResults();
6817 EXPECT_TRUE(has_failure);
6818 }
6819
TEST(HasFailureTest,ReturnsTrueWhenThereIsNonfatalFailure)6820 TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
6821 ADD_FAILURE();
6822 const bool has_failure = HasFailure();
6823 ClearCurrentTestPartResults();
6824 EXPECT_TRUE(has_failure);
6825 }
6826
TEST(HasFailureTest,ReturnsTrueWhenThereAreFatalAndNonfatalFailures)6827 TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
6828 FailFatally();
6829 ADD_FAILURE();
6830 const bool has_failure = HasFailure();
6831 ClearCurrentTestPartResults();
6832 EXPECT_TRUE(has_failure);
6833 }
6834
6835 // A wrapper for calling HasFailure outside of a test body.
HasFailureHelper()6836 static bool HasFailureHelper() { return testing::Test::HasFailure(); }
6837
TEST(HasFailureTest,WorksOutsideOfTestBody)6838 TEST(HasFailureTest, WorksOutsideOfTestBody) {
6839 EXPECT_FALSE(HasFailureHelper());
6840 }
6841
TEST(HasFailureTest,WorksOutsideOfTestBody2)6842 TEST(HasFailureTest, WorksOutsideOfTestBody2) {
6843 ADD_FAILURE();
6844 const bool has_failure = HasFailureHelper();
6845 ClearCurrentTestPartResults();
6846 EXPECT_TRUE(has_failure);
6847 }
6848
6849 class TestListener : public EmptyTestEventListener {
6850 public:
TestListener()6851 TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
TestListener(int * on_start_counter,bool * is_destroyed)6852 TestListener(int* on_start_counter, bool* is_destroyed)
6853 : on_start_counter_(on_start_counter),
6854 is_destroyed_(is_destroyed) {}
6855
~TestListener()6856 ~TestListener() override {
6857 if (is_destroyed_)
6858 *is_destroyed_ = true;
6859 }
6860
6861 protected:
OnTestProgramStart(const UnitTest &)6862 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6863 if (on_start_counter_ != nullptr) (*on_start_counter_)++;
6864 }
6865
6866 private:
6867 int* on_start_counter_;
6868 bool* is_destroyed_;
6869 };
6870
6871 // Tests the constructor.
TEST(TestEventListenersTest,ConstructionWorks)6872 TEST(TestEventListenersTest, ConstructionWorks) {
6873 TestEventListeners listeners;
6874
6875 EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr);
6876 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
6877 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
6878 }
6879
6880 // Tests that the TestEventListeners destructor deletes all the listeners it
6881 // owns.
TEST(TestEventListenersTest,DestructionWorks)6882 TEST(TestEventListenersTest, DestructionWorks) {
6883 bool default_result_printer_is_destroyed = false;
6884 bool default_xml_printer_is_destroyed = false;
6885 bool extra_listener_is_destroyed = false;
6886 TestListener* default_result_printer =
6887 new TestListener(nullptr, &default_result_printer_is_destroyed);
6888 TestListener* default_xml_printer =
6889 new TestListener(nullptr, &default_xml_printer_is_destroyed);
6890 TestListener* extra_listener =
6891 new TestListener(nullptr, &extra_listener_is_destroyed);
6892
6893 {
6894 TestEventListeners listeners;
6895 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
6896 default_result_printer);
6897 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
6898 default_xml_printer);
6899 listeners.Append(extra_listener);
6900 }
6901 EXPECT_TRUE(default_result_printer_is_destroyed);
6902 EXPECT_TRUE(default_xml_printer_is_destroyed);
6903 EXPECT_TRUE(extra_listener_is_destroyed);
6904 }
6905
6906 // Tests that a listener Append'ed to a TestEventListeners list starts
6907 // receiving events.
TEST(TestEventListenersTest,Append)6908 TEST(TestEventListenersTest, Append) {
6909 int on_start_counter = 0;
6910 bool is_destroyed = false;
6911 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
6912 {
6913 TestEventListeners listeners;
6914 listeners.Append(listener);
6915 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6916 *UnitTest::GetInstance());
6917 EXPECT_EQ(1, on_start_counter);
6918 }
6919 EXPECT_TRUE(is_destroyed);
6920 }
6921
6922 // Tests that listeners receive events in the order they were appended to
6923 // the list, except for *End requests, which must be received in the reverse
6924 // order.
6925 class SequenceTestingListener : public EmptyTestEventListener {
6926 public:
SequenceTestingListener(std::vector<std::string> * vector,const char * id)6927 SequenceTestingListener(std::vector<std::string>* vector, const char* id)
6928 : vector_(vector), id_(id) {}
6929
6930 protected:
OnTestProgramStart(const UnitTest &)6931 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
6932 vector_->push_back(GetEventDescription("OnTestProgramStart"));
6933 }
6934
OnTestProgramEnd(const UnitTest &)6935 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {
6936 vector_->push_back(GetEventDescription("OnTestProgramEnd"));
6937 }
6938
OnTestIterationStart(const UnitTest &,int)6939 void OnTestIterationStart(const UnitTest& /*unit_test*/,
6940 int /*iteration*/) override {
6941 vector_->push_back(GetEventDescription("OnTestIterationStart"));
6942 }
6943
OnTestIterationEnd(const UnitTest &,int)6944 void OnTestIterationEnd(const UnitTest& /*unit_test*/,
6945 int /*iteration*/) override {
6946 vector_->push_back(GetEventDescription("OnTestIterationEnd"));
6947 }
6948
6949 private:
GetEventDescription(const char * method)6950 std::string GetEventDescription(const char* method) {
6951 Message message;
6952 message << id_ << "." << method;
6953 return message.GetString();
6954 }
6955
6956 std::vector<std::string>* vector_;
6957 const char* const id_;
6958
6959 GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
6960 };
6961
TEST(EventListenerTest,AppendKeepsOrder)6962 TEST(EventListenerTest, AppendKeepsOrder) {
6963 std::vector<std::string> vec;
6964 TestEventListeners listeners;
6965 listeners.Append(new SequenceTestingListener(&vec, "1st"));
6966 listeners.Append(new SequenceTestingListener(&vec, "2nd"));
6967 listeners.Append(new SequenceTestingListener(&vec, "3rd"));
6968
6969 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
6970 *UnitTest::GetInstance());
6971 ASSERT_EQ(3U, vec.size());
6972 EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
6973 EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
6974 EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
6975
6976 vec.clear();
6977 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
6978 *UnitTest::GetInstance());
6979 ASSERT_EQ(3U, vec.size());
6980 EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
6981 EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
6982 EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
6983
6984 vec.clear();
6985 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
6986 *UnitTest::GetInstance(), 0);
6987 ASSERT_EQ(3U, vec.size());
6988 EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
6989 EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
6990 EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
6991
6992 vec.clear();
6993 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
6994 *UnitTest::GetInstance(), 0);
6995 ASSERT_EQ(3U, vec.size());
6996 EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
6997 EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
6998 EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
6999 }
7000
7001 // Tests that a listener removed from a TestEventListeners list stops receiving
7002 // events and is not deleted when the list is destroyed.
TEST(TestEventListenersTest,Release)7003 TEST(TestEventListenersTest, Release) {
7004 int on_start_counter = 0;
7005 bool is_destroyed = false;
7006 // Although Append passes the ownership of this object to the list,
7007 // the following calls release it, and we need to delete it before the
7008 // test ends.
7009 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7010 {
7011 TestEventListeners listeners;
7012 listeners.Append(listener);
7013 EXPECT_EQ(listener, listeners.Release(listener));
7014 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7015 *UnitTest::GetInstance());
7016 EXPECT_TRUE(listeners.Release(listener) == nullptr);
7017 }
7018 EXPECT_EQ(0, on_start_counter);
7019 EXPECT_FALSE(is_destroyed);
7020 delete listener;
7021 }
7022
7023 // Tests that no events are forwarded when event forwarding is disabled.
TEST(EventListenerTest,SuppressEventForwarding)7024 TEST(EventListenerTest, SuppressEventForwarding) {
7025 int on_start_counter = 0;
7026 TestListener* listener = new TestListener(&on_start_counter, nullptr);
7027
7028 TestEventListeners listeners;
7029 listeners.Append(listener);
7030 ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7031 TestEventListenersAccessor::SuppressEventForwarding(&listeners);
7032 ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
7033 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7034 *UnitTest::GetInstance());
7035 EXPECT_EQ(0, on_start_counter);
7036 }
7037
7038 // Tests that events generated by Google Test are not forwarded in
7039 // death test subprocesses.
TEST(EventListenerDeathTest,EventsNotForwardedInDeathTestSubprecesses)7040 TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
7041 EXPECT_DEATH_IF_SUPPORTED({
7042 GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
7043 *GetUnitTestImpl()->listeners())) << "expected failure";},
7044 "expected failure");
7045 }
7046
7047 // Tests that a listener installed via SetDefaultResultPrinter() starts
7048 // receiving events and is returned via default_result_printer() and that
7049 // the previous default_result_printer is removed from the list and deleted.
TEST(EventListenerTest,default_result_printer)7050 TEST(EventListenerTest, default_result_printer) {
7051 int on_start_counter = 0;
7052 bool is_destroyed = false;
7053 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7054
7055 TestEventListeners listeners;
7056 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7057
7058 EXPECT_EQ(listener, listeners.default_result_printer());
7059
7060 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7061 *UnitTest::GetInstance());
7062
7063 EXPECT_EQ(1, on_start_counter);
7064
7065 // Replacing default_result_printer with something else should remove it
7066 // from the list and destroy it.
7067 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr);
7068
7069 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7070 EXPECT_TRUE(is_destroyed);
7071
7072 // After broadcasting an event the counter is still the same, indicating
7073 // the listener is not in the list anymore.
7074 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7075 *UnitTest::GetInstance());
7076 EXPECT_EQ(1, on_start_counter);
7077 }
7078
7079 // Tests that the default_result_printer listener stops receiving events
7080 // when removed via Release and that is not owned by the list anymore.
TEST(EventListenerTest,RemovingDefaultResultPrinterWorks)7081 TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
7082 int on_start_counter = 0;
7083 bool is_destroyed = false;
7084 // Although Append passes the ownership of this object to the list,
7085 // the following calls release it, and we need to delete it before the
7086 // test ends.
7087 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7088 {
7089 TestEventListeners listeners;
7090 TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
7091
7092 EXPECT_EQ(listener, listeners.Release(listener));
7093 EXPECT_TRUE(listeners.default_result_printer() == nullptr);
7094 EXPECT_FALSE(is_destroyed);
7095
7096 // Broadcasting events now should not affect default_result_printer.
7097 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7098 *UnitTest::GetInstance());
7099 EXPECT_EQ(0, on_start_counter);
7100 }
7101 // Destroying the list should not affect the listener now, too.
7102 EXPECT_FALSE(is_destroyed);
7103 delete listener;
7104 }
7105
7106 // Tests that a listener installed via SetDefaultXmlGenerator() starts
7107 // receiving events and is returned via default_xml_generator() and that
7108 // the previous default_xml_generator is removed from the list and deleted.
TEST(EventListenerTest,default_xml_generator)7109 TEST(EventListenerTest, default_xml_generator) {
7110 int on_start_counter = 0;
7111 bool is_destroyed = false;
7112 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7113
7114 TestEventListeners listeners;
7115 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7116
7117 EXPECT_EQ(listener, listeners.default_xml_generator());
7118
7119 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7120 *UnitTest::GetInstance());
7121
7122 EXPECT_EQ(1, on_start_counter);
7123
7124 // Replacing default_xml_generator with something else should remove it
7125 // from the list and destroy it.
7126 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr);
7127
7128 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7129 EXPECT_TRUE(is_destroyed);
7130
7131 // After broadcasting an event the counter is still the same, indicating
7132 // the listener is not in the list anymore.
7133 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7134 *UnitTest::GetInstance());
7135 EXPECT_EQ(1, on_start_counter);
7136 }
7137
7138 // Tests that the default_xml_generator listener stops receiving events
7139 // when removed via Release and that is not owned by the list anymore.
TEST(EventListenerTest,RemovingDefaultXmlGeneratorWorks)7140 TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
7141 int on_start_counter = 0;
7142 bool is_destroyed = false;
7143 // Although Append passes the ownership of this object to the list,
7144 // the following calls release it, and we need to delete it before the
7145 // test ends.
7146 TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
7147 {
7148 TestEventListeners listeners;
7149 TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
7150
7151 EXPECT_EQ(listener, listeners.Release(listener));
7152 EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
7153 EXPECT_FALSE(is_destroyed);
7154
7155 // Broadcasting events now should not affect default_xml_generator.
7156 TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
7157 *UnitTest::GetInstance());
7158 EXPECT_EQ(0, on_start_counter);
7159 }
7160 // Destroying the list should not affect the listener now, too.
7161 EXPECT_FALSE(is_destroyed);
7162 delete listener;
7163 }
7164
7165 // Sanity tests to ensure that the alternative, verbose spellings of
7166 // some of the macros work. We don't test them thoroughly as that
7167 // would be quite involved. Since their implementations are
7168 // straightforward, and they are rarely used, we'll just rely on the
7169 // users to tell us when they are broken.
GTEST_TEST(AlternativeNameTest,Works)7170 GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
7171 GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
7172
7173 // GTEST_FAIL is the same as FAIL.
7174 EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
7175 "An expected failure");
7176
7177 // GTEST_ASSERT_XY is the same as ASSERT_XY.
7178
7179 GTEST_ASSERT_EQ(0, 0);
7180 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
7181 "An expected failure");
7182 EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
7183 "An expected failure");
7184
7185 GTEST_ASSERT_NE(0, 1);
7186 GTEST_ASSERT_NE(1, 0);
7187 EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
7188 "An expected failure");
7189
7190 GTEST_ASSERT_LE(0, 0);
7191 GTEST_ASSERT_LE(0, 1);
7192 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
7193 "An expected failure");
7194
7195 GTEST_ASSERT_LT(0, 1);
7196 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
7197 "An expected failure");
7198 EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
7199 "An expected failure");
7200
7201 GTEST_ASSERT_GE(0, 0);
7202 GTEST_ASSERT_GE(1, 0);
7203 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
7204 "An expected failure");
7205
7206 GTEST_ASSERT_GT(1, 0);
7207 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
7208 "An expected failure");
7209 EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
7210 "An expected failure");
7211 }
7212
7213 // Tests for internal utilities necessary for implementation of the universal
7214 // printing.
7215
7216 class ConversionHelperBase {};
7217 class ConversionHelperDerived : public ConversionHelperBase {};
7218
7219 struct HasDebugStringMethods {
DebugStringHasDebugStringMethods7220 std::string DebugString() const { return ""; }
ShortDebugStringHasDebugStringMethods7221 std::string ShortDebugString() const { return ""; }
7222 };
7223
7224 struct InheritsDebugStringMethods : public HasDebugStringMethods {};
7225
7226 struct WrongTypeDebugStringMethod {
DebugStringWrongTypeDebugStringMethod7227 std::string DebugString() const { return ""; }
ShortDebugStringWrongTypeDebugStringMethod7228 int ShortDebugString() const { return 1; }
7229 };
7230
7231 struct NotConstDebugStringMethod {
DebugStringNotConstDebugStringMethod7232 std::string DebugString() { return ""; }
ShortDebugStringNotConstDebugStringMethod7233 std::string ShortDebugString() const { return ""; }
7234 };
7235
7236 struct MissingDebugStringMethod {
DebugStringMissingDebugStringMethod7237 std::string DebugString() { return ""; }
7238 };
7239
7240 struct IncompleteType;
7241
7242 // Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
7243 // constant.
TEST(HasDebugStringAndShortDebugStringTest,ValueIsCompileTimeConstant)7244 TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
7245 GTEST_COMPILE_ASSERT_(
7246 HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
7247 const_true);
7248 GTEST_COMPILE_ASSERT_(
7249 HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
7250 const_true);
7251 GTEST_COMPILE_ASSERT_(HasDebugStringAndShortDebugString<
7252 const InheritsDebugStringMethods>::value,
7253 const_true);
7254 GTEST_COMPILE_ASSERT_(
7255 !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
7256 const_false);
7257 GTEST_COMPILE_ASSERT_(
7258 !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
7259 const_false);
7260 GTEST_COMPILE_ASSERT_(
7261 !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
7262 const_false);
7263 GTEST_COMPILE_ASSERT_(
7264 !HasDebugStringAndShortDebugString<IncompleteType>::value, const_false);
7265 GTEST_COMPILE_ASSERT_(!HasDebugStringAndShortDebugString<int>::value,
7266 const_false);
7267 }
7268
7269 // Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
7270 // needed methods.
TEST(HasDebugStringAndShortDebugStringTest,ValueIsTrueWhenTypeHasDebugStringAndShortDebugString)7271 TEST(HasDebugStringAndShortDebugStringTest,
7272 ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
7273 EXPECT_TRUE(
7274 HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
7275 }
7276
7277 // Tests that HasDebugStringAndShortDebugString<T>::value is false when T
7278 // doesn't have needed methods.
TEST(HasDebugStringAndShortDebugStringTest,ValueIsFalseWhenTypeIsNotAProtocolMessage)7279 TEST(HasDebugStringAndShortDebugStringTest,
7280 ValueIsFalseWhenTypeIsNotAProtocolMessage) {
7281 EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);
7282 EXPECT_FALSE(
7283 HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);
7284 }
7285
7286 // Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
7287
7288 template <typename T1, typename T2>
TestGTestRemoveReferenceAndConst()7289 void TestGTestRemoveReferenceAndConst() {
7290 static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value,
7291 "GTEST_REMOVE_REFERENCE_AND_CONST_ failed.");
7292 }
7293
TEST(RemoveReferenceToConstTest,Works)7294 TEST(RemoveReferenceToConstTest, Works) {
7295 TestGTestRemoveReferenceAndConst<int, int>();
7296 TestGTestRemoveReferenceAndConst<double, double&>();
7297 TestGTestRemoveReferenceAndConst<char, const char>();
7298 TestGTestRemoveReferenceAndConst<char, const char&>();
7299 TestGTestRemoveReferenceAndConst<const char*, const char*>();
7300 }
7301
7302 // Tests GTEST_REFERENCE_TO_CONST_.
7303
7304 template <typename T1, typename T2>
TestGTestReferenceToConst()7305 void TestGTestReferenceToConst() {
7306 static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value,
7307 "GTEST_REFERENCE_TO_CONST_ failed.");
7308 }
7309
TEST(GTestReferenceToConstTest,Works)7310 TEST(GTestReferenceToConstTest, Works) {
7311 TestGTestReferenceToConst<const char&, char>();
7312 TestGTestReferenceToConst<const int&, const int>();
7313 TestGTestReferenceToConst<const double&, double>();
7314 TestGTestReferenceToConst<const std::string&, const std::string&>();
7315 }
7316
7317
7318 // Tests IsContainerTest.
7319
7320 class NonContainer {};
7321
TEST(IsContainerTestTest,WorksForNonContainer)7322 TEST(IsContainerTestTest, WorksForNonContainer) {
7323 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
7324 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
7325 EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
7326 }
7327
TEST(IsContainerTestTest,WorksForContainer)7328 TEST(IsContainerTestTest, WorksForContainer) {
7329 EXPECT_EQ(sizeof(IsContainer),
7330 sizeof(IsContainerTest<std::vector<bool> >(0)));
7331 EXPECT_EQ(sizeof(IsContainer),
7332 sizeof(IsContainerTest<std::map<int, double> >(0)));
7333 }
7334
7335 struct ConstOnlyContainerWithPointerIterator {
7336 using const_iterator = int*;
7337 const_iterator begin() const;
7338 const_iterator end() const;
7339 };
7340
7341 struct ConstOnlyContainerWithClassIterator {
7342 struct const_iterator {
7343 const int& operator*() const;
7344 const_iterator& operator++(/* pre-increment */);
7345 };
7346 const_iterator begin() const;
7347 const_iterator end() const;
7348 };
7349
TEST(IsContainerTestTest,ConstOnlyContainer)7350 TEST(IsContainerTestTest, ConstOnlyContainer) {
7351 EXPECT_EQ(sizeof(IsContainer),
7352 sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
7353 EXPECT_EQ(sizeof(IsContainer),
7354 sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
7355 }
7356
7357 // Tests IsHashTable.
7358 struct AHashTable {
7359 typedef void hasher;
7360 };
7361 struct NotReallyAHashTable {
7362 typedef void hasher;
7363 typedef void reverse_iterator;
7364 };
TEST(IsHashTable,Basic)7365 TEST(IsHashTable, Basic) {
7366 EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value);
7367 EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value);
7368 EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value);
7369 EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value);
7370 }
7371
7372 // Tests ArrayEq().
7373
TEST(ArrayEqTest,WorksForDegeneratedArrays)7374 TEST(ArrayEqTest, WorksForDegeneratedArrays) {
7375 EXPECT_TRUE(ArrayEq(5, 5L));
7376 EXPECT_FALSE(ArrayEq('a', 0));
7377 }
7378
TEST(ArrayEqTest,WorksForOneDimensionalArrays)7379 TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
7380 // Note that a and b are distinct but compatible types.
7381 const int a[] = { 0, 1 };
7382 long b[] = { 0, 1 };
7383 EXPECT_TRUE(ArrayEq(a, b));
7384 EXPECT_TRUE(ArrayEq(a, 2, b));
7385
7386 b[0] = 2;
7387 EXPECT_FALSE(ArrayEq(a, b));
7388 EXPECT_FALSE(ArrayEq(a, 1, b));
7389 }
7390
TEST(ArrayEqTest,WorksForTwoDimensionalArrays)7391 TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
7392 const char a[][3] = { "hi", "lo" };
7393 const char b[][3] = { "hi", "lo" };
7394 const char c[][3] = { "hi", "li" };
7395
7396 EXPECT_TRUE(ArrayEq(a, b));
7397 EXPECT_TRUE(ArrayEq(a, 2, b));
7398
7399 EXPECT_FALSE(ArrayEq(a, c));
7400 EXPECT_FALSE(ArrayEq(a, 2, c));
7401 }
7402
7403 // Tests ArrayAwareFind().
7404
TEST(ArrayAwareFindTest,WorksForOneDimensionalArray)7405 TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
7406 const char a[] = "hello";
7407 EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
7408 EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
7409 }
7410
TEST(ArrayAwareFindTest,WorksForTwoDimensionalArray)7411 TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
7412 int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
7413 const int b[2] = { 2, 3 };
7414 EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
7415
7416 const int c[2] = { 6, 7 };
7417 EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
7418 }
7419
7420 // Tests CopyArray().
7421
TEST(CopyArrayTest,WorksForDegeneratedArrays)7422 TEST(CopyArrayTest, WorksForDegeneratedArrays) {
7423 int n = 0;
7424 CopyArray('a', &n);
7425 EXPECT_EQ('a', n);
7426 }
7427
TEST(CopyArrayTest,WorksForOneDimensionalArrays)7428 TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
7429 const char a[3] = "hi";
7430 int b[3];
7431 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7432 CopyArray(a, &b);
7433 EXPECT_TRUE(ArrayEq(a, b));
7434 #endif
7435
7436 int c[3];
7437 CopyArray(a, 3, c);
7438 EXPECT_TRUE(ArrayEq(a, c));
7439 }
7440
TEST(CopyArrayTest,WorksForTwoDimensionalArrays)7441 TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
7442 const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
7443 int b[2][3];
7444 #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
7445 CopyArray(a, &b);
7446 EXPECT_TRUE(ArrayEq(a, b));
7447 #endif
7448
7449 int c[2][3];
7450 CopyArray(a, 2, c);
7451 EXPECT_TRUE(ArrayEq(a, c));
7452 }
7453
7454 // Tests NativeArray.
7455
TEST(NativeArrayTest,ConstructorFromArrayWorks)7456 TEST(NativeArrayTest, ConstructorFromArrayWorks) {
7457 const int a[3] = { 0, 1, 2 };
7458 NativeArray<int> na(a, 3, RelationToSourceReference());
7459 EXPECT_EQ(3U, na.size());
7460 EXPECT_EQ(a, na.begin());
7461 }
7462
TEST(NativeArrayTest,CreatesAndDeletesCopyOfArrayWhenAskedTo)7463 TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
7464 typedef int Array[2];
7465 Array* a = new Array[1];
7466 (*a)[0] = 0;
7467 (*a)[1] = 1;
7468 NativeArray<int> na(*a, 2, RelationToSourceCopy());
7469 EXPECT_NE(*a, na.begin());
7470 delete[] a;
7471 EXPECT_EQ(0, na.begin()[0]);
7472 EXPECT_EQ(1, na.begin()[1]);
7473
7474 // We rely on the heap checker to verify that na deletes the copy of
7475 // array.
7476 }
7477
TEST(NativeArrayTest,TypeMembersAreCorrect)7478 TEST(NativeArrayTest, TypeMembersAreCorrect) {
7479 StaticAssertTypeEq<char, NativeArray<char>::value_type>();
7480 StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
7481
7482 StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
7483 StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
7484 }
7485
TEST(NativeArrayTest,MethodsWork)7486 TEST(NativeArrayTest, MethodsWork) {
7487 const int a[3] = { 0, 1, 2 };
7488 NativeArray<int> na(a, 3, RelationToSourceCopy());
7489 ASSERT_EQ(3U, na.size());
7490 EXPECT_EQ(3, na.end() - na.begin());
7491
7492 NativeArray<int>::const_iterator it = na.begin();
7493 EXPECT_EQ(0, *it);
7494 ++it;
7495 EXPECT_EQ(1, *it);
7496 it++;
7497 EXPECT_EQ(2, *it);
7498 ++it;
7499 EXPECT_EQ(na.end(), it);
7500
7501 EXPECT_TRUE(na == na);
7502
7503 NativeArray<int> na2(a, 3, RelationToSourceReference());
7504 EXPECT_TRUE(na == na2);
7505
7506 const int b1[3] = { 0, 1, 1 };
7507 const int b2[4] = { 0, 1, 2, 3 };
7508 EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
7509 EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
7510 }
7511
TEST(NativeArrayTest,WorksForTwoDimensionalArray)7512 TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
7513 const char a[2][3] = { "hi", "lo" };
7514 NativeArray<char[3]> na(a, 2, RelationToSourceReference());
7515 ASSERT_EQ(2U, na.size());
7516 EXPECT_EQ(a, na.begin());
7517 }
7518
7519 // IndexSequence
TEST(IndexSequence,MakeIndexSequence)7520 TEST(IndexSequence, MakeIndexSequence) {
7521 using testing::internal::IndexSequence;
7522 using testing::internal::MakeIndexSequence;
7523 EXPECT_TRUE(
7524 (std::is_same<IndexSequence<>, MakeIndexSequence<0>::type>::value));
7525 EXPECT_TRUE(
7526 (std::is_same<IndexSequence<0>, MakeIndexSequence<1>::type>::value));
7527 EXPECT_TRUE(
7528 (std::is_same<IndexSequence<0, 1>, MakeIndexSequence<2>::type>::value));
7529 EXPECT_TRUE((
7530 std::is_same<IndexSequence<0, 1, 2>, MakeIndexSequence<3>::type>::value));
7531 EXPECT_TRUE(
7532 (std::is_base_of<IndexSequence<0, 1, 2>, MakeIndexSequence<3>>::value));
7533 }
7534
7535 // ElemFromList
TEST(ElemFromList,Basic)7536 TEST(ElemFromList, Basic) {
7537 using testing::internal::ElemFromList;
7538 EXPECT_TRUE(
7539 (std::is_same<int, ElemFromList<0, int, double, char>::type>::value));
7540 EXPECT_TRUE(
7541 (std::is_same<double, ElemFromList<1, int, double, char>::type>::value));
7542 EXPECT_TRUE(
7543 (std::is_same<char, ElemFromList<2, int, double, char>::type>::value));
7544 EXPECT_TRUE((
7545 std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int,
7546 char, int, int, int, int>::type>::value));
7547 }
7548
7549 // FlatTuple
TEST(FlatTuple,Basic)7550 TEST(FlatTuple, Basic) {
7551 using testing::internal::FlatTuple;
7552
7553 FlatTuple<int, double, const char*> tuple = {};
7554 EXPECT_EQ(0, tuple.Get<0>());
7555 EXPECT_EQ(0.0, tuple.Get<1>());
7556 EXPECT_EQ(nullptr, tuple.Get<2>());
7557
7558 tuple = FlatTuple<int, double, const char*>(
7559 testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo");
7560 EXPECT_EQ(7, tuple.Get<0>());
7561 EXPECT_EQ(3.2, tuple.Get<1>());
7562 EXPECT_EQ(std::string("Foo"), tuple.Get<2>());
7563
7564 tuple.Get<1>() = 5.1;
7565 EXPECT_EQ(5.1, tuple.Get<1>());
7566 }
7567
7568 namespace {
AddIntToString(int i,const std::string & s)7569 std::string AddIntToString(int i, const std::string& s) {
7570 return s + std::to_string(i);
7571 }
7572 } // namespace
7573
TEST(FlatTuple,Apply)7574 TEST(FlatTuple, Apply) {
7575 using testing::internal::FlatTuple;
7576
7577 FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},
7578 5, "Hello"};
7579
7580 // Lambda.
7581 EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
7582 return i == static_cast<int>(s.size());
7583 }));
7584
7585 // Function.
7586 EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
7587
7588 // Mutating operations.
7589 tuple.Apply([](int& i, std::string& s) {
7590 ++i;
7591 s += s;
7592 });
7593 EXPECT_EQ(tuple.Get<0>(), 6);
7594 EXPECT_EQ(tuple.Get<1>(), "HelloHello");
7595 }
7596
7597 struct ConstructionCounting {
ConstructionCountingConstructionCounting7598 ConstructionCounting() { ++default_ctor_calls; }
~ConstructionCountingConstructionCounting7599 ~ConstructionCounting() { ++dtor_calls; }
ConstructionCountingConstructionCounting7600 ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }
ConstructionCountingConstructionCounting7601 ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }
operator =ConstructionCounting7602 ConstructionCounting& operator=(const ConstructionCounting&) {
7603 ++copy_assignment_calls;
7604 return *this;
7605 }
operator =ConstructionCounting7606 ConstructionCounting& operator=(ConstructionCounting&&) noexcept {
7607 ++move_assignment_calls;
7608 return *this;
7609 }
7610
ResetConstructionCounting7611 static void Reset() {
7612 default_ctor_calls = 0;
7613 dtor_calls = 0;
7614 copy_ctor_calls = 0;
7615 move_ctor_calls = 0;
7616 copy_assignment_calls = 0;
7617 move_assignment_calls = 0;
7618 }
7619
7620 static int default_ctor_calls;
7621 static int dtor_calls;
7622 static int copy_ctor_calls;
7623 static int move_ctor_calls;
7624 static int copy_assignment_calls;
7625 static int move_assignment_calls;
7626 };
7627
7628 int ConstructionCounting::default_ctor_calls = 0;
7629 int ConstructionCounting::dtor_calls = 0;
7630 int ConstructionCounting::copy_ctor_calls = 0;
7631 int ConstructionCounting::move_ctor_calls = 0;
7632 int ConstructionCounting::copy_assignment_calls = 0;
7633 int ConstructionCounting::move_assignment_calls = 0;
7634
TEST(FlatTuple,ConstructorCalls)7635 TEST(FlatTuple, ConstructorCalls) {
7636 using testing::internal::FlatTuple;
7637
7638 // Default construction.
7639 ConstructionCounting::Reset();
7640 { FlatTuple<ConstructionCounting> tuple; }
7641 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7642 EXPECT_EQ(ConstructionCounting::dtor_calls, 1);
7643 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7644 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7645 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7646 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7647
7648 // Copy construction.
7649 ConstructionCounting::Reset();
7650 {
7651 ConstructionCounting elem;
7652 FlatTuple<ConstructionCounting> tuple{
7653 testing::internal::FlatTupleConstructTag{}, elem};
7654 }
7655 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7656 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7657 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);
7658 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7659 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7660 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7661
7662 // Move construction.
7663 ConstructionCounting::Reset();
7664 {
7665 FlatTuple<ConstructionCounting> tuple{
7666 testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}};
7667 }
7668 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
7669 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7670 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7671 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);
7672 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7673 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7674
7675 // Copy assignment.
7676 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7677 // elements
7678 ConstructionCounting::Reset();
7679 {
7680 FlatTuple<ConstructionCounting> tuple;
7681 ConstructionCounting elem;
7682 tuple.Get<0>() = elem;
7683 }
7684 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
7685 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7686 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7687 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7688 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);
7689 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
7690
7691 // Move assignment.
7692 // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
7693 // elements
7694 ConstructionCounting::Reset();
7695 {
7696 FlatTuple<ConstructionCounting> tuple;
7697 tuple.Get<0>() = ConstructionCounting{};
7698 }
7699 EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
7700 EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
7701 EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
7702 EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
7703 EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
7704 EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);
7705
7706 ConstructionCounting::Reset();
7707 }
7708
TEST(FlatTuple,ManyTypes)7709 TEST(FlatTuple, ManyTypes) {
7710 using testing::internal::FlatTuple;
7711
7712 // Instantiate FlatTuple with 257 ints.
7713 // Tests show that we can do it with thousands of elements, but very long
7714 // compile times makes it unusuitable for this test.
7715 #define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int,
7716 #define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8
7717 #define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16
7718 #define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32
7719 #define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64
7720 #define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128
7721
7722 // Let's make sure that we can have a very long list of types without blowing
7723 // up the template instantiation depth.
7724 FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple;
7725
7726 tuple.Get<0>() = 7;
7727 tuple.Get<99>() = 17;
7728 tuple.Get<256>() = 1000;
7729 EXPECT_EQ(7, tuple.Get<0>());
7730 EXPECT_EQ(17, tuple.Get<99>());
7731 EXPECT_EQ(1000, tuple.Get<256>());
7732 }
7733
7734 // Tests SkipPrefix().
7735
TEST(SkipPrefixTest,SkipsWhenPrefixMatches)7736 TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
7737 const char* const str = "hello";
7738
7739 const char* p = str;
7740 EXPECT_TRUE(SkipPrefix("", &p));
7741 EXPECT_EQ(str, p);
7742
7743 p = str;
7744 EXPECT_TRUE(SkipPrefix("hell", &p));
7745 EXPECT_EQ(str + 4, p);
7746 }
7747
TEST(SkipPrefixTest,DoesNotSkipWhenPrefixDoesNotMatch)7748 TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
7749 const char* const str = "world";
7750
7751 const char* p = str;
7752 EXPECT_FALSE(SkipPrefix("W", &p));
7753 EXPECT_EQ(str, p);
7754
7755 p = str;
7756 EXPECT_FALSE(SkipPrefix("world!", &p));
7757 EXPECT_EQ(str, p);
7758 }
7759
7760 // Tests ad_hoc_test_result().
TEST(AdHocTestResultTest,AdHocTestResultForUnitTestDoesNotShowFailure)7761 TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
7762 const testing::TestResult& test_result =
7763 testing::UnitTest::GetInstance()->ad_hoc_test_result();
7764 EXPECT_FALSE(test_result.Failed());
7765 }
7766
7767 class DynamicUnitTestFixture : public testing::Test {};
7768
7769 class DynamicTest : public DynamicUnitTestFixture {
TestBody()7770 void TestBody() override { EXPECT_TRUE(true); }
7771 };
7772
7773 auto* dynamic_test = testing::RegisterTest(
7774 "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__,
__anona388e2a90902() 7775 __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });
7776
TEST(RegisterTest,WasRegistered)7777 TEST(RegisterTest, WasRegistered) {
7778 auto* unittest = testing::UnitTest::GetInstance();
7779 for (int i = 0; i < unittest->total_test_suite_count(); ++i) {
7780 auto* tests = unittest->GetTestSuite(i);
7781 if (tests->name() != std::string("DynamicUnitTestFixture")) continue;
7782 for (int j = 0; j < tests->total_test_count(); ++j) {
7783 if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue;
7784 // Found it.
7785 EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE");
7786 EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE");
7787 return;
7788 }
7789 }
7790
7791 FAIL() << "Didn't find the test!";
7792 }
7793