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