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