/src/3rdparty/webkit/Source/ThirdParty/gtest/test/gtest_unittest.cc

https://bitbucket.org/ultra_iter/qt-vtl · C++ · 6718 lines · 4544 code · 1109 blank · 1065 comment · 137 complexity · 2a2fb6867b2f677bf95a2910c435ca59 MD5 · raw file

  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. // Author: wan@google.com (Zhanyong Wan)
  31. //
  32. // Tests for Google Test itself. This verifies that the basic constructs of
  33. // Google Test work.
  34. #include <gtest/gtest.h>
  35. #include <vector>
  36. // Verifies that the command line flag variables can be accessed
  37. // in code once <gtest/gtest.h> has been #included.
  38. // Do not move it after other #includes.
  39. TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
  40. bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
  41. || testing::GTEST_FLAG(break_on_failure)
  42. || testing::GTEST_FLAG(catch_exceptions)
  43. || testing::GTEST_FLAG(color) != "unknown"
  44. || testing::GTEST_FLAG(filter) != "unknown"
  45. || testing::GTEST_FLAG(list_tests)
  46. || testing::GTEST_FLAG(output) != "unknown"
  47. || testing::GTEST_FLAG(print_time)
  48. || testing::GTEST_FLAG(random_seed)
  49. || testing::GTEST_FLAG(repeat) > 0
  50. || testing::GTEST_FLAG(show_internal_stack_frames)
  51. || testing::GTEST_FLAG(shuffle)
  52. || testing::GTEST_FLAG(stack_trace_depth) > 0
  53. || testing::GTEST_FLAG(throw_on_failure);
  54. EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
  55. }
  56. #include <gtest/gtest-spi.h>
  57. // Indicates that this translation unit is part of Google Test's
  58. // implementation. It must come before gtest-internal-inl.h is
  59. // included, or there will be a compiler error. This trick is to
  60. // prevent a user from accidentally including gtest-internal-inl.h in
  61. // his code.
  62. #define GTEST_IMPLEMENTATION_ 1
  63. #include "src/gtest-internal-inl.h"
  64. #undef GTEST_IMPLEMENTATION_
  65. #include <limits.h> // For INT_MAX.
  66. #include <stdlib.h>
  67. #include <time.h>
  68. #include <map>
  69. namespace testing {
  70. namespace internal {
  71. // Provides access to otherwise private parts of the TestEventListeners class
  72. // that are needed to test it.
  73. class TestEventListenersAccessor {
  74. public:
  75. static TestEventListener* GetRepeater(TestEventListeners* listeners) {
  76. return listeners->repeater();
  77. }
  78. static void SetDefaultResultPrinter(TestEventListeners* listeners,
  79. TestEventListener* listener) {
  80. listeners->SetDefaultResultPrinter(listener);
  81. }
  82. static void SetDefaultXmlGenerator(TestEventListeners* listeners,
  83. TestEventListener* listener) {
  84. listeners->SetDefaultXmlGenerator(listener);
  85. }
  86. static bool EventForwardingEnabled(const TestEventListeners& listeners) {
  87. return listeners.EventForwardingEnabled();
  88. }
  89. static void SuppressEventForwarding(TestEventListeners* listeners) {
  90. listeners->SuppressEventForwarding();
  91. }
  92. };
  93. } // namespace internal
  94. } // namespace testing
  95. using testing::AssertionFailure;
  96. using testing::AssertionResult;
  97. using testing::AssertionSuccess;
  98. using testing::DoubleLE;
  99. using testing::EmptyTestEventListener;
  100. using testing::FloatLE;
  101. using testing::GTEST_FLAG(also_run_disabled_tests);
  102. using testing::GTEST_FLAG(break_on_failure);
  103. using testing::GTEST_FLAG(catch_exceptions);
  104. using testing::GTEST_FLAG(color);
  105. using testing::GTEST_FLAG(death_test_use_fork);
  106. using testing::GTEST_FLAG(filter);
  107. using testing::GTEST_FLAG(list_tests);
  108. using testing::GTEST_FLAG(output);
  109. using testing::GTEST_FLAG(print_time);
  110. using testing::GTEST_FLAG(random_seed);
  111. using testing::GTEST_FLAG(repeat);
  112. using testing::GTEST_FLAG(show_internal_stack_frames);
  113. using testing::GTEST_FLAG(shuffle);
  114. using testing::GTEST_FLAG(stack_trace_depth);
  115. using testing::GTEST_FLAG(throw_on_failure);
  116. using testing::IsNotSubstring;
  117. using testing::IsSubstring;
  118. using testing::Message;
  119. using testing::ScopedFakeTestPartResultReporter;
  120. using testing::StaticAssertTypeEq;
  121. using testing::Test;
  122. using testing::TestEventListeners;
  123. using testing::TestCase;
  124. using testing::TestPartResult;
  125. using testing::TestPartResultArray;
  126. using testing::TestProperty;
  127. using testing::TestResult;
  128. using testing::UnitTest;
  129. using testing::kMaxStackTraceDepth;
  130. using testing::internal::AlwaysFalse;
  131. using testing::internal::AlwaysTrue;
  132. using testing::internal::AppendUserMessage;
  133. using testing::internal::CodePointToUtf8;
  134. using testing::internal::CountIf;
  135. using testing::internal::EqFailure;
  136. using testing::internal::FloatingPoint;
  137. using testing::internal::FormatTimeInMillisAsSeconds;
  138. using testing::internal::ForEach;
  139. using testing::internal::GTestFlagSaver;
  140. using testing::internal::GetCurrentOsStackTraceExceptTop;
  141. using testing::internal::GetElementOr;
  142. using testing::internal::GetNextRandomSeed;
  143. using testing::internal::GetRandomSeedFromFlag;
  144. using testing::internal::GetTestTypeId;
  145. using testing::internal::GetTypeId;
  146. using testing::internal::GetUnitTestImpl;
  147. using testing::internal::Int32;
  148. using testing::internal::Int32FromEnvOrDie;
  149. using testing::internal::ParseInt32Flag;
  150. using testing::internal::ShouldRunTestOnShard;
  151. using testing::internal::ShouldShard;
  152. using testing::internal::ShouldUseColor;
  153. using testing::internal::Shuffle;
  154. using testing::internal::ShuffleRange;
  155. using testing::internal::StreamableToString;
  156. using testing::internal::String;
  157. using testing::internal::TestEventListenersAccessor;
  158. using testing::internal::TestResultAccessor;
  159. using testing::internal::UInt32;
  160. using testing::internal::WideStringToUtf8;
  161. using testing::internal::kMaxRandomSeed;
  162. using testing::internal::kTestTypeIdInGoogleTest;
  163. using testing::internal::scoped_ptr;
  164. #if GTEST_HAS_STREAM_REDIRECTION_
  165. using testing::internal::CaptureStdout;
  166. using testing::internal::GetCapturedStdout;
  167. #endif // GTEST_HAS_STREAM_REDIRECTION_
  168. #if GTEST_IS_THREADSAFE
  169. using testing::internal::ThreadWithParam;
  170. #endif
  171. class TestingVector : public std::vector<int> {
  172. };
  173. ::std::ostream& operator<<(::std::ostream& os,
  174. const TestingVector& vector) {
  175. os << "{ ";
  176. for (size_t i = 0; i < vector.size(); i++) {
  177. os << vector[i] << " ";
  178. }
  179. os << "}";
  180. return os;
  181. }
  182. // This line tests that we can define tests in an unnamed namespace.
  183. namespace {
  184. TEST(GetRandomSeedFromFlagTest, HandlesZero) {
  185. const int seed = GetRandomSeedFromFlag(0);
  186. EXPECT_LE(1, seed);
  187. EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
  188. }
  189. TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
  190. EXPECT_EQ(1, GetRandomSeedFromFlag(1));
  191. EXPECT_EQ(2, GetRandomSeedFromFlag(2));
  192. EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
  193. EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
  194. GetRandomSeedFromFlag(kMaxRandomSeed));
  195. }
  196. TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
  197. const int seed1 = GetRandomSeedFromFlag(-1);
  198. EXPECT_LE(1, seed1);
  199. EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
  200. const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
  201. EXPECT_LE(1, seed2);
  202. EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
  203. }
  204. TEST(GetNextRandomSeedTest, WorksForValidInput) {
  205. EXPECT_EQ(2, GetNextRandomSeed(1));
  206. EXPECT_EQ(3, GetNextRandomSeed(2));
  207. EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
  208. GetNextRandomSeed(kMaxRandomSeed - 1));
  209. EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
  210. // We deliberately don't test GetNextRandomSeed() with invalid
  211. // inputs, as that requires death tests, which are expensive. This
  212. // is fine as GetNextRandomSeed() is internal and has a
  213. // straightforward definition.
  214. }
  215. static void ClearCurrentTestPartResults() {
  216. TestResultAccessor::ClearTestPartResults(
  217. GetUnitTestImpl()->current_test_result());
  218. }
  219. // Tests GetTypeId.
  220. TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
  221. EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
  222. EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
  223. }
  224. class SubClassOfTest : public Test {};
  225. class AnotherSubClassOfTest : public Test {};
  226. TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
  227. EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
  228. EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
  229. EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
  230. EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
  231. EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
  232. EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
  233. }
  234. // Verifies that GetTestTypeId() returns the same value, no matter it
  235. // is called from inside Google Test or outside of it.
  236. TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
  237. EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
  238. }
  239. // Tests FormatTimeInMillisAsSeconds().
  240. TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
  241. EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
  242. }
  243. TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
  244. EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
  245. EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
  246. EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
  247. EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
  248. EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
  249. }
  250. TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
  251. EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
  252. EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
  253. EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
  254. EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
  255. EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
  256. }
  257. #if GTEST_CAN_COMPARE_NULL
  258. #ifdef __BORLANDC__
  259. // Silences warnings: "Condition is always true", "Unreachable code"
  260. #pragma option push -w-ccc -w-rch
  261. #endif
  262. // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null
  263. // pointer literal.
  264. TEST(NullLiteralTest, IsTrueForNullLiterals) {
  265. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL));
  266. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0));
  267. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U));
  268. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L));
  269. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(false));
  270. #ifndef __BORLANDC__
  271. // Some compilers may fail to detect some null pointer literals;
  272. // as long as users of the framework don't use such literals, this
  273. // is harmless.
  274. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(1 - 1));
  275. EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(true && false));
  276. #endif
  277. }
  278. // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null
  279. // pointer literal.
  280. TEST(NullLiteralTest, IsFalseForNonNullLiterals) {
  281. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1));
  282. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0));
  283. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a'));
  284. EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL)));
  285. }
  286. #ifdef __BORLANDC__
  287. // Restores warnings after previous "#pragma option push" suppressed them.
  288. #pragma option pop
  289. #endif
  290. #endif // GTEST_CAN_COMPARE_NULL
  291. //
  292. // Tests CodePointToUtf8().
  293. // Tests that the NUL character L'\0' is encoded correctly.
  294. TEST(CodePointToUtf8Test, CanEncodeNul) {
  295. char buffer[32];
  296. EXPECT_STREQ("", CodePointToUtf8(L'\0', buffer));
  297. }
  298. // Tests that ASCII characters are encoded correctly.
  299. TEST(CodePointToUtf8Test, CanEncodeAscii) {
  300. char buffer[32];
  301. EXPECT_STREQ("a", CodePointToUtf8(L'a', buffer));
  302. EXPECT_STREQ("Z", CodePointToUtf8(L'Z', buffer));
  303. EXPECT_STREQ("&", CodePointToUtf8(L'&', buffer));
  304. EXPECT_STREQ("\x7F", CodePointToUtf8(L'\x7F', buffer));
  305. }
  306. // Tests that Unicode code-points that have 8 to 11 bits are encoded
  307. // as 110xxxxx 10xxxxxx.
  308. TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
  309. char buffer[32];
  310. // 000 1101 0011 => 110-00011 10-010011
  311. EXPECT_STREQ("\xC3\x93", CodePointToUtf8(L'\xD3', buffer));
  312. // 101 0111 0110 => 110-10101 10-110110
  313. EXPECT_STREQ("\xD5\xB6", CodePointToUtf8(L'\x576', buffer));
  314. }
  315. // Tests that Unicode code-points that have 12 to 16 bits are encoded
  316. // as 1110xxxx 10xxxxxx 10xxxxxx.
  317. TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
  318. char buffer[32];
  319. // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
  320. EXPECT_STREQ("\xE0\xA3\x93", CodePointToUtf8(L'\x8D3', buffer));
  321. // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
  322. EXPECT_STREQ("\xEC\x9D\x8D", CodePointToUtf8(L'\xC74D', buffer));
  323. }
  324. #if !GTEST_WIDE_STRING_USES_UTF16_
  325. // Tests in this group require a wchar_t to hold > 16 bits, and thus
  326. // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is
  327. // 16-bit wide. This code may not compile on those systems.
  328. // Tests that Unicode code-points that have 17 to 21 bits are encoded
  329. // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
  330. TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
  331. char buffer[32];
  332. // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
  333. EXPECT_STREQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3', buffer));
  334. // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
  335. EXPECT_STREQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400', buffer));
  336. // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
  337. EXPECT_STREQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634', buffer));
  338. }
  339. // Tests that encoding an invalid code-point generates the expected result.
  340. TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
  341. char buffer[32];
  342. EXPECT_STREQ("(Invalid Unicode 0x1234ABCD)",
  343. CodePointToUtf8(L'\x1234ABCD', buffer));
  344. }
  345. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  346. // Tests WideStringToUtf8().
  347. // Tests that the NUL character L'\0' is encoded correctly.
  348. TEST(WideStringToUtf8Test, CanEncodeNul) {
  349. EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
  350. EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
  351. }
  352. // Tests that ASCII strings are encoded correctly.
  353. TEST(WideStringToUtf8Test, CanEncodeAscii) {
  354. EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
  355. EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
  356. EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
  357. EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
  358. }
  359. // Tests that Unicode code-points that have 8 to 11 bits are encoded
  360. // as 110xxxxx 10xxxxxx.
  361. TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
  362. // 000 1101 0011 => 110-00011 10-010011
  363. EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
  364. EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
  365. // 101 0111 0110 => 110-10101 10-110110
  366. EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", 1).c_str());
  367. EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(L"\x576", -1).c_str());
  368. }
  369. // Tests that Unicode code-points that have 12 to 16 bits are encoded
  370. // as 1110xxxx 10xxxxxx 10xxxxxx.
  371. TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
  372. // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
  373. EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", 1).c_str());
  374. EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(L"\x8D3", -1).c_str());
  375. // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
  376. EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", 1).c_str());
  377. EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(L"\xC74D", -1).c_str());
  378. }
  379. // Tests that the conversion stops when the function encounters \0 character.
  380. TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
  381. EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
  382. }
  383. // Tests that the conversion stops when the function reaches the limit
  384. // specified by the 'length' parameter.
  385. TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
  386. EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
  387. }
  388. #if !GTEST_WIDE_STRING_USES_UTF16_
  389. // Tests that Unicode code-points that have 17 to 21 bits are encoded
  390. // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
  391. // on the systems using UTF-16 encoding.
  392. TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
  393. // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
  394. EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
  395. EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
  396. // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
  397. EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
  398. EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
  399. }
  400. // Tests that encoding an invalid code-point generates the expected result.
  401. TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
  402. EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
  403. WideStringToUtf8(L"\xABCDFF", -1).c_str());
  404. }
  405. #else // !GTEST_WIDE_STRING_USES_UTF16_
  406. // Tests that surrogate pairs are encoded correctly on the systems using
  407. // UTF-16 encoding in the wide strings.
  408. TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
  409. EXPECT_STREQ("\xF0\x90\x90\x80",
  410. WideStringToUtf8(L"\xD801\xDC00", -1).c_str());
  411. }
  412. // Tests that encoding an invalid UTF-16 surrogate pair
  413. // generates the expected result.
  414. TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
  415. // Leading surrogate is at the end of the string.
  416. EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(L"\xD800", -1).c_str());
  417. // Leading surrogate is not followed by the trailing surrogate.
  418. EXPECT_STREQ("\xED\xA0\x80$", WideStringToUtf8(L"\xD800$", -1).c_str());
  419. // Trailing surrogate appearas without a leading surrogate.
  420. EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(L"\xDC00PQR", -1).c_str());
  421. }
  422. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  423. // Tests that codepoint concatenation works correctly.
  424. #if !GTEST_WIDE_STRING_USES_UTF16_
  425. TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
  426. EXPECT_STREQ(
  427. "\xF4\x88\x98\xB4"
  428. "\xEC\x9D\x8D"
  429. "\n"
  430. "\xD5\xB6"
  431. "\xE0\xA3\x93"
  432. "\xF4\x88\x98\xB4",
  433. WideStringToUtf8(L"\x108634\xC74D\n\x576\x8D3\x108634", -1).c_str());
  434. }
  435. #else
  436. TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
  437. EXPECT_STREQ(
  438. "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
  439. WideStringToUtf8(L"\xC74D\n\x576\x8D3", -1).c_str());
  440. }
  441. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  442. // Tests the Random class.
  443. TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
  444. testing::internal::Random random(42);
  445. EXPECT_DEATH_IF_SUPPORTED(
  446. random.Generate(0),
  447. "Cannot generate a number in the range \\[0, 0\\)");
  448. EXPECT_DEATH_IF_SUPPORTED(
  449. random.Generate(testing::internal::Random::kMaxRange + 1),
  450. "Generation of a number in \\[0, 2147483649\\) was requested, "
  451. "but this can only generate numbers in \\[0, 2147483648\\)");
  452. }
  453. TEST(RandomTest, GeneratesNumbersWithinRange) {
  454. const UInt32 kRange = 10000;
  455. testing::internal::Random random(12345);
  456. for (int i = 0; i < 10; i++) {
  457. EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
  458. }
  459. testing::internal::Random random2(testing::internal::Random::kMaxRange);
  460. for (int i = 0; i < 10; i++) {
  461. EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
  462. }
  463. }
  464. TEST(RandomTest, RepeatsWhenReseeded) {
  465. const int kSeed = 123;
  466. const int kArraySize = 10;
  467. const UInt32 kRange = 10000;
  468. UInt32 values[kArraySize];
  469. testing::internal::Random random(kSeed);
  470. for (int i = 0; i < kArraySize; i++) {
  471. values[i] = random.Generate(kRange);
  472. }
  473. random.Reseed(kSeed);
  474. for (int i = 0; i < kArraySize; i++) {
  475. EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
  476. }
  477. }
  478. // Tests STL container utilities.
  479. // Tests CountIf().
  480. static bool IsPositive(int n) { return n > 0; }
  481. TEST(ContainerUtilityTest, CountIf) {
  482. std::vector<int> v;
  483. EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
  484. v.push_back(-1);
  485. v.push_back(0);
  486. EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
  487. v.push_back(2);
  488. v.push_back(-10);
  489. v.push_back(10);
  490. EXPECT_EQ(2, CountIf(v, IsPositive));
  491. }
  492. // Tests ForEach().
  493. static int g_sum = 0;
  494. static void Accumulate(int n) { g_sum += n; }
  495. TEST(ContainerUtilityTest, ForEach) {
  496. std::vector<int> v;
  497. g_sum = 0;
  498. ForEach(v, Accumulate);
  499. EXPECT_EQ(0, g_sum); // Works for an empty container;
  500. g_sum = 0;
  501. v.push_back(1);
  502. ForEach(v, Accumulate);
  503. EXPECT_EQ(1, g_sum); // Works for a container with one element.
  504. g_sum = 0;
  505. v.push_back(20);
  506. v.push_back(300);
  507. ForEach(v, Accumulate);
  508. EXPECT_EQ(321, g_sum);
  509. }
  510. // Tests GetElementOr().
  511. TEST(ContainerUtilityTest, GetElementOr) {
  512. std::vector<char> a;
  513. EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
  514. a.push_back('a');
  515. a.push_back('b');
  516. EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
  517. EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
  518. EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
  519. EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
  520. }
  521. TEST(ContainerUtilityDeathTest, ShuffleRange) {
  522. std::vector<int> a;
  523. a.push_back(0);
  524. a.push_back(1);
  525. a.push_back(2);
  526. testing::internal::Random random(1);
  527. EXPECT_DEATH_IF_SUPPORTED(
  528. ShuffleRange(&random, -1, 1, &a),
  529. "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
  530. EXPECT_DEATH_IF_SUPPORTED(
  531. ShuffleRange(&random, 4, 4, &a),
  532. "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
  533. EXPECT_DEATH_IF_SUPPORTED(
  534. ShuffleRange(&random, 3, 2, &a),
  535. "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
  536. EXPECT_DEATH_IF_SUPPORTED(
  537. ShuffleRange(&random, 3, 4, &a),
  538. "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
  539. }
  540. class VectorShuffleTest : public Test {
  541. protected:
  542. static const int kVectorSize = 20;
  543. VectorShuffleTest() : random_(1) {
  544. for (int i = 0; i < kVectorSize; i++) {
  545. vector_.push_back(i);
  546. }
  547. }
  548. static bool VectorIsCorrupt(const TestingVector& vector) {
  549. if (kVectorSize != static_cast<int>(vector.size())) {
  550. return true;
  551. }
  552. bool found_in_vector[kVectorSize] = { false };
  553. for (size_t i = 0; i < vector.size(); i++) {
  554. const int e = vector[i];
  555. if (e < 0 || e >= kVectorSize || found_in_vector[e]) {
  556. return true;
  557. }
  558. found_in_vector[e] = true;
  559. }
  560. // Vector size is correct, elements' range is correct, no
  561. // duplicate elements. Therefore no corruption has occurred.
  562. return false;
  563. }
  564. static bool VectorIsNotCorrupt(const TestingVector& vector) {
  565. return !VectorIsCorrupt(vector);
  566. }
  567. static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
  568. for (int i = begin; i < end; i++) {
  569. if (i != vector[i]) {
  570. return true;
  571. }
  572. }
  573. return false;
  574. }
  575. static bool RangeIsUnshuffled(
  576. const TestingVector& vector, int begin, int end) {
  577. return !RangeIsShuffled(vector, begin, end);
  578. }
  579. static bool VectorIsShuffled(const TestingVector& vector) {
  580. return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
  581. }
  582. static bool VectorIsUnshuffled(const TestingVector& vector) {
  583. return !VectorIsShuffled(vector);
  584. }
  585. testing::internal::Random random_;
  586. TestingVector vector_;
  587. }; // class VectorShuffleTest
  588. const int VectorShuffleTest::kVectorSize;
  589. TEST_F(VectorShuffleTest, HandlesEmptyRange) {
  590. // Tests an empty range at the beginning...
  591. ShuffleRange(&random_, 0, 0, &vector_);
  592. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  593. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  594. // ...in the middle...
  595. ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
  596. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  597. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  598. // ...at the end...
  599. ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
  600. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  601. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  602. // ...and past the end.
  603. ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
  604. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  605. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  606. }
  607. TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
  608. // Tests a size one range at the beginning...
  609. ShuffleRange(&random_, 0, 1, &vector_);
  610. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  611. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  612. // ...in the middle...
  613. ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
  614. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  615. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  616. // ...and at the end.
  617. ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
  618. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  619. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  620. }
  621. // Because we use our own random number generator and a fixed seed,
  622. // we can guarantee that the following "random" tests will succeed.
  623. TEST_F(VectorShuffleTest, ShufflesEntireVector) {
  624. Shuffle(&random_, &vector_);
  625. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  626. EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
  627. // Tests the first and last elements in particular to ensure that
  628. // there are no off-by-one problems in our shuffle algorithm.
  629. EXPECT_NE(0, vector_[0]);
  630. EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]);
  631. }
  632. TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
  633. const int kRangeSize = kVectorSize/2;
  634. ShuffleRange(&random_, 0, kRangeSize, &vector_);
  635. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  636. EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
  637. EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize);
  638. }
  639. TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
  640. const int kRangeSize = kVectorSize / 2;
  641. ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
  642. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  643. EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
  644. EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize);
  645. }
  646. TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
  647. int kRangeSize = kVectorSize/3;
  648. ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
  649. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  650. EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
  651. EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
  652. EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize);
  653. }
  654. TEST_F(VectorShuffleTest, ShufflesRepeatably) {
  655. TestingVector vector2;
  656. for (int i = 0; i < kVectorSize; i++) {
  657. vector2.push_back(i);
  658. }
  659. random_.Reseed(1234);
  660. Shuffle(&random_, &vector_);
  661. random_.Reseed(1234);
  662. Shuffle(&random_, &vector2);
  663. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  664. ASSERT_PRED1(VectorIsNotCorrupt, vector2);
  665. for (int i = 0; i < kVectorSize; i++) {
  666. EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
  667. }
  668. }
  669. // Tests the size of the AssertHelper class.
  670. TEST(AssertHelperTest, AssertHelperIsSmall) {
  671. // To avoid breaking clients that use lots of assertions in one
  672. // function, we cannot grow the size of AssertHelper.
  673. EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
  674. }
  675. // Tests the String class.
  676. // Tests String's constructors.
  677. TEST(StringTest, Constructors) {
  678. // Default ctor.
  679. String s1;
  680. // We aren't using EXPECT_EQ(NULL, s1.c_str()) because comparing
  681. // pointers with NULL isn't supported on all platforms.
  682. EXPECT_EQ(0U, s1.length());
  683. EXPECT_TRUE(NULL == s1.c_str());
  684. // Implicitly constructs from a C-string.
  685. String s2 = "Hi";
  686. EXPECT_EQ(2U, s2.length());
  687. EXPECT_STREQ("Hi", s2.c_str());
  688. // Constructs from a C-string and a length.
  689. String s3("hello", 3);
  690. EXPECT_EQ(3U, s3.length());
  691. EXPECT_STREQ("hel", s3.c_str());
  692. // The empty String should be created when String is constructed with
  693. // a NULL pointer and length 0.
  694. EXPECT_EQ(0U, String(NULL, 0).length());
  695. EXPECT_FALSE(String(NULL, 0).c_str() == NULL);
  696. // Constructs a String that contains '\0'.
  697. String s4("a\0bcd", 4);
  698. EXPECT_EQ(4U, s4.length());
  699. EXPECT_EQ('a', s4.c_str()[0]);
  700. EXPECT_EQ('\0', s4.c_str()[1]);
  701. EXPECT_EQ('b', s4.c_str()[2]);
  702. EXPECT_EQ('c', s4.c_str()[3]);
  703. // Copy ctor where the source is NULL.
  704. const String null_str;
  705. String s5 = null_str;
  706. EXPECT_TRUE(s5.c_str() == NULL);
  707. // Copy ctor where the source isn't NULL.
  708. String s6 = s3;
  709. EXPECT_EQ(3U, s6.length());
  710. EXPECT_STREQ("hel", s6.c_str());
  711. // Copy ctor where the source contains '\0'.
  712. String s7 = s4;
  713. EXPECT_EQ(4U, s7.length());
  714. EXPECT_EQ('a', s7.c_str()[0]);
  715. EXPECT_EQ('\0', s7.c_str()[1]);
  716. EXPECT_EQ('b', s7.c_str()[2]);
  717. EXPECT_EQ('c', s7.c_str()[3]);
  718. }
  719. TEST(StringTest, ConvertsFromStdString) {
  720. // An empty std::string.
  721. const std::string src1("");
  722. const String dest1 = src1;
  723. EXPECT_EQ(0U, dest1.length());
  724. EXPECT_STREQ("", dest1.c_str());
  725. // A normal std::string.
  726. const std::string src2("Hi");
  727. const String dest2 = src2;
  728. EXPECT_EQ(2U, dest2.length());
  729. EXPECT_STREQ("Hi", dest2.c_str());
  730. // An std::string with an embedded NUL character.
  731. const char src3[] = "a\0b";
  732. const String dest3 = std::string(src3, sizeof(src3));
  733. EXPECT_EQ(sizeof(src3), dest3.length());
  734. EXPECT_EQ('a', dest3.c_str()[0]);
  735. EXPECT_EQ('\0', dest3.c_str()[1]);
  736. EXPECT_EQ('b', dest3.c_str()[2]);
  737. }
  738. TEST(StringTest, ConvertsToStdString) {
  739. // An empty String.
  740. const String src1("");
  741. const std::string dest1 = src1;
  742. EXPECT_EQ("", dest1);
  743. // A normal String.
  744. const String src2("Hi");
  745. const std::string dest2 = src2;
  746. EXPECT_EQ("Hi", dest2);
  747. // A String containing a '\0'.
  748. const String src3("x\0y", 3);
  749. const std::string dest3 = src3;
  750. EXPECT_EQ(std::string("x\0y", 3), dest3);
  751. }
  752. #if GTEST_HAS_GLOBAL_STRING
  753. TEST(StringTest, ConvertsFromGlobalString) {
  754. // An empty ::string.
  755. const ::string src1("");
  756. const String dest1 = src1;
  757. EXPECT_EQ(0U, dest1.length());
  758. EXPECT_STREQ("", dest1.c_str());
  759. // A normal ::string.
  760. const ::string src2("Hi");
  761. const String dest2 = src2;
  762. EXPECT_EQ(2U, dest2.length());
  763. EXPECT_STREQ("Hi", dest2.c_str());
  764. // An ::string with an embedded NUL character.
  765. const char src3[] = "x\0y";
  766. const String dest3 = ::string(src3, sizeof(src3));
  767. EXPECT_EQ(sizeof(src3), dest3.length());
  768. EXPECT_EQ('x', dest3.c_str()[0]);
  769. EXPECT_EQ('\0', dest3.c_str()[1]);
  770. EXPECT_EQ('y', dest3.c_str()[2]);
  771. }
  772. TEST(StringTest, ConvertsToGlobalString) {
  773. // An empty String.
  774. const String src1("");
  775. const ::string dest1 = src1;
  776. EXPECT_EQ("", dest1);
  777. // A normal String.
  778. const String src2("Hi");
  779. const ::string dest2 = src2;
  780. EXPECT_EQ("Hi", dest2);
  781. const String src3("x\0y", 3);
  782. const ::string dest3 = src3;
  783. EXPECT_EQ(::string("x\0y", 3), dest3);
  784. }
  785. #endif // GTEST_HAS_GLOBAL_STRING
  786. // Tests String::ShowCStringQuoted().
  787. TEST(StringTest, ShowCStringQuoted) {
  788. EXPECT_STREQ("(null)",
  789. String::ShowCStringQuoted(NULL).c_str());
  790. EXPECT_STREQ("\"\"",
  791. String::ShowCStringQuoted("").c_str());
  792. EXPECT_STREQ("\"foo\"",
  793. String::ShowCStringQuoted("foo").c_str());
  794. }
  795. // Tests String::empty().
  796. TEST(StringTest, Empty) {
  797. EXPECT_TRUE(String("").empty());
  798. EXPECT_FALSE(String().empty());
  799. EXPECT_FALSE(String(NULL).empty());
  800. EXPECT_FALSE(String("a").empty());
  801. EXPECT_FALSE(String("\0", 1).empty());
  802. }
  803. // Tests String::Compare().
  804. TEST(StringTest, Compare) {
  805. // NULL vs NULL.
  806. EXPECT_EQ(0, String().Compare(String()));
  807. // NULL vs non-NULL.
  808. EXPECT_EQ(-1, String().Compare(String("")));
  809. // Non-NULL vs NULL.
  810. EXPECT_EQ(1, String("").Compare(String()));
  811. // The following covers non-NULL vs non-NULL.
  812. // "" vs "".
  813. EXPECT_EQ(0, String("").Compare(String("")));
  814. // "" vs non-"".
  815. EXPECT_EQ(-1, String("").Compare(String("\0", 1)));
  816. EXPECT_EQ(-1, String("").Compare(" "));
  817. // Non-"" vs "".
  818. EXPECT_EQ(1, String("a").Compare(String("")));
  819. // The following covers non-"" vs non-"".
  820. // Same length and equal.
  821. EXPECT_EQ(0, String("a").Compare(String("a")));
  822. // Same length and different.
  823. EXPECT_EQ(-1, String("a\0b", 3).Compare(String("a\0c", 3)));
  824. EXPECT_EQ(1, String("b").Compare(String("a")));
  825. // Different lengths.
  826. EXPECT_EQ(-1, String("a").Compare(String("ab")));
  827. EXPECT_EQ(-1, String("a").Compare(String("a\0", 2)));
  828. EXPECT_EQ(1, String("abc").Compare(String("aacd")));
  829. }
  830. // Tests String::operator==().
  831. TEST(StringTest, Equals) {
  832. const String null(NULL);
  833. EXPECT_TRUE(null == NULL); // NOLINT
  834. EXPECT_FALSE(null == ""); // NOLINT
  835. EXPECT_FALSE(null == "bar"); // NOLINT
  836. const String empty("");
  837. EXPECT_FALSE(empty == NULL); // NOLINT
  838. EXPECT_TRUE(empty == ""); // NOLINT
  839. EXPECT_FALSE(empty == "bar"); // NOLINT
  840. const String foo("foo");
  841. EXPECT_FALSE(foo == NULL); // NOLINT
  842. EXPECT_FALSE(foo == ""); // NOLINT
  843. EXPECT_FALSE(foo == "bar"); // NOLINT
  844. EXPECT_TRUE(foo == "foo"); // NOLINT
  845. const String bar("x\0y", 3);
  846. EXPECT_FALSE(bar == "x");
  847. }
  848. // Tests String::operator!=().
  849. TEST(StringTest, NotEquals) {
  850. const String null(NULL);
  851. EXPECT_FALSE(null != NULL); // NOLINT
  852. EXPECT_TRUE(null != ""); // NOLINT
  853. EXPECT_TRUE(null != "bar"); // NOLINT
  854. const String empty("");
  855. EXPECT_TRUE(empty != NULL); // NOLINT
  856. EXPECT_FALSE(empty != ""); // NOLINT
  857. EXPECT_TRUE(empty != "bar"); // NOLINT
  858. const String foo("foo");
  859. EXPECT_TRUE(foo != NULL); // NOLINT
  860. EXPECT_TRUE(foo != ""); // NOLINT
  861. EXPECT_TRUE(foo != "bar"); // NOLINT
  862. EXPECT_FALSE(foo != "foo"); // NOLINT
  863. const String bar("x\0y", 3);
  864. EXPECT_TRUE(bar != "x");
  865. }
  866. // Tests String::length().
  867. TEST(StringTest, Length) {
  868. EXPECT_EQ(0U, String().length());
  869. EXPECT_EQ(0U, String("").length());
  870. EXPECT_EQ(2U, String("ab").length());
  871. EXPECT_EQ(3U, String("a\0b", 3).length());
  872. }
  873. // Tests String::EndsWith().
  874. TEST(StringTest, EndsWith) {
  875. EXPECT_TRUE(String("foobar").EndsWith("bar"));
  876. EXPECT_TRUE(String("foobar").EndsWith(""));
  877. EXPECT_TRUE(String("").EndsWith(""));
  878. EXPECT_FALSE(String("foobar").EndsWith("foo"));
  879. EXPECT_FALSE(String("").EndsWith("foo"));
  880. }
  881. // Tests String::EndsWithCaseInsensitive().
  882. TEST(StringTest, EndsWithCaseInsensitive) {
  883. EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive("BAR"));
  884. EXPECT_TRUE(String("foobaR").EndsWithCaseInsensitive("bar"));
  885. EXPECT_TRUE(String("foobar").EndsWithCaseInsensitive(""));
  886. EXPECT_TRUE(String("").EndsWithCaseInsensitive(""));
  887. EXPECT_FALSE(String("Foobar").EndsWithCaseInsensitive("foo"));
  888. EXPECT_FALSE(String("foobar").EndsWithCaseInsensitive("Foo"));
  889. EXPECT_FALSE(String("").EndsWithCaseInsensitive("foo"));
  890. }
  891. // C++Builder's preprocessor is buggy; it fails to expand macros that
  892. // appear in macro parameters after wide char literals. Provide an alias
  893. // for NULL as a workaround.
  894. static const wchar_t* const kNull = NULL;
  895. // Tests String::CaseInsensitiveWideCStringEquals
  896. TEST(StringTest, CaseInsensitiveWideCStringEquals) {
  897. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL));
  898. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
  899. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
  900. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
  901. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
  902. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
  903. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
  904. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
  905. }
  906. // Tests that NULL can be assigned to a String.
  907. TEST(StringTest, CanBeAssignedNULL) {
  908. const String src(NULL);
  909. String dest;
  910. dest = src;
  911. EXPECT_STREQ(NULL, dest.c_str());
  912. }
  913. // Tests that the empty string "" can be assigned to a String.
  914. TEST(StringTest, CanBeAssignedEmpty) {
  915. const String src("");
  916. String dest;
  917. dest = src;
  918. EXPECT_STREQ("", dest.c_str());
  919. }
  920. // Tests that a non-empty string can be assigned to a String.
  921. TEST(StringTest, CanBeAssignedNonEmpty) {
  922. const String src("hello");
  923. String dest;
  924. dest = src;
  925. EXPECT_EQ(5U, dest.length());
  926. EXPECT_STREQ("hello", dest.c_str());
  927. const String src2("x\0y", 3);
  928. String dest2;
  929. dest2 = src2;
  930. EXPECT_EQ(3U, dest2.length());
  931. EXPECT_EQ('x', dest2.c_str()[0]);
  932. EXPECT_EQ('\0', dest2.c_str()[1]);
  933. EXPECT_EQ('y', dest2.c_str()[2]);
  934. }
  935. // Tests that a String can be assigned to itself.
  936. TEST(StringTest, CanBeAssignedSelf) {
  937. String dest("hello");
  938. dest = dest;
  939. EXPECT_STREQ("hello", dest.c_str());
  940. }
  941. // Sun Studio < 12 incorrectly rejects this code due to an overloading
  942. // ambiguity.
  943. #if !(defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
  944. // Tests streaming a String.
  945. TEST(StringTest, Streams) {
  946. EXPECT_EQ(StreamableToString(String()), "(null)");
  947. EXPECT_EQ(StreamableToString(String("")), "");
  948. EXPECT_EQ(StreamableToString(String("a\0b", 3)), "a\\0b");
  949. }
  950. #endif
  951. // Tests that String::Format() works.
  952. TEST(StringTest, FormatWorks) {
  953. // Normal case: the format spec is valid, the arguments match the
  954. // spec, and the result is < 4095 characters.
  955. EXPECT_STREQ("Hello, 42", String::Format("%s, %d", "Hello", 42).c_str());
  956. // Edge case: the result is 4095 characters.
  957. char buffer[4096];
  958. const size_t kSize = sizeof(buffer);
  959. memset(buffer, 'a', kSize - 1);
  960. buffer[kSize - 1] = '\0';
  961. EXPECT_STREQ(buffer, String::Format("%s", buffer).c_str());
  962. // The result needs to be 4096 characters, exceeding Format()'s limit.
  963. EXPECT_STREQ("<formatting error or buffer exceeded>",
  964. String::Format("x%s", buffer).c_str());
  965. #if GTEST_OS_LINUX
  966. // On Linux, invalid format spec should lead to an error message.
  967. // In other environment (e.g. MSVC on Windows), String::Format() may
  968. // simply ignore a bad format spec, so this assertion is run on
  969. // Linux only.
  970. EXPECT_STREQ("<formatting error or buffer exceeded>",
  971. String::Format("%").c_str());
  972. #endif
  973. }
  974. #if GTEST_OS_WINDOWS
  975. // Tests String::ShowWideCString().
  976. TEST(StringTest, ShowWideCString) {
  977. EXPECT_STREQ("(null)",
  978. String::ShowWideCString(NULL).c_str());
  979. EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
  980. EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
  981. }
  982. // Tests String::ShowWideCStringQuoted().
  983. TEST(StringTest, ShowWideCStringQuoted) {
  984. EXPECT_STREQ("(null)",
  985. String::ShowWideCStringQuoted(NULL).c_str());
  986. EXPECT_STREQ("L\"\"",
  987. String::ShowWideCStringQuoted(L"").c_str());
  988. EXPECT_STREQ("L\"foo\"",
  989. String::ShowWideCStringQuoted(L"foo").c_str());
  990. }
  991. #if GTEST_OS_WINDOWS_MOBILE
  992. TEST(StringTest, AnsiAndUtf16Null) {
  993. EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
  994. EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
  995. }
  996. TEST(StringTest, AnsiAndUtf16ConvertBasic) {
  997. const char* ansi = String::Utf16ToAnsi(L"str");
  998. EXPECT_STREQ("str", ansi);
  999. delete [] ansi;
  1000. const WCHAR* utf16 = String::AnsiToUtf16("str");
  1001. EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
  1002. delete [] utf16;
  1003. }
  1004. TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
  1005. const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
  1006. EXPECT_STREQ(".:\\ \"*?", ansi);
  1007. delete [] ansi;
  1008. const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
  1009. EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
  1010. delete [] utf16;
  1011. }
  1012. #endif // GTEST_OS_WINDOWS_MOBILE
  1013. #endif // GTEST_OS_WINDOWS
  1014. // Tests TestProperty construction.
  1015. TEST(TestPropertyTest, StringValue) {
  1016. TestProperty property("key", "1");
  1017. EXPECT_STREQ("key", property.key());
  1018. EXPECT_STREQ("1", property.value());
  1019. }
  1020. // Tests TestProperty replacing a value.
  1021. TEST(TestPropertyTest, ReplaceStringValue) {
  1022. TestProperty property("key", "1");
  1023. EXPECT_STREQ("1", property.value());
  1024. property.SetValue("2");
  1025. EXPECT_STREQ("2", property.value());
  1026. }
  1027. // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
  1028. // functions (i.e. their definitions cannot be inlined at the call
  1029. // sites), or C++Builder won't compile the code.
  1030. static void AddFatalFailure() {
  1031. FAIL() << "Expected fatal failure.";
  1032. }
  1033. static void AddNonfatalFailure() {
  1034. ADD_FAILURE() << "Expected non-fatal failure.";
  1035. }
  1036. class ScopedFakeTestPartResultReporterTest : public Test {
  1037. public: // Must be public and not protected due to a bug in g++ 3.4.2.
  1038. enum FailureMode {
  1039. FATAL_FAILURE,
  1040. NONFATAL_FAILURE
  1041. };
  1042. static void AddFailure(FailureMode failure) {
  1043. if (failure == FATAL_FAILURE) {
  1044. AddFatalFailure();
  1045. } else {
  1046. AddNonfatalFailure();
  1047. }
  1048. }
  1049. };
  1050. // Tests that ScopedFakeTestPartResultReporter intercepts test
  1051. // failures.
  1052. TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
  1053. TestPartResultArray results;
  1054. {
  1055. ScopedFakeTestPartResultReporter reporter(
  1056. ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
  1057. &results);
  1058. AddFailure(NONFATAL_FAILURE);
  1059. AddFailure(FATAL_FAILURE);
  1060. }
  1061. EXPECT_EQ(2, results.size());
  1062. EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
  1063. EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
  1064. }
  1065. TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
  1066. TestPartResultArray results;
  1067. {
  1068. // Tests, that the deprecated constructor still works.
  1069. ScopedFakeTestPartResultReporter reporter(&results);
  1070. AddFailure(NONFATAL_FAILURE);
  1071. }
  1072. EXPECT_EQ(1, results.size());
  1073. }
  1074. #if GTEST_IS_THREADSAFE
  1075. class ScopedFakeTestPartResultReporterWithThreadsTest
  1076. : public ScopedFakeTestPartResultReporterTest {
  1077. protected:
  1078. static void AddFailureInOtherThread(FailureMode failure) {
  1079. ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
  1080. thread.Join();
  1081. }
  1082. };
  1083. TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
  1084. InterceptsTestFailuresInAllThreads) {
  1085. TestPartResultArray results;
  1086. {
  1087. ScopedFakeTestPartResultReporter reporter(
  1088. ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
  1089. AddFailure(NONFATAL_FAILURE);
  1090. AddFailure(FATAL_FAILURE);
  1091. AddFailureInOtherThread(NONFATAL_FAILURE);
  1092. AddFailureInOtherThread(FATAL_FAILURE);
  1093. }
  1094. EXPECT_EQ(4, results.size());
  1095. EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
  1096. EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
  1097. EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
  1098. EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
  1099. }
  1100. #endif // GTEST_IS_THREADSAFE
  1101. // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
  1102. // work even if the failure is generated in a called function rather than
  1103. // the current context.
  1104. typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
  1105. TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
  1106. EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
  1107. }
  1108. TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
  1109. // We have another test below to verify that the macro catches fatal
  1110. // failures generated on another thread.
  1111. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
  1112. "Expected fatal failure.");
  1113. }
  1114. #ifdef __BORLANDC__
  1115. // Silences warnings: "Condition is always true"
  1116. #pragma option push -w-ccc
  1117. #endif
  1118. // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
  1119. // function even when the statement in it contains ASSERT_*.
  1120. int NonVoidFunction() {
  1121. EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
  1122. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
  1123. return 0;
  1124. }
  1125. TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
  1126. NonVoidFunction();
  1127. }
  1128. // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
  1129. // current function even though 'statement' generates a fatal failure.
  1130. void DoesNotAbortHelper(bool* aborted) {
  1131. EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
  1132. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
  1133. *aborted = false;
  1134. }
  1135. #ifdef __BORLANDC__
  1136. // Restores warnings after previous "#pragma option push" suppressed them.
  1137. #pragma option pop
  1138. #endif
  1139. TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
  1140. bool aborted = true;
  1141. DoesNotAbortHelper(&aborted);
  1142. EXPECT_FALSE(aborted);
  1143. }
  1144. // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
  1145. // statement that contains a macro which expands to code containing an
  1146. // unprotected comma.
  1147. static int global_var = 0;
  1148. #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
  1149. TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
  1150. #if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600
  1151. // ICE's in C++Builder 2007.
  1152. EXPECT_FATAL_FAILURE({
  1153. GTEST_USE_UNPROTECTED_COMMA_;
  1154. AddFatalFailure();
  1155. }, "");
  1156. #endif
  1157. EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
  1158. GTEST_USE_UNPROTECTED_COMMA_;
  1159. AddFatalFailure();
  1160. }, "");
  1161. }
  1162. // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
  1163. typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
  1164. TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
  1165. EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
  1166. "Expected non-fatal failure.");
  1167. }
  1168. TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
  1169. // We have another test below to verify that the macro catches
  1170. // non-fatal failures generated on another thread.
  1171. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
  1172. "Expected non-fatal failure.");
  1173. }
  1174. // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
  1175. // statement that contains a macro which expands to code containing an
  1176. // unprotected comma.
  1177. TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
  1178. EXPECT_NONFATAL_FAILURE({
  1179. GTEST_USE_UNPROTECTED_COMMA_;
  1180. AddNonfatalFailure();
  1181. }, "");
  1182. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
  1183. GTEST_USE_UNPROTECTED_COMMA_;
  1184. AddNonfatalFailure();
  1185. }, "");
  1186. }
  1187. #if GTEST_IS_THREADSAFE
  1188. typedef ScopedFakeTestPartResultReporterWithThreadsTest
  1189. ExpectFailureWithThreadsTest;
  1190. TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
  1191. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
  1192. "Expected fatal failure.");
  1193. }
  1194. TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
  1195. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
  1196. AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
  1197. }
  1198. #endif // GTEST_IS_THREADSAFE
  1199. // Tests the TestProperty class.
  1200. TEST(TestPropertyTest, ConstructorWorks) {
  1201. const TestProperty property("key", "value");
  1202. EXPECT_STREQ("key", property.key());
  1203. EXPECT_STREQ("value", property.value());
  1204. }
  1205. TEST(TestPropertyTest, SetValue) {
  1206. TestProperty property("key", "value_1");
  1207. EXPECT_STREQ("key", property.key());
  1208. property.SetValue("value_2");
  1209. EXPECT_STREQ("key", property.key());
  1210. EXPECT_STREQ("value_2", property.value());
  1211. }
  1212. // Tests the TestResult class
  1213. // The test fixture for testing TestResult.
  1214. class TestResultTest : public Test {
  1215. protected:
  1216. typedef std::vector<TestPartResult> TPRVector;
  1217. // We make use of 2 TestPartResult objects,
  1218. TestPartResult * pr1, * pr2;
  1219. // ... and 3 TestResult objects.
  1220. TestResult * r0, * r1, * r2;
  1221. virtual void SetUp() {
  1222. // pr1 is for success.
  1223. pr1 = new TestPartResult(TestPartResult::kSuccess,
  1224. "foo/bar.cc",
  1225. 10,
  1226. "Success!");
  1227. // pr2 is for fatal failure.
  1228. pr2 = new TestPartResult(TestPartResult::kFatalFailure,
  1229. "foo/bar.cc",
  1230. -1, // This line number means "unknown"
  1231. "Failure!");
  1232. // Creates the TestResult objects.
  1233. r0 = new TestResult();
  1234. r1 = new TestResult();
  1235. r2 = new TestResult();
  1236. // In order to test TestResult, we need to modify its internal
  1237. // state, in particular the TestPartResult vector it holds.
  1238. // test_part_results() returns a const reference to this vector.
  1239. // We cast it to a non-const object s.t. it can be modified (yes,
  1240. // this is a hack).
  1241. TPRVector* results1 = const_cast<TPRVector*>(
  1242. &TestResultAccessor::test_part_results(*r1));
  1243. TPRVector* results2 = const_cast<TPRVector*>(
  1244. &TestResultAccessor::test_part_results(*r2));
  1245. // r0 is an empty TestResult.
  1246. // r1 contains a single SUCCESS TestPartResult.
  1247. results1->push_back(*pr1);
  1248. // r2 contains a SUCCESS, and a FAILURE.
  1249. results2->push_back(*pr1);
  1250. results2->push_back(*pr2);
  1251. }
  1252. virtual void TearDown() {
  1253. delete pr1;
  1254. delete pr2;
  1255. delete r0;
  1256. delete r1;
  1257. delete r2;
  1258. }
  1259. // Helper that compares two two TestPartResults.
  1260. static void CompareTestPartResult(const TestPartResult& expected,
  1261. const TestPartResult& actual) {
  1262. EXPECT_EQ(expected.type(), actual.type());
  1263. EXPECT_STREQ(expected.file_name(), actual.file_name());
  1264. EXPECT_EQ(expected.line_number(), actual.line_number());
  1265. EXPECT_STREQ(expected.summary(), actual.summary());
  1266. EXPECT_STREQ(expected.message(), actual.message());
  1267. EXPECT_EQ(expected.passed(), actual.passed());
  1268. EXPECT_EQ(expected.failed(), actual.failed());
  1269. EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
  1270. EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
  1271. }
  1272. };
  1273. // Tests TestResult::total_part_count().
  1274. TEST_F(TestResultTest, total_part_count) {
  1275. ASSERT_EQ(0, r0->total_part_count());
  1276. ASSERT_EQ(1, r1->total_part_count());
  1277. ASSERT_EQ(2, r2->total_part_count());
  1278. }
  1279. // Tests TestResult::Passed().
  1280. TEST_F(TestResultTest, Passed) {
  1281. ASSERT_TRUE(r0->Passed());
  1282. ASSERT_TRUE(r1->Passed());
  1283. ASSERT_FALSE(r2->Passed());
  1284. }
  1285. // Tests TestResult::Failed().
  1286. TEST_F(TestResultTest, Failed) {
  1287. ASSERT_FALSE(r0->Failed());
  1288. ASSERT_FALSE(r1->Failed());
  1289. ASSERT_TRUE(r2->Failed());
  1290. }
  1291. // Tests TestResult::GetTestPartResult().
  1292. typedef TestResultTest TestResultDeathTest;
  1293. TEST_F(TestResultDeathTest, GetTestPartResult) {
  1294. CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
  1295. CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
  1296. EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
  1297. EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
  1298. }
  1299. // Tests TestResult has no properties when none are added.
  1300. TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
  1301. TestResult test_result;
  1302. ASSERT_EQ(0, test_result.test_property_count());
  1303. }
  1304. // Tests TestResult has the expected property when added.
  1305. TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
  1306. TestResult test_result;
  1307. TestProperty property("key_1", "1");
  1308. TestResultAccessor::RecordProperty(&test_result, property);
  1309. ASSERT_EQ(1, test_result.test_property_count());
  1310. const TestProperty& actual_property = test_result.GetTestProperty(0);
  1311. EXPECT_STREQ("key_1", actual_property.key());
  1312. EXPECT_STREQ("1", actual_property.value());
  1313. }
  1314. // Tests TestResult has multiple properties when added.
  1315. TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
  1316. TestResult test_result;
  1317. TestProperty property_1("key_1", "1");
  1318. TestProperty property_2("key_2", "2");
  1319. TestResultAccessor::RecordProperty(&test_result, property_1);
  1320. TestResultAccessor::RecordProperty(&test_result, property_2);
  1321. ASSERT_EQ(2, test_result.test_property_count());
  1322. const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
  1323. EXPECT_STREQ("key_1", actual_property_1.key());
  1324. EXPECT_STREQ("1", actual_property_1.value());
  1325. const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
  1326. EXPECT_STREQ("key_2", actual_property_2.key());
  1327. EXPECT_STREQ("2", actual_property_2.value());
  1328. }
  1329. // Tests TestResult::RecordProperty() overrides values for duplicate keys.
  1330. TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
  1331. TestResult test_result;
  1332. TestProperty property_1_1("key_1", "1");
  1333. TestProperty property_2_1("key_2", "2");
  1334. TestProperty property_1_2("key_1", "12");
  1335. TestProperty property_2_2("key_2", "22");
  1336. TestResultAccessor::RecordProperty(&test_result, property_1_1);
  1337. TestResultAccessor::RecordProperty(&test_result, property_2_1);
  1338. TestResultAccessor::RecordProperty(&test_result, property_1_2);
  1339. TestResultAccessor::RecordProperty(&test_result, property_2_2);
  1340. ASSERT_EQ(2, test_result.test_property_count());
  1341. const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
  1342. EXPECT_STREQ("key_1", actual_property_1.key());
  1343. EXPECT_STREQ("12", actual_property_1.value());
  1344. const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
  1345. EXPECT_STREQ("key_2", actual_property_2.key());
  1346. EXPECT_STREQ("22", actual_property_2.value());
  1347. }
  1348. // Tests TestResult::GetTestProperty().
  1349. TEST(TestResultPropertyDeathTest, GetTestProperty) {
  1350. TestResult test_result;
  1351. TestProperty property_1("key_1", "1");
  1352. TestProperty property_2("key_2", "2");
  1353. TestProperty property_3("key_3", "3");
  1354. TestResultAccessor::RecordProperty(&test_result, property_1);
  1355. TestResultAccessor::RecordProperty(&test_result, property_2);
  1356. TestResultAccessor::RecordProperty(&test_result, property_3);
  1357. const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
  1358. const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
  1359. const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
  1360. EXPECT_STREQ("key_1", fetched_property_1.key());
  1361. EXPECT_STREQ("1", fetched_property_1.value());
  1362. EXPECT_STREQ("key_2", fetched_property_2.key());
  1363. EXPECT_STREQ("2", fetched_property_2.value());
  1364. EXPECT_STREQ("key_3", fetched_property_3.key());
  1365. EXPECT_STREQ("3", fetched_property_3.value());
  1366. EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
  1367. EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
  1368. }
  1369. // When a property using a reserved key is supplied to this function, it tests
  1370. // that a non-fatal failure is added, a fatal failure is not added, and that the
  1371. // property is not recorded.
  1372. void ExpectNonFatalFailureRecordingPropertyWithReservedKey(const char* key) {
  1373. TestResult test_result;
  1374. TestProperty property(key, "1");
  1375. EXPECT_NONFATAL_FAILURE(
  1376. TestResultAccessor::RecordProperty(&test_result, property),
  1377. "Reserved key");
  1378. ASSERT_EQ(0, test_result.test_property_count()) << "Not recorded";
  1379. }
  1380. // Attempting to recording a property with the Reserved literal "name"
  1381. // should add a non-fatal failure and the property should not be recorded.
  1382. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledName) {
  1383. ExpectNonFatalFailureRecordingPropertyWithReservedKey("name");
  1384. }
  1385. // Attempting to recording a property with the Reserved literal "status"
  1386. // should add a non-fatal failure and the property should not be recorded.
  1387. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledStatus) {
  1388. ExpectNonFatalFailureRecordingPropertyWithReservedKey("status");
  1389. }
  1390. // Attempting to recording a property with the Reserved literal "time"
  1391. // should add a non-fatal failure and the property should not be recorded.
  1392. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledTime) {
  1393. ExpectNonFatalFailureRecordingPropertyWithReservedKey("time");
  1394. }
  1395. // Attempting to recording a property with the Reserved literal "classname"
  1396. // should add a non-fatal failure and the property should not be recorded.
  1397. TEST(TestResultPropertyTest, AddFailureWhenUsingReservedKeyCalledClassname) {
  1398. ExpectNonFatalFailureRecordingPropertyWithReservedKey("classname");
  1399. }
  1400. // Tests that GTestFlagSaver works on Windows and Mac.
  1401. class GTestFlagSaverTest : public Test {
  1402. protected:
  1403. // Saves the Google Test flags such that we can restore them later, and
  1404. // then sets them to their default values. This will be called
  1405. // before the first test in this test case is run.
  1406. static void SetUpTestCase() {
  1407. saver_ = new GTestFlagSaver;
  1408. GTEST_FLAG(also_run_disabled_tests) = false;
  1409. GTEST_FLAG(break_on_failure) = false;
  1410. GTEST_FLAG(catch_exceptions) = false;
  1411. GTEST_FLAG(death_test_use_fork) = false;
  1412. GTEST_FLAG(color) = "auto";
  1413. GTEST_FLAG(filter) = "";
  1414. GTEST_FLAG(list_tests) = false;
  1415. GTEST_FLAG(output) = "";
  1416. GTEST_FLAG(print_time) = true;
  1417. GTEST_FLAG(random_seed) = 0;
  1418. GTEST_FLAG(repeat) = 1;
  1419. GTEST_FLAG(shuffle) = false;
  1420. GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
  1421. GTEST_FLAG(throw_on_failure) = false;
  1422. }
  1423. // Restores the Google Test flags that the tests have modified. This will
  1424. // be called after the last test in this test case is run.
  1425. static void TearDownTestCase() {
  1426. delete saver_;
  1427. saver_ = NULL;
  1428. }
  1429. // Verifies that the Google Test flags have their default values, and then
  1430. // modifies each of them.
  1431. void VerifyAndModifyFlags() {
  1432. EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
  1433. EXPECT_FALSE(GTEST_FLAG(break_on_failure));
  1434. EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
  1435. EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
  1436. EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
  1437. EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
  1438. EXPECT_FALSE(GTEST_FLAG(list_tests));
  1439. EXPECT_STREQ("", GTEST_FLAG(output).c_str());
  1440. EXPECT_TRUE(GTEST_FLAG(print_time));
  1441. EXPECT_EQ(0, GTEST_FLAG(random_seed));
  1442. EXPECT_EQ(1, GTEST_FLAG(repeat));
  1443. EXPECT_FALSE(GTEST_FLAG(shuffle));
  1444. EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
  1445. EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
  1446. GTEST_FLAG(also_run_disabled_tests) = true;
  1447. GTEST_FLAG(break_on_failure) = true;
  1448. GTEST_FLAG(catch_exceptions) = true;
  1449. GTEST_FLAG(color) = "no";
  1450. GTEST_FLAG(death_test_use_fork) = true;
  1451. GTEST_FLAG(filter) = "abc";
  1452. GTEST_FLAG(list_tests) = true;
  1453. GTEST_FLAG(output) = "xml:foo.xml";
  1454. GTEST_FLAG(print_time) = false;
  1455. GTEST_FLAG(random_seed) = 1;
  1456. GTEST_FLAG(repeat) = 100;
  1457. GTEST_FLAG(shuffle) = true;
  1458. GTEST_FLAG(stack_trace_depth) = 1;
  1459. GTEST_FLAG(throw_on_failure) = true;
  1460. }
  1461. private:
  1462. // For saving Google Test flags during this test case.
  1463. static GTestFlagSaver* saver_;
  1464. };
  1465. GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL;
  1466. // Google Test doesn't guarantee the order of tests. The following two
  1467. // tests are designed to work regardless of their order.
  1468. // Modifies the Google Test flags in the test body.
  1469. TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
  1470. VerifyAndModifyFlags();
  1471. }
  1472. // Verifies that the Google Test flags in the body of the previous test were
  1473. // restored to their original values.
  1474. TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
  1475. VerifyAndModifyFlags();
  1476. }
  1477. // Sets an environment variable with the given name to the given
  1478. // value. If the value argument is "", unsets the environment
  1479. // variable. The caller must ensure that both arguments are not NULL.
  1480. static void SetEnv(const char* name, const char* value) {
  1481. #if GTEST_OS_WINDOWS_MOBILE
  1482. // Environment variables are not supported on Windows CE.
  1483. return;
  1484. #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
  1485. // C++Builder's putenv only stores a pointer to its parameter; we have to
  1486. // ensure that the string remains valid as long as it might be needed.
  1487. // We use an std::map to do so.
  1488. static std::map<String, String*> added_env;
  1489. // Because putenv stores a pointer to the string buffer, we can't delete the
  1490. // previous string (if present) until after it's replaced.
  1491. String *prev_env = NULL;
  1492. if (added_env.find(name) != added_env.end()) {
  1493. prev_env = added_env[name];
  1494. }
  1495. added_env[name] = new String((Message() << name << "=" << value).GetString());
  1496. // The standard signature of putenv accepts a 'char*' argument. Other
  1497. // implementations, like C++Builder's, accept a 'const char*'.
  1498. // We cast away the 'const' since that would work for both variants.
  1499. putenv(const_cast<char*>(added_env[name]->c_str()));
  1500. delete prev_env;
  1501. #elif GTEST_OS_WINDOWS // If we are on Windows proper.
  1502. _putenv((Message() << name << "=" << value).GetString().c_str());
  1503. #else
  1504. if (*value == '\0') {
  1505. unsetenv(name);
  1506. } else {
  1507. setenv(name, value, 1);
  1508. }
  1509. #endif // GTEST_OS_WINDOWS_MOBILE
  1510. }
  1511. #if !GTEST_OS_WINDOWS_MOBILE
  1512. // Environment variables are not supported on Windows CE.
  1513. using testing::internal::Int32FromGTestEnv;
  1514. // Tests Int32FromGTestEnv().
  1515. // Tests that Int32FromGTestEnv() returns the default value when the
  1516. // environment variable is not set.
  1517. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
  1518. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
  1519. EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
  1520. }
  1521. // Tests that Int32FromGTestEnv() returns the default value when the
  1522. // environment variable overflows as an Int32.
  1523. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
  1524. printf("(expecting 2 warnings)\n");
  1525. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
  1526. EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
  1527. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
  1528. EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
  1529. }
  1530. // Tests that Int32FromGTestEnv() returns the default value when the
  1531. // environment variable does not represent a valid decimal integer.
  1532. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
  1533. printf("(expecting 2 warnings)\n");
  1534. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
  1535. EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
  1536. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
  1537. EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
  1538. }
  1539. // Tests that Int32FromGTestEnv() parses and returns the value of the
  1540. // environment variable when it represents a valid decimal integer in
  1541. // the range of an Int32.
  1542. TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
  1543. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
  1544. EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
  1545. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
  1546. EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
  1547. }
  1548. #endif // !GTEST_OS_WINDOWS_MOBILE
  1549. // Tests ParseInt32Flag().
  1550. // Tests that ParseInt32Flag() returns false and doesn't change the
  1551. // output value when the flag has wrong format
  1552. TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
  1553. Int32 value = 123;
  1554. EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
  1555. EXPECT_EQ(123, value);
  1556. EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
  1557. EXPECT_EQ(123, value);
  1558. }
  1559. // Tests that ParseInt32Flag() returns false and doesn't change the
  1560. // output value when the flag overflows as an Int32.
  1561. TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
  1562. printf("(expecting 2 warnings)\n");
  1563. Int32 value = 123;
  1564. EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
  1565. EXPECT_EQ(123, value);
  1566. EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
  1567. EXPECT_EQ(123, value);
  1568. }
  1569. // Tests that ParseInt32Flag() returns false and doesn't change the
  1570. // output value when the flag does not represent a valid decimal
  1571. // integer.
  1572. TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
  1573. printf("(expecting 2 warnings)\n");
  1574. Int32 value = 123;
  1575. EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
  1576. EXPECT_EQ(123, value);
  1577. EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
  1578. EXPECT_EQ(123, value);
  1579. }
  1580. // Tests that ParseInt32Flag() parses the value of the flag and
  1581. // returns true when the flag represents a valid decimal integer in
  1582. // the range of an Int32.
  1583. TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
  1584. Int32 value = 123;
  1585. EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
  1586. EXPECT_EQ(456, value);
  1587. EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
  1588. "abc", &value));
  1589. EXPECT_EQ(-789, value);
  1590. }
  1591. // Tests that Int32FromEnvOrDie() parses the value of the var or
  1592. // returns the correct default.
  1593. // Environment variables are not supported on Windows CE.
  1594. #if !GTEST_OS_WINDOWS_MOBILE
  1595. TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
  1596. EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
  1597. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
  1598. EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
  1599. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
  1600. EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
  1601. }
  1602. #endif // !GTEST_OS_WINDOWS_MOBILE
  1603. // Tests that Int32FromEnvOrDie() aborts with an error message
  1604. // if the variable is not an Int32.
  1605. TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
  1606. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
  1607. EXPECT_DEATH_IF_SUPPORTED(
  1608. Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
  1609. ".*");
  1610. }
  1611. // Tests that Int32FromEnvOrDie() aborts with an error message
  1612. // if the variable cannot be represnted by an Int32.
  1613. TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
  1614. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
  1615. EXPECT_DEATH_IF_SUPPORTED(
  1616. Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
  1617. ".*");
  1618. }
  1619. // Tests that ShouldRunTestOnShard() selects all tests
  1620. // where there is 1 shard.
  1621. TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
  1622. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
  1623. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
  1624. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
  1625. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
  1626. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
  1627. }
  1628. class ShouldShardTest : public testing::Test {
  1629. protected:
  1630. virtual void SetUp() {
  1631. index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
  1632. total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
  1633. }
  1634. virtual void TearDown() {
  1635. SetEnv(index_var_, "");
  1636. SetEnv(total_var_, "");
  1637. }
  1638. const char* index_var_;
  1639. const char* total_var_;
  1640. };
  1641. // Tests that sharding is disabled if neither of the environment variables
  1642. // are set.
  1643. TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
  1644. SetEnv(index_var_, "");
  1645. SetEnv(total_var_, "");
  1646. EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
  1647. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1648. }
  1649. // Tests that sharding is not enabled if total_shards == 1.
  1650. TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
  1651. SetEnv(index_var_, "0");
  1652. SetEnv(total_var_, "1");
  1653. EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
  1654. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1655. }
  1656. // Tests that sharding is enabled if total_shards > 1 and
  1657. // we are not in a death test subprocess.
  1658. // Environment variables are not supported on Windows CE.
  1659. #if !GTEST_OS_WINDOWS_MOBILE
  1660. TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
  1661. SetEnv(index_var_, "4");
  1662. SetEnv(total_var_, "22");
  1663. EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  1664. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1665. SetEnv(index_var_, "8");
  1666. SetEnv(total_var_, "9");
  1667. EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  1668. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1669. SetEnv(index_var_, "0");
  1670. SetEnv(total_var_, "9");
  1671. EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  1672. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1673. }
  1674. #endif // !GTEST_OS_WINDOWS_MOBILE
  1675. // Tests that we exit in error if the sharding values are not valid.
  1676. typedef ShouldShardTest ShouldShardDeathTest;
  1677. TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
  1678. SetEnv(index_var_, "4");
  1679. SetEnv(total_var_, "4");
  1680. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1681. SetEnv(index_var_, "4");
  1682. SetEnv(total_var_, "-2");
  1683. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1684. SetEnv(index_var_, "5");
  1685. SetEnv(total_var_, "");
  1686. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1687. SetEnv(index_var_, "");
  1688. SetEnv(total_var_, "5");
  1689. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1690. }
  1691. // Tests that ShouldRunTestOnShard is a partition when 5
  1692. // shards are used.
  1693. TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
  1694. // Choose an arbitrary number of tests and shards.
  1695. const int num_tests = 17;
  1696. const int num_shards = 5;
  1697. // Check partitioning: each test should be on exactly 1 shard.
  1698. for (int test_id = 0; test_id < num_tests; test_id++) {
  1699. int prev_selected_shard_index = -1;
  1700. for (int shard_index = 0; shard_index < num_shards; shard_index++) {
  1701. if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
  1702. if (prev_selected_shard_index < 0) {
  1703. prev_selected_shard_index = shard_index;
  1704. } else {
  1705. ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
  1706. << shard_index << " are both selected to run test " << test_id;
  1707. }
  1708. }
  1709. }
  1710. }
  1711. // Check balance: This is not required by the sharding protocol, but is a
  1712. // desirable property for performance.
  1713. for (int shard_index = 0; shard_index < num_shards; shard_index++) {
  1714. int num_tests_on_shard = 0;
  1715. for (int test_id = 0; test_id < num_tests; test_id++) {
  1716. num_tests_on_shard +=
  1717. ShouldRunTestOnShard(num_shards, shard_index, test_id);
  1718. }
  1719. EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
  1720. }
  1721. }
  1722. // For the same reason we are not explicitly testing everything in the
  1723. // Test class, there are no separate tests for the following classes
  1724. // (except for some trivial cases):
  1725. //
  1726. // TestCase, UnitTest, UnitTestResultPrinter.
  1727. //
  1728. // Similarly, there are no separate tests for the following macros:
  1729. //
  1730. // TEST, TEST_F, RUN_ALL_TESTS
  1731. TEST(UnitTestTest, CanGetOriginalWorkingDir) {
  1732. ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL);
  1733. EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
  1734. }
  1735. // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
  1736. // of various arities. They do not attempt to be exhaustive. Rather,
  1737. // view them as smoke tests that can be easily reviewed and verified.
  1738. // A more complete set of tests for predicate assertions can be found
  1739. // in gtest_pred_impl_unittest.cc.
  1740. // First, some predicates and predicate-formatters needed by the tests.
  1741. // Returns true iff the argument is an even number.
  1742. bool IsEven(int n) {
  1743. return (n % 2) == 0;
  1744. }
  1745. // A functor that returns true iff the argument is an even number.
  1746. struct IsEvenFunctor {
  1747. bool operator()(int n) { return IsEven(n); }
  1748. };
  1749. // A predicate-formatter function that asserts the argument is an even
  1750. // number.
  1751. AssertionResult AssertIsEven(const char* expr, int n) {
  1752. if (IsEven(n)) {
  1753. return AssertionSuccess();
  1754. }
  1755. Message msg;
  1756. msg << expr << " evaluates to " << n << ", which is not even.";
  1757. return AssertionFailure(msg);
  1758. }
  1759. // A predicate function that returns AssertionResult for use in
  1760. // EXPECT/ASSERT_TRUE/FALSE.
  1761. AssertionResult ResultIsEven(int n) {
  1762. if (IsEven(n))
  1763. return AssertionSuccess() << n << " is even";
  1764. else
  1765. return AssertionFailure() << n << " is odd";
  1766. }
  1767. // A predicate function that returns AssertionResult but gives no
  1768. // explanation why it succeeds. Needed for testing that
  1769. // EXPECT/ASSERT_FALSE handles such functions correctly.
  1770. AssertionResult ResultIsEvenNoExplanation(int n) {
  1771. if (IsEven(n))
  1772. return AssertionSuccess();
  1773. else
  1774. return AssertionFailure() << n << " is odd";
  1775. }
  1776. // A predicate-formatter functor that asserts the argument is an even
  1777. // number.
  1778. struct AssertIsEvenFunctor {
  1779. AssertionResult operator()(const char* expr, int n) {
  1780. return AssertIsEven(expr, n);
  1781. }
  1782. };
  1783. // Returns true iff the sum of the arguments is an even number.
  1784. bool SumIsEven2(int n1, int n2) {
  1785. return IsEven(n1 + n2);
  1786. }
  1787. // A functor that returns true iff the sum of the arguments is an even
  1788. // number.
  1789. struct SumIsEven3Functor {
  1790. bool operator()(int n1, int n2, int n3) {
  1791. return IsEven(n1 + n2 + n3);
  1792. }
  1793. };
  1794. // A predicate-formatter function that asserts the sum of the
  1795. // arguments is an even number.
  1796. AssertionResult AssertSumIsEven4(
  1797. const char* e1, const char* e2, const char* e3, const char* e4,
  1798. int n1, int n2, int n3, int n4) {
  1799. const int sum = n1 + n2 + n3 + n4;
  1800. if (IsEven(sum)) {
  1801. return AssertionSuccess();
  1802. }
  1803. Message msg;
  1804. msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
  1805. << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
  1806. << ") evaluates to " << sum << ", which is not even.";
  1807. return AssertionFailure(msg);
  1808. }
  1809. // A predicate-formatter functor that asserts the sum of the arguments
  1810. // is an even number.
  1811. struct AssertSumIsEven5Functor {
  1812. AssertionResult operator()(
  1813. const char* e1, const char* e2, const char* e3, const char* e4,
  1814. const char* e5, int n1, int n2, int n3, int n4, int n5) {
  1815. const int sum = n1 + n2 + n3 + n4 + n5;
  1816. if (IsEven(sum)) {
  1817. return AssertionSuccess();
  1818. }
  1819. Message msg;
  1820. msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
  1821. << " ("
  1822. << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
  1823. << ") evaluates to " << sum << ", which is not even.";
  1824. return AssertionFailure(msg);
  1825. }
  1826. };
  1827. // Tests unary predicate assertions.
  1828. // Tests unary predicate assertions that don't use a custom formatter.
  1829. TEST(Pred1Test, WithoutFormat) {
  1830. // Success cases.
  1831. EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
  1832. ASSERT_PRED1(IsEven, 4);
  1833. // Failure cases.
  1834. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1835. EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
  1836. }, "This failure is expected.");
  1837. EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
  1838. "evaluates to false");
  1839. }
  1840. // Tests unary predicate assertions that use a custom formatter.
  1841. TEST(Pred1Test, WithFormat) {
  1842. // Success cases.
  1843. EXPECT_PRED_FORMAT1(AssertIsEven, 2);
  1844. ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
  1845. << "This failure is UNEXPECTED!";
  1846. // Failure cases.
  1847. const int n = 5;
  1848. EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
  1849. "n evaluates to 5, which is not even.");
  1850. EXPECT_FATAL_FAILURE({ // NOLINT
  1851. ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
  1852. }, "This failure is expected.");
  1853. }
  1854. // Tests that unary predicate assertions evaluates their arguments
  1855. // exactly once.
  1856. TEST(Pred1Test, SingleEvaluationOnFailure) {
  1857. // A success case.
  1858. static int n = 0;
  1859. EXPECT_PRED1(IsEven, n++);
  1860. EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
  1861. // A failure case.
  1862. EXPECT_FATAL_FAILURE({ // NOLINT
  1863. ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
  1864. << "This failure is expected.";
  1865. }, "This failure is expected.");
  1866. EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
  1867. }
  1868. // Tests predicate assertions whose arity is >= 2.
  1869. // Tests predicate assertions that don't use a custom formatter.
  1870. TEST(PredTest, WithoutFormat) {
  1871. // Success cases.
  1872. ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
  1873. EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
  1874. // Failure cases.
  1875. const int n1 = 1;
  1876. const int n2 = 2;
  1877. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1878. EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
  1879. }, "This failure is expected.");
  1880. EXPECT_FATAL_FAILURE({ // NOLINT
  1881. ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
  1882. }, "evaluates to false");
  1883. }
  1884. // Tests predicate assertions that use a custom formatter.
  1885. TEST(PredTest, WithFormat) {
  1886. // Success cases.
  1887. ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
  1888. "This failure is UNEXPECTED!";
  1889. EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
  1890. // Failure cases.
  1891. const int n1 = 1;
  1892. const int n2 = 2;
  1893. const int n3 = 4;
  1894. const int n4 = 6;
  1895. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1896. EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
  1897. }, "evaluates to 13, which is not even.");
  1898. EXPECT_FATAL_FAILURE({ // NOLINT
  1899. ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
  1900. << "This failure is expected.";
  1901. }, "This failure is expected.");
  1902. }
  1903. // Tests that predicate assertions evaluates their arguments
  1904. // exactly once.
  1905. TEST(PredTest, SingleEvaluationOnFailure) {
  1906. // A success case.
  1907. int n1 = 0;
  1908. int n2 = 0;
  1909. EXPECT_PRED2(SumIsEven2, n1++, n2++);
  1910. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  1911. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  1912. // Another success case.
  1913. n1 = n2 = 0;
  1914. int n3 = 0;
  1915. int n4 = 0;
  1916. int n5 = 0;
  1917. ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
  1918. n1++, n2++, n3++, n4++, n5++)
  1919. << "This failure is UNEXPECTED!";
  1920. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  1921. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  1922. EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
  1923. EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
  1924. EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
  1925. // A failure case.
  1926. n1 = n2 = n3 = 0;
  1927. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1928. EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
  1929. << "This failure is expected.";
  1930. }, "This failure is expected.");
  1931. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  1932. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  1933. EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
  1934. // Another failure case.
  1935. n1 = n2 = n3 = n4 = 0;
  1936. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1937. EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
  1938. }, "evaluates to 1, which is not even.");
  1939. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  1940. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  1941. EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
  1942. EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
  1943. }
  1944. // Some helper functions for testing using overloaded/template
  1945. // functions with ASSERT_PREDn and EXPECT_PREDn.
  1946. bool IsPositive(double x) {
  1947. return x > 0;
  1948. }
  1949. template <typename T>
  1950. bool IsNegative(T x) {
  1951. return x < 0;
  1952. }
  1953. template <typename T1, typename T2>
  1954. bool GreaterThan(T1 x1, T2 x2) {
  1955. return x1 > x2;
  1956. }
  1957. // Tests that overloaded functions can be used in *_PRED* as long as
  1958. // their types are explicitly specified.
  1959. TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
  1960. // C++Builder requires C-style casts rather than static_cast.
  1961. EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
  1962. ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
  1963. }
  1964. // Tests that template functions can be used in *_PRED* as long as
  1965. // their types are explicitly specified.
  1966. TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
  1967. EXPECT_PRED1(IsNegative<int>, -5);
  1968. // Makes sure that we can handle templates with more than one
  1969. // parameter.
  1970. ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
  1971. }
  1972. // Some helper functions for testing using overloaded/template
  1973. // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
  1974. AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
  1975. return n > 0 ? AssertionSuccess() :
  1976. AssertionFailure(Message() << "Failure");
  1977. }
  1978. AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
  1979. return x > 0 ? AssertionSuccess() :
  1980. AssertionFailure(Message() << "Failure");
  1981. }
  1982. template <typename T>
  1983. AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
  1984. return x < 0 ? AssertionSuccess() :
  1985. AssertionFailure(Message() << "Failure");
  1986. }
  1987. template <typename T1, typename T2>
  1988. AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
  1989. const T1& x1, const T2& x2) {
  1990. return x1 == x2 ? AssertionSuccess() :
  1991. AssertionFailure(Message() << "Failure");
  1992. }
  1993. // Tests that overloaded functions can be used in *_PRED_FORMAT*
  1994. // without explicitly specifying their types.
  1995. TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
  1996. EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
  1997. ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
  1998. }
  1999. // Tests that template functions can be used in *_PRED_FORMAT* without
  2000. // explicitly specifying their types.
  2001. TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
  2002. EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
  2003. ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
  2004. }
  2005. // Tests string assertions.
  2006. // Tests ASSERT_STREQ with non-NULL arguments.
  2007. TEST(StringAssertionTest, ASSERT_STREQ) {
  2008. const char * const p1 = "good";
  2009. ASSERT_STREQ(p1, p1);
  2010. // Let p2 have the same content as p1, but be at a different address.
  2011. const char p2[] = "good";
  2012. ASSERT_STREQ(p1, p2);
  2013. EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
  2014. "Expected: \"bad\"");
  2015. }
  2016. // Tests ASSERT_STREQ with NULL arguments.
  2017. TEST(StringAssertionTest, ASSERT_STREQ_Null) {
  2018. ASSERT_STREQ(static_cast<const char *>(NULL), NULL);
  2019. EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"),
  2020. "non-null");
  2021. }
  2022. // Tests ASSERT_STREQ with NULL arguments.
  2023. TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
  2024. EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL),
  2025. "non-null");
  2026. }
  2027. // Tests ASSERT_STRNE.
  2028. TEST(StringAssertionTest, ASSERT_STRNE) {
  2029. ASSERT_STRNE("hi", "Hi");
  2030. ASSERT_STRNE("Hi", NULL);
  2031. ASSERT_STRNE(NULL, "Hi");
  2032. ASSERT_STRNE("", NULL);
  2033. ASSERT_STRNE(NULL, "");
  2034. ASSERT_STRNE("", "Hi");
  2035. ASSERT_STRNE("Hi", "");
  2036. EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
  2037. "\"Hi\" vs \"Hi\"");
  2038. }
  2039. // Tests ASSERT_STRCASEEQ.
  2040. TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
  2041. ASSERT_STRCASEEQ("hi", "Hi");
  2042. ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL);
  2043. ASSERT_STRCASEEQ("", "");
  2044. EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
  2045. "(ignoring case)");
  2046. }
  2047. // Tests ASSERT_STRCASENE.
  2048. TEST(StringAssertionTest, ASSERT_STRCASENE) {
  2049. ASSERT_STRCASENE("hi1", "Hi2");
  2050. ASSERT_STRCASENE("Hi", NULL);
  2051. ASSERT_STRCASENE(NULL, "Hi");
  2052. ASSERT_STRCASENE("", NULL);
  2053. ASSERT_STRCASENE(NULL, "");
  2054. ASSERT_STRCASENE("", "Hi");
  2055. ASSERT_STRCASENE("Hi", "");
  2056. EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
  2057. "(ignoring case)");
  2058. }
  2059. // Tests *_STREQ on wide strings.
  2060. TEST(StringAssertionTest, STREQ_Wide) {
  2061. // NULL strings.
  2062. ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL);
  2063. // Empty strings.
  2064. ASSERT_STREQ(L"", L"");
  2065. // Non-null vs NULL.
  2066. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL),
  2067. "non-null");
  2068. // Equal strings.
  2069. EXPECT_STREQ(L"Hi", L"Hi");
  2070. // Unequal strings.
  2071. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
  2072. "Abc");
  2073. // Strings containing wide characters.
  2074. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
  2075. "abc");
  2076. }
  2077. // Tests *_STRNE on wide strings.
  2078. TEST(StringAssertionTest, STRNE_Wide) {
  2079. // NULL strings.
  2080. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2081. EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL);
  2082. }, "");
  2083. // Empty strings.
  2084. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
  2085. "L\"\"");
  2086. // Non-null vs NULL.
  2087. ASSERT_STRNE(L"non-null", NULL);
  2088. // Equal strings.
  2089. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
  2090. "L\"Hi\"");
  2091. // Unequal strings.
  2092. EXPECT_STRNE(L"abc", L"Abc");
  2093. // Strings containing wide characters.
  2094. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
  2095. "abc");
  2096. }
  2097. // Tests for ::testing::IsSubstring().
  2098. // Tests that IsSubstring() returns the correct result when the input
  2099. // argument type is const char*.
  2100. TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
  2101. EXPECT_FALSE(IsSubstring("", "", NULL, "a"));
  2102. EXPECT_FALSE(IsSubstring("", "", "b", NULL));
  2103. EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
  2104. EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL));
  2105. EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
  2106. }
  2107. // Tests that IsSubstring() returns the correct result when the input
  2108. // argument type is const wchar_t*.
  2109. TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
  2110. EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
  2111. EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
  2112. EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
  2113. EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL));
  2114. EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
  2115. }
  2116. // Tests that IsSubstring() generates the correct message when the input
  2117. // argument type is const char*.
  2118. TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
  2119. EXPECT_STREQ("Value of: needle_expr\n"
  2120. " Actual: \"needle\"\n"
  2121. "Expected: a substring of haystack_expr\n"
  2122. "Which is: \"haystack\"",
  2123. IsSubstring("needle_expr", "haystack_expr",
  2124. "needle", "haystack").failure_message());
  2125. }
  2126. // Tests that IsSubstring returns the correct result when the input
  2127. // argument type is ::std::string.
  2128. TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
  2129. EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
  2130. EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
  2131. }
  2132. #if GTEST_HAS_STD_WSTRING
  2133. // Tests that IsSubstring returns the correct result when the input
  2134. // argument type is ::std::wstring.
  2135. TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
  2136. EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
  2137. EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
  2138. }
  2139. // Tests that IsSubstring() generates the correct message when the input
  2140. // argument type is ::std::wstring.
  2141. TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
  2142. EXPECT_STREQ("Value of: needle_expr\n"
  2143. " Actual: L\"needle\"\n"
  2144. "Expected: a substring of haystack_expr\n"
  2145. "Which is: L\"haystack\"",
  2146. IsSubstring(
  2147. "needle_expr", "haystack_expr",
  2148. ::std::wstring(L"needle"), L"haystack").failure_message());
  2149. }
  2150. #endif // GTEST_HAS_STD_WSTRING
  2151. // Tests for ::testing::IsNotSubstring().
  2152. // Tests that IsNotSubstring() returns the correct result when the input
  2153. // argument type is const char*.
  2154. TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
  2155. EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
  2156. EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
  2157. }
  2158. // Tests that IsNotSubstring() returns the correct result when the input
  2159. // argument type is const wchar_t*.
  2160. TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
  2161. EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
  2162. EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
  2163. }
  2164. // Tests that IsNotSubstring() generates the correct message when the input
  2165. // argument type is const wchar_t*.
  2166. TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
  2167. EXPECT_STREQ("Value of: needle_expr\n"
  2168. " Actual: L\"needle\"\n"
  2169. "Expected: not a substring of haystack_expr\n"
  2170. "Which is: L\"two needles\"",
  2171. IsNotSubstring(
  2172. "needle_expr", "haystack_expr",
  2173. L"needle", L"two needles").failure_message());
  2174. }
  2175. // Tests that IsNotSubstring returns the correct result when the input
  2176. // argument type is ::std::string.
  2177. TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
  2178. EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
  2179. EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
  2180. }
  2181. // Tests that IsNotSubstring() generates the correct message when the input
  2182. // argument type is ::std::string.
  2183. TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
  2184. EXPECT_STREQ("Value of: needle_expr\n"
  2185. " Actual: \"needle\"\n"
  2186. "Expected: not a substring of haystack_expr\n"
  2187. "Which is: \"two needles\"",
  2188. IsNotSubstring(
  2189. "needle_expr", "haystack_expr",
  2190. ::std::string("needle"), "two needles").failure_message());
  2191. }
  2192. #if GTEST_HAS_STD_WSTRING
  2193. // Tests that IsNotSubstring returns the correct result when the input
  2194. // argument type is ::std::wstring.
  2195. TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
  2196. EXPECT_FALSE(
  2197. IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
  2198. EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
  2199. }
  2200. #endif // GTEST_HAS_STD_WSTRING
  2201. // Tests floating-point assertions.
  2202. template <typename RawType>
  2203. class FloatingPointTest : public Test {
  2204. protected:
  2205. // Pre-calculated numbers to be used by the tests.
  2206. struct TestValues {
  2207. RawType close_to_positive_zero;
  2208. RawType close_to_negative_zero;
  2209. RawType further_from_negative_zero;
  2210. RawType close_to_one;
  2211. RawType further_from_one;
  2212. RawType infinity;
  2213. RawType close_to_infinity;
  2214. RawType further_from_infinity;
  2215. RawType nan1;
  2216. RawType nan2;
  2217. };
  2218. typedef typename testing::internal::FloatingPoint<RawType> Floating;
  2219. typedef typename Floating::Bits Bits;
  2220. virtual void SetUp() {
  2221. const size_t max_ulps = Floating::kMaxUlps;
  2222. // The bits that represent 0.0.
  2223. const Bits zero_bits = Floating(0).bits();
  2224. // Makes some numbers close to 0.0.
  2225. values_.close_to_positive_zero = Floating::ReinterpretBits(
  2226. zero_bits + max_ulps/2);
  2227. values_.close_to_negative_zero = -Floating::ReinterpretBits(
  2228. zero_bits + max_ulps - max_ulps/2);
  2229. values_.further_from_negative_zero = -Floating::ReinterpretBits(
  2230. zero_bits + max_ulps + 1 - max_ulps/2);
  2231. // The bits that represent 1.0.
  2232. const Bits one_bits = Floating(1).bits();
  2233. // Makes some numbers close to 1.0.
  2234. values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
  2235. values_.further_from_one = Floating::ReinterpretBits(
  2236. one_bits + max_ulps + 1);
  2237. // +infinity.
  2238. values_.infinity = Floating::Infinity();
  2239. // The bits that represent +infinity.
  2240. const Bits infinity_bits = Floating(values_.infinity).bits();
  2241. // Makes some numbers close to infinity.
  2242. values_.close_to_infinity = Floating::ReinterpretBits(
  2243. infinity_bits - max_ulps);
  2244. values_.further_from_infinity = Floating::ReinterpretBits(
  2245. infinity_bits - max_ulps - 1);
  2246. // Makes some NAN's. Sets the most significant bit of the fraction so that
  2247. // our NaN's are quiet; trying to process a signaling NaN would raise an
  2248. // exception if our environment enables floating point exceptions.
  2249. values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
  2250. | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
  2251. values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
  2252. | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
  2253. }
  2254. void TestSize() {
  2255. EXPECT_EQ(sizeof(RawType), sizeof(Bits));
  2256. }
  2257. static TestValues values_;
  2258. };
  2259. template <typename RawType>
  2260. typename FloatingPointTest<RawType>::TestValues
  2261. FloatingPointTest<RawType>::values_;
  2262. // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
  2263. typedef FloatingPointTest<float> FloatTest;
  2264. // Tests that the size of Float::Bits matches the size of float.
  2265. TEST_F(FloatTest, Size) {
  2266. TestSize();
  2267. }
  2268. // Tests comparing with +0 and -0.
  2269. TEST_F(FloatTest, Zeros) {
  2270. EXPECT_FLOAT_EQ(0.0, -0.0);
  2271. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
  2272. "1.0");
  2273. EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
  2274. "1.5");
  2275. }
  2276. // Tests comparing numbers close to 0.
  2277. //
  2278. // This ensures that *_FLOAT_EQ handles the sign correctly and no
  2279. // overflow occurs when comparing numbers whose absolute value is very
  2280. // small.
  2281. TEST_F(FloatTest, AlmostZeros) {
  2282. // In C++Builder, names within local classes (such as used by
  2283. // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  2284. // scoping class. Use a static local alias as a workaround.
  2285. // We use the assignment syntax since some compilers, like Sun Studio,
  2286. // don't allow initializing references using construction syntax
  2287. // (parentheses).
  2288. static const FloatTest::TestValues& v = this->values_;
  2289. EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
  2290. EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
  2291. EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
  2292. EXPECT_FATAL_FAILURE({ // NOLINT
  2293. ASSERT_FLOAT_EQ(v.close_to_positive_zero,
  2294. v.further_from_negative_zero);
  2295. }, "v.further_from_negative_zero");
  2296. }
  2297. // Tests comparing numbers close to each other.
  2298. TEST_F(FloatTest, SmallDiff) {
  2299. EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
  2300. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
  2301. "values_.further_from_one");
  2302. }
  2303. // Tests comparing numbers far apart.
  2304. TEST_F(FloatTest, LargeDiff) {
  2305. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
  2306. "3.0");
  2307. }
  2308. // Tests comparing with infinity.
  2309. //
  2310. // This ensures that no overflow occurs when comparing numbers whose
  2311. // absolute value is very large.
  2312. TEST_F(FloatTest, Infinity) {
  2313. EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
  2314. EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
  2315. #if !GTEST_OS_SYMBIAN
  2316. // Nokia's STLport crashes if we try to output infinity or NaN.
  2317. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
  2318. "-values_.infinity");
  2319. // This is interesting as the representations of infinity and nan1
  2320. // are only 1 DLP apart.
  2321. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
  2322. "values_.nan1");
  2323. #endif // !GTEST_OS_SYMBIAN
  2324. }
  2325. // Tests that comparing with NAN always returns false.
  2326. TEST_F(FloatTest, NaN) {
  2327. #if !GTEST_OS_SYMBIAN
  2328. // Nokia's STLport crashes if we try to output infinity or NaN.
  2329. // In C++Builder, names within local classes (such as used by
  2330. // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  2331. // scoping class. Use a static local alias as a workaround.
  2332. // We use the assignment syntax since some compilers, like Sun Studio,
  2333. // don't allow initializing references using construction syntax
  2334. // (parentheses).
  2335. static const FloatTest::TestValues& v = this->values_;
  2336. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
  2337. "v.nan1");
  2338. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
  2339. "v.nan2");
  2340. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
  2341. "v.nan1");
  2342. EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
  2343. "v.infinity");
  2344. #endif // !GTEST_OS_SYMBIAN
  2345. }
  2346. // Tests that *_FLOAT_EQ are reflexive.
  2347. TEST_F(FloatTest, Reflexive) {
  2348. EXPECT_FLOAT_EQ(0.0, 0.0);
  2349. EXPECT_FLOAT_EQ(1.0, 1.0);
  2350. ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
  2351. }
  2352. // Tests that *_FLOAT_EQ are commutative.
  2353. TEST_F(FloatTest, Commutative) {
  2354. // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
  2355. EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
  2356. // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
  2357. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
  2358. "1.0");
  2359. }
  2360. // Tests EXPECT_NEAR.
  2361. TEST_F(FloatTest, EXPECT_NEAR) {
  2362. EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
  2363. EXPECT_NEAR(2.0f, 3.0f, 1.0f);
  2364. EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
  2365. "The difference between 1.0f and 1.5f is 0.5, "
  2366. "which exceeds 0.25f");
  2367. // To work around a bug in gcc 2.95.0, there is intentionally no
  2368. // space after the first comma in the previous line.
  2369. }
  2370. // Tests ASSERT_NEAR.
  2371. TEST_F(FloatTest, ASSERT_NEAR) {
  2372. ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
  2373. ASSERT_NEAR(2.0f, 3.0f, 1.0f);
  2374. EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT
  2375. "The difference between 1.0f and 1.5f is 0.5, "
  2376. "which exceeds 0.25f");
  2377. // To work around a bug in gcc 2.95.0, there is intentionally no
  2378. // space after the first comma in the previous line.
  2379. }
  2380. // Tests the cases where FloatLE() should succeed.
  2381. TEST_F(FloatTest, FloatLESucceeds) {
  2382. EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
  2383. ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
  2384. // or when val1 is greater than, but almost equals to, val2.
  2385. EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
  2386. }
  2387. // Tests the cases where FloatLE() should fail.
  2388. TEST_F(FloatTest, FloatLEFails) {
  2389. // When val1 is greater than val2 by a large margin,
  2390. EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
  2391. "(2.0f) <= (1.0f)");
  2392. // or by a small yet non-negligible margin,
  2393. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2394. EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
  2395. }, "(values_.further_from_one) <= (1.0f)");
  2396. #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
  2397. // Nokia's STLport crashes if we try to output infinity or NaN.
  2398. // C++Builder gives bad results for ordered comparisons involving NaNs
  2399. // due to compiler bugs.
  2400. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2401. EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
  2402. }, "(values_.nan1) <= (values_.infinity)");
  2403. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2404. EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
  2405. }, "(-values_.infinity) <= (values_.nan1)");
  2406. EXPECT_FATAL_FAILURE({ // NOLINT
  2407. ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
  2408. }, "(values_.nan1) <= (values_.nan1)");
  2409. #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
  2410. }
  2411. // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
  2412. typedef FloatingPointTest<double> DoubleTest;
  2413. // Tests that the size of Double::Bits matches the size of double.
  2414. TEST_F(DoubleTest, Size) {
  2415. TestSize();
  2416. }
  2417. // Tests comparing with +0 and -0.
  2418. TEST_F(DoubleTest, Zeros) {
  2419. EXPECT_DOUBLE_EQ(0.0, -0.0);
  2420. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
  2421. "1.0");
  2422. EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
  2423. "1.0");
  2424. }
  2425. // Tests comparing numbers close to 0.
  2426. //
  2427. // This ensures that *_DOUBLE_EQ handles the sign correctly and no
  2428. // overflow occurs when comparing numbers whose absolute value is very
  2429. // small.
  2430. TEST_F(DoubleTest, AlmostZeros) {
  2431. // In C++Builder, names within local classes (such as used by
  2432. // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  2433. // scoping class. Use a static local alias as a workaround.
  2434. // We use the assignment syntax since some compilers, like Sun Studio,
  2435. // don't allow initializing references using construction syntax
  2436. // (parentheses).
  2437. static const DoubleTest::TestValues& v = this->values_;
  2438. EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
  2439. EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
  2440. EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
  2441. EXPECT_FATAL_FAILURE({ // NOLINT
  2442. ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
  2443. v.further_from_negative_zero);
  2444. }, "v.further_from_negative_zero");
  2445. }
  2446. // Tests comparing numbers close to each other.
  2447. TEST_F(DoubleTest, SmallDiff) {
  2448. EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
  2449. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
  2450. "values_.further_from_one");
  2451. }
  2452. // Tests comparing numbers far apart.
  2453. TEST_F(DoubleTest, LargeDiff) {
  2454. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
  2455. "3.0");
  2456. }
  2457. // Tests comparing with infinity.
  2458. //
  2459. // This ensures that no overflow occurs when comparing numbers whose
  2460. // absolute value is very large.
  2461. TEST_F(DoubleTest, Infinity) {
  2462. EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
  2463. EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
  2464. #if !GTEST_OS_SYMBIAN
  2465. // Nokia's STLport crashes if we try to output infinity or NaN.
  2466. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
  2467. "-values_.infinity");
  2468. // This is interesting as the representations of infinity_ and nan1_
  2469. // are only 1 DLP apart.
  2470. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
  2471. "values_.nan1");
  2472. #endif // !GTEST_OS_SYMBIAN
  2473. }
  2474. // Tests that comparing with NAN always returns false.
  2475. TEST_F(DoubleTest, NaN) {
  2476. #if !GTEST_OS_SYMBIAN
  2477. // In C++Builder, names within local classes (such as used by
  2478. // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  2479. // scoping class. Use a static local alias as a workaround.
  2480. // We use the assignment syntax since some compilers, like Sun Studio,
  2481. // don't allow initializing references using construction syntax
  2482. // (parentheses).
  2483. static const DoubleTest::TestValues& v = this->values_;
  2484. // Nokia's STLport crashes if we try to output infinity or NaN.
  2485. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
  2486. "v.nan1");
  2487. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
  2488. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
  2489. EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
  2490. "v.infinity");
  2491. #endif // !GTEST_OS_SYMBIAN
  2492. }
  2493. // Tests that *_DOUBLE_EQ are reflexive.
  2494. TEST_F(DoubleTest, Reflexive) {
  2495. EXPECT_DOUBLE_EQ(0.0, 0.0);
  2496. EXPECT_DOUBLE_EQ(1.0, 1.0);
  2497. #if !GTEST_OS_SYMBIAN
  2498. // Nokia's STLport crashes if we try to output infinity or NaN.
  2499. ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
  2500. #endif // !GTEST_OS_SYMBIAN
  2501. }
  2502. // Tests that *_DOUBLE_EQ are commutative.
  2503. TEST_F(DoubleTest, Commutative) {
  2504. // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
  2505. EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
  2506. // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
  2507. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
  2508. "1.0");
  2509. }
  2510. // Tests EXPECT_NEAR.
  2511. TEST_F(DoubleTest, EXPECT_NEAR) {
  2512. EXPECT_NEAR(-1.0, -1.1, 0.2);
  2513. EXPECT_NEAR(2.0, 3.0, 1.0);
  2514. EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
  2515. "The difference between 1.0 and 1.5 is 0.5, "
  2516. "which exceeds 0.25");
  2517. // To work around a bug in gcc 2.95.0, there is intentionally no
  2518. // space after the first comma in the previous statement.
  2519. }
  2520. // Tests ASSERT_NEAR.
  2521. TEST_F(DoubleTest, ASSERT_NEAR) {
  2522. ASSERT_NEAR(-1.0, -1.1, 0.2);
  2523. ASSERT_NEAR(2.0, 3.0, 1.0);
  2524. EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
  2525. "The difference between 1.0 and 1.5 is 0.5, "
  2526. "which exceeds 0.25");
  2527. // To work around a bug in gcc 2.95.0, there is intentionally no
  2528. // space after the first comma in the previous statement.
  2529. }
  2530. // Tests the cases where DoubleLE() should succeed.
  2531. TEST_F(DoubleTest, DoubleLESucceeds) {
  2532. EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
  2533. ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
  2534. // or when val1 is greater than, but almost equals to, val2.
  2535. EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
  2536. }
  2537. // Tests the cases where DoubleLE() should fail.
  2538. TEST_F(DoubleTest, DoubleLEFails) {
  2539. // When val1 is greater than val2 by a large margin,
  2540. EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
  2541. "(2.0) <= (1.0)");
  2542. // or by a small yet non-negligible margin,
  2543. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2544. EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
  2545. }, "(values_.further_from_one) <= (1.0)");
  2546. #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
  2547. // Nokia's STLport crashes if we try to output infinity or NaN.
  2548. // C++Builder gives bad results for ordered comparisons involving NaNs
  2549. // due to compiler bugs.
  2550. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2551. EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
  2552. }, "(values_.nan1) <= (values_.infinity)");
  2553. EXPECT_NONFATAL_FAILURE({ // NOLINT
  2554. EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
  2555. }, " (-values_.infinity) <= (values_.nan1)");
  2556. EXPECT_FATAL_FAILURE({ // NOLINT
  2557. ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
  2558. }, "(values_.nan1) <= (values_.nan1)");
  2559. #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__)
  2560. }
  2561. // Verifies that a test or test case whose name starts with DISABLED_ is
  2562. // not run.
  2563. // A test whose name starts with DISABLED_.
  2564. // Should not run.
  2565. TEST(DisabledTest, DISABLED_TestShouldNotRun) {
  2566. FAIL() << "Unexpected failure: Disabled test should not be run.";
  2567. }
  2568. // A test whose name does not start with DISABLED_.
  2569. // Should run.
  2570. TEST(DisabledTest, NotDISABLED_TestShouldRun) {
  2571. EXPECT_EQ(1, 1);
  2572. }
  2573. // A test case whose name starts with DISABLED_.
  2574. // Should not run.
  2575. TEST(DISABLED_TestCase, TestShouldNotRun) {
  2576. FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
  2577. }
  2578. // A test case and test whose names start with DISABLED_.
  2579. // Should not run.
  2580. TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) {
  2581. FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
  2582. }
  2583. // Check that when all tests in a test case are disabled, SetupTestCase() and
  2584. // TearDownTestCase() are not called.
  2585. class DisabledTestsTest : public Test {
  2586. protected:
  2587. static void SetUpTestCase() {
  2588. FAIL() << "Unexpected failure: All tests disabled in test case. "
  2589. "SetupTestCase() should not be called.";
  2590. }
  2591. static void TearDownTestCase() {
  2592. FAIL() << "Unexpected failure: All tests disabled in test case. "
  2593. "TearDownTestCase() should not be called.";
  2594. }
  2595. };
  2596. TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
  2597. FAIL() << "Unexpected failure: Disabled test should not be run.";
  2598. }
  2599. TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
  2600. FAIL() << "Unexpected failure: Disabled test should not be run.";
  2601. }
  2602. // Tests that disabled typed tests aren't run.
  2603. #if GTEST_HAS_TYPED_TEST
  2604. template <typename T>
  2605. class TypedTest : public Test {
  2606. };
  2607. typedef testing::Types<int, double> NumericTypes;
  2608. TYPED_TEST_CASE(TypedTest, NumericTypes);
  2609. TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
  2610. FAIL() << "Unexpected failure: Disabled typed test should not run.";
  2611. }
  2612. template <typename T>
  2613. class DISABLED_TypedTest : public Test {
  2614. };
  2615. TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes);
  2616. TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
  2617. FAIL() << "Unexpected failure: Disabled typed test should not run.";
  2618. }
  2619. #endif // GTEST_HAS_TYPED_TEST
  2620. // Tests that disabled type-parameterized tests aren't run.
  2621. #if GTEST_HAS_TYPED_TEST_P
  2622. template <typename T>
  2623. class TypedTestP : public Test {
  2624. };
  2625. TYPED_TEST_CASE_P(TypedTestP);
  2626. TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
  2627. FAIL() << "Unexpected failure: "
  2628. << "Disabled type-parameterized test should not run.";
  2629. }
  2630. REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);
  2631. INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);
  2632. template <typename T>
  2633. class DISABLED_TypedTestP : public Test {
  2634. };
  2635. TYPED_TEST_CASE_P(DISABLED_TypedTestP);
  2636. TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
  2637. FAIL() << "Unexpected failure: "
  2638. << "Disabled type-parameterized test should not run.";
  2639. }
  2640. REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);
  2641. INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);
  2642. #endif // GTEST_HAS_TYPED_TEST_P
  2643. // Tests that assertion macros evaluate their arguments exactly once.
  2644. class SingleEvaluationTest : public Test {
  2645. public: // Must be public and not protected due to a bug in g++ 3.4.2.
  2646. // This helper function is needed by the FailedASSERT_STREQ test
  2647. // below. It's public to work around C++Builder's bug with scoping local
  2648. // classes.
  2649. static void CompareAndIncrementCharPtrs() {
  2650. ASSERT_STREQ(p1_++, p2_++);
  2651. }
  2652. // This helper function is needed by the FailedASSERT_NE test below. It's
  2653. // public to work around C++Builder's bug with scoping local classes.
  2654. static void CompareAndIncrementInts() {
  2655. ASSERT_NE(a_++, b_++);
  2656. }
  2657. protected:
  2658. SingleEvaluationTest() {
  2659. p1_ = s1_;
  2660. p2_ = s2_;
  2661. a_ = 0;
  2662. b_ = 0;
  2663. }
  2664. static const char* const s1_;
  2665. static const char* const s2_;
  2666. static const char* p1_;
  2667. static const char* p2_;
  2668. static int a_;
  2669. static int b_;
  2670. };
  2671. const char* const SingleEvaluationTest::s1_ = "01234";
  2672. const char* const SingleEvaluationTest::s2_ = "abcde";
  2673. const char* SingleEvaluationTest::p1_;
  2674. const char* SingleEvaluationTest::p2_;
  2675. int SingleEvaluationTest::a_;
  2676. int SingleEvaluationTest::b_;
  2677. // Tests that when ASSERT_STREQ fails, it evaluates its arguments
  2678. // exactly once.
  2679. TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
  2680. EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
  2681. "p2_++");
  2682. EXPECT_EQ(s1_ + 1, p1_);
  2683. EXPECT_EQ(s2_ + 1, p2_);
  2684. }
  2685. // Tests that string assertion arguments are evaluated exactly once.
  2686. TEST_F(SingleEvaluationTest, ASSERT_STR) {
  2687. // successful EXPECT_STRNE
  2688. EXPECT_STRNE(p1_++, p2_++);
  2689. EXPECT_EQ(s1_ + 1, p1_);
  2690. EXPECT_EQ(s2_ + 1, p2_);
  2691. // failed EXPECT_STRCASEEQ
  2692. EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
  2693. "ignoring case");
  2694. EXPECT_EQ(s1_ + 2, p1_);
  2695. EXPECT_EQ(s2_ + 2, p2_);
  2696. }
  2697. // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
  2698. // once.
  2699. TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
  2700. EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
  2701. "(a_++) != (b_++)");
  2702. EXPECT_EQ(1, a_);
  2703. EXPECT_EQ(1, b_);
  2704. }
  2705. // Tests that assertion arguments are evaluated exactly once.
  2706. TEST_F(SingleEvaluationTest, OtherCases) {
  2707. // successful EXPECT_TRUE
  2708. EXPECT_TRUE(0 == a_++); // NOLINT
  2709. EXPECT_EQ(1, a_);
  2710. // failed EXPECT_TRUE
  2711. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
  2712. EXPECT_EQ(2, a_);
  2713. // successful EXPECT_GT
  2714. EXPECT_GT(a_++, b_++);
  2715. EXPECT_EQ(3, a_);
  2716. EXPECT_EQ(1, b_);
  2717. // failed EXPECT_LT
  2718. EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
  2719. EXPECT_EQ(4, a_);
  2720. EXPECT_EQ(2, b_);
  2721. // successful ASSERT_TRUE
  2722. ASSERT_TRUE(0 < a_++); // NOLINT
  2723. EXPECT_EQ(5, a_);
  2724. // successful ASSERT_GT
  2725. ASSERT_GT(a_++, b_++);
  2726. EXPECT_EQ(6, a_);
  2727. EXPECT_EQ(3, b_);
  2728. }
  2729. #if GTEST_HAS_EXCEPTIONS
  2730. void ThrowAnInteger() {
  2731. throw 1;
  2732. }
  2733. // Tests that assertion arguments are evaluated exactly once.
  2734. TEST_F(SingleEvaluationTest, ExceptionTests) {
  2735. // successful EXPECT_THROW
  2736. EXPECT_THROW({ // NOLINT
  2737. a_++;
  2738. ThrowAnInteger();
  2739. }, int);
  2740. EXPECT_EQ(1, a_);
  2741. // failed EXPECT_THROW, throws different
  2742. EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
  2743. a_++;
  2744. ThrowAnInteger();
  2745. }, bool), "throws a different type");
  2746. EXPECT_EQ(2, a_);
  2747. // failed EXPECT_THROW, throws nothing
  2748. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
  2749. EXPECT_EQ(3, a_);
  2750. // successful EXPECT_NO_THROW
  2751. EXPECT_NO_THROW(a_++);
  2752. EXPECT_EQ(4, a_);
  2753. // failed EXPECT_NO_THROW
  2754. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
  2755. a_++;
  2756. ThrowAnInteger();
  2757. }), "it throws");
  2758. EXPECT_EQ(5, a_);
  2759. // successful EXPECT_ANY_THROW
  2760. EXPECT_ANY_THROW({ // NOLINT
  2761. a_++;
  2762. ThrowAnInteger();
  2763. });
  2764. EXPECT_EQ(6, a_);
  2765. // failed EXPECT_ANY_THROW
  2766. EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
  2767. EXPECT_EQ(7, a_);
  2768. }
  2769. #endif // GTEST_HAS_EXCEPTIONS
  2770. // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
  2771. class NoFatalFailureTest : public Test {
  2772. protected:
  2773. void Succeeds() {}
  2774. void FailsNonFatal() {
  2775. ADD_FAILURE() << "some non-fatal failure";
  2776. }
  2777. void Fails() {
  2778. FAIL() << "some fatal failure";
  2779. }
  2780. void DoAssertNoFatalFailureOnFails() {
  2781. ASSERT_NO_FATAL_FAILURE(Fails());
  2782. ADD_FAILURE() << "shold not reach here.";
  2783. }
  2784. void DoExpectNoFatalFailureOnFails() {
  2785. EXPECT_NO_FATAL_FAILURE(Fails());
  2786. ADD_FAILURE() << "other failure";
  2787. }
  2788. };
  2789. TEST_F(NoFatalFailureTest, NoFailure) {
  2790. EXPECT_NO_FATAL_FAILURE(Succeeds());
  2791. ASSERT_NO_FATAL_FAILURE(Succeeds());
  2792. }
  2793. TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
  2794. EXPECT_NONFATAL_FAILURE(
  2795. EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
  2796. "some non-fatal failure");
  2797. EXPECT_NONFATAL_FAILURE(
  2798. ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
  2799. "some non-fatal failure");
  2800. }
  2801. TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
  2802. TestPartResultArray gtest_failures;
  2803. {
  2804. ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
  2805. DoAssertNoFatalFailureOnFails();
  2806. }
  2807. ASSERT_EQ(2, gtest_failures.size());
  2808. EXPECT_EQ(TestPartResult::kFatalFailure,
  2809. gtest_failures.GetTestPartResult(0).type());
  2810. EXPECT_EQ(TestPartResult::kFatalFailure,
  2811. gtest_failures.GetTestPartResult(1).type());
  2812. EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
  2813. gtest_failures.GetTestPartResult(0).message());
  2814. EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
  2815. gtest_failures.GetTestPartResult(1).message());
  2816. }
  2817. TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
  2818. TestPartResultArray gtest_failures;
  2819. {
  2820. ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
  2821. DoExpectNoFatalFailureOnFails();
  2822. }
  2823. ASSERT_EQ(3, gtest_failures.size());
  2824. EXPECT_EQ(TestPartResult::kFatalFailure,
  2825. gtest_failures.GetTestPartResult(0).type());
  2826. EXPECT_EQ(TestPartResult::kNonFatalFailure,
  2827. gtest_failures.GetTestPartResult(1).type());
  2828. EXPECT_EQ(TestPartResult::kNonFatalFailure,
  2829. gtest_failures.GetTestPartResult(2).type());
  2830. EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
  2831. gtest_failures.GetTestPartResult(0).message());
  2832. EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
  2833. gtest_failures.GetTestPartResult(1).message());
  2834. EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
  2835. gtest_failures.GetTestPartResult(2).message());
  2836. }
  2837. TEST_F(NoFatalFailureTest, MessageIsStreamable) {
  2838. TestPartResultArray gtest_failures;
  2839. {
  2840. ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
  2841. EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
  2842. }
  2843. ASSERT_EQ(2, gtest_failures.size());
  2844. EXPECT_EQ(TestPartResult::kNonFatalFailure,
  2845. gtest_failures.GetTestPartResult(0).type());
  2846. EXPECT_EQ(TestPartResult::kNonFatalFailure,
  2847. gtest_failures.GetTestPartResult(1).type());
  2848. EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
  2849. gtest_failures.GetTestPartResult(0).message());
  2850. EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
  2851. gtest_failures.GetTestPartResult(1).message());
  2852. }
  2853. // Tests non-string assertions.
  2854. // Tests EqFailure(), used for implementing *EQ* assertions.
  2855. TEST(AssertionTest, EqFailure) {
  2856. const String foo_val("5"), bar_val("6");
  2857. const String msg1(
  2858. EqFailure("foo", "bar", foo_val, bar_val, false)
  2859. .failure_message());
  2860. EXPECT_STREQ(
  2861. "Value of: bar\n"
  2862. " Actual: 6\n"
  2863. "Expected: foo\n"
  2864. "Which is: 5",
  2865. msg1.c_str());
  2866. const String msg2(
  2867. EqFailure("foo", "6", foo_val, bar_val, false)
  2868. .failure_message());
  2869. EXPECT_STREQ(
  2870. "Value of: 6\n"
  2871. "Expected: foo\n"
  2872. "Which is: 5",
  2873. msg2.c_str());
  2874. const String msg3(
  2875. EqFailure("5", "bar", foo_val, bar_val, false)
  2876. .failure_message());
  2877. EXPECT_STREQ(
  2878. "Value of: bar\n"
  2879. " Actual: 6\n"
  2880. "Expected: 5",
  2881. msg3.c_str());
  2882. const String msg4(
  2883. EqFailure("5", "6", foo_val, bar_val, false).failure_message());
  2884. EXPECT_STREQ(
  2885. "Value of: 6\n"
  2886. "Expected: 5",
  2887. msg4.c_str());
  2888. const String msg5(
  2889. EqFailure("foo", "bar",
  2890. String("\"x\""), String("\"y\""),
  2891. true).failure_message());
  2892. EXPECT_STREQ(
  2893. "Value of: bar\n"
  2894. " Actual: \"y\"\n"
  2895. "Expected: foo (ignoring case)\n"
  2896. "Which is: \"x\"",
  2897. msg5.c_str());
  2898. }
  2899. // Tests AppendUserMessage(), used for implementing the *EQ* macros.
  2900. TEST(AssertionTest, AppendUserMessage) {
  2901. const String foo("foo");
  2902. Message msg;
  2903. EXPECT_STREQ("foo",
  2904. AppendUserMessage(foo, msg).c_str());
  2905. msg << "bar";
  2906. EXPECT_STREQ("foo\nbar",
  2907. AppendUserMessage(foo, msg).c_str());
  2908. }
  2909. #ifdef __BORLANDC__
  2910. // Silences warnings: "Condition is always true", "Unreachable code"
  2911. #pragma option push -w-ccc -w-rch
  2912. #endif
  2913. // Tests ASSERT_TRUE.
  2914. TEST(AssertionTest, ASSERT_TRUE) {
  2915. ASSERT_TRUE(2 > 1); // NOLINT
  2916. EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
  2917. "2 < 1");
  2918. }
  2919. // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
  2920. TEST(AssertionTest, AssertTrueWithAssertionResult) {
  2921. ASSERT_TRUE(ResultIsEven(2));
  2922. #if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600
  2923. // ICE's in C++Builder 2007.
  2924. EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
  2925. "Value of: ResultIsEven(3)\n"
  2926. " Actual: false (3 is odd)\n"
  2927. "Expected: true");
  2928. #endif
  2929. ASSERT_TRUE(ResultIsEvenNoExplanation(2));
  2930. EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
  2931. "Value of: ResultIsEvenNoExplanation(3)\n"
  2932. " Actual: false (3 is odd)\n"
  2933. "Expected: true");
  2934. }
  2935. // Tests ASSERT_FALSE.
  2936. TEST(AssertionTest, ASSERT_FALSE) {
  2937. ASSERT_FALSE(2 < 1); // NOLINT
  2938. EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
  2939. "Value of: 2 > 1\n"
  2940. " Actual: true\n"
  2941. "Expected: false");
  2942. }
  2943. // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
  2944. TEST(AssertionTest, AssertFalseWithAssertionResult) {
  2945. ASSERT_FALSE(ResultIsEven(3));
  2946. #if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600
  2947. // ICE's in C++Builder 2007.
  2948. EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
  2949. "Value of: ResultIsEven(2)\n"
  2950. " Actual: true (2 is even)\n"
  2951. "Expected: false");
  2952. #endif
  2953. ASSERT_FALSE(ResultIsEvenNoExplanation(3));
  2954. EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
  2955. "Value of: ResultIsEvenNoExplanation(2)\n"
  2956. " Actual: true\n"
  2957. "Expected: false");
  2958. }
  2959. #ifdef __BORLANDC__
  2960. // Restores warnings after previous "#pragma option push" supressed them
  2961. #pragma option pop
  2962. #endif
  2963. // Tests using ASSERT_EQ on double values. The purpose is to make
  2964. // sure that the specialization we did for integer and anonymous enums
  2965. // isn't used for double arguments.
  2966. TEST(ExpectTest, ASSERT_EQ_Double) {
  2967. // A success.
  2968. ASSERT_EQ(5.6, 5.6);
  2969. // A failure.
  2970. EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
  2971. "5.1");
  2972. }
  2973. // Tests ASSERT_EQ.
  2974. TEST(AssertionTest, ASSERT_EQ) {
  2975. ASSERT_EQ(5, 2 + 3);
  2976. EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
  2977. "Value of: 2*3\n"
  2978. " Actual: 6\n"
  2979. "Expected: 5");
  2980. }
  2981. // Tests ASSERT_EQ(NULL, pointer).
  2982. #if GTEST_CAN_COMPARE_NULL
  2983. TEST(AssertionTest, ASSERT_EQ_NULL) {
  2984. // A success.
  2985. const char* p = NULL;
  2986. // Some older GCC versions may issue a spurious waring in this or the next
  2987. // assertion statement. This warning should not be suppressed with
  2988. // static_cast since the test verifies the ability to use bare NULL as the
  2989. // expected parameter to the macro.
  2990. ASSERT_EQ(NULL, p);
  2991. // A failure.
  2992. static int n = 0;
  2993. EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
  2994. "Value of: &n\n");
  2995. }
  2996. #endif // GTEST_CAN_COMPARE_NULL
  2997. // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
  2998. // treated as a null pointer by the compiler, we need to make sure
  2999. // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
  3000. // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
  3001. TEST(ExpectTest, ASSERT_EQ_0) {
  3002. int n = 0;
  3003. // A success.
  3004. ASSERT_EQ(0, n);
  3005. // A failure.
  3006. EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
  3007. "Expected: 0");
  3008. }
  3009. // Tests ASSERT_NE.
  3010. TEST(AssertionTest, ASSERT_NE) {
  3011. ASSERT_NE(6, 7);
  3012. EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
  3013. "Expected: ('a') != ('a'), "
  3014. "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
  3015. }
  3016. // Tests ASSERT_LE.
  3017. TEST(AssertionTest, ASSERT_LE) {
  3018. ASSERT_LE(2, 3);
  3019. ASSERT_LE(2, 2);
  3020. EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
  3021. "Expected: (2) <= (0), actual: 2 vs 0");
  3022. }
  3023. // Tests ASSERT_LT.
  3024. TEST(AssertionTest, ASSERT_LT) {
  3025. ASSERT_LT(2, 3);
  3026. EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
  3027. "Expected: (2) < (2), actual: 2 vs 2");
  3028. }
  3029. // Tests ASSERT_GE.
  3030. TEST(AssertionTest, ASSERT_GE) {
  3031. ASSERT_GE(2, 1);
  3032. ASSERT_GE(2, 2);
  3033. EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
  3034. "Expected: (2) >= (3), actual: 2 vs 3");
  3035. }
  3036. // Tests ASSERT_GT.
  3037. TEST(AssertionTest, ASSERT_GT) {
  3038. ASSERT_GT(2, 1);
  3039. EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
  3040. "Expected: (2) > (2), actual: 2 vs 2");
  3041. }
  3042. #if GTEST_HAS_EXCEPTIONS
  3043. void ThrowNothing() {}
  3044. // Tests ASSERT_THROW.
  3045. TEST(AssertionTest, ASSERT_THROW) {
  3046. ASSERT_THROW(ThrowAnInteger(), int);
  3047. #ifndef __BORLANDC__
  3048. // ICE's in C++Builder 2007 and 2009.
  3049. EXPECT_FATAL_FAILURE(
  3050. ASSERT_THROW(ThrowAnInteger(), bool),
  3051. "Expected: ThrowAnInteger() throws an exception of type bool.\n"
  3052. " Actual: it throws a different type.");
  3053. #endif
  3054. EXPECT_FATAL_FAILURE(
  3055. ASSERT_THROW(ThrowNothing(), bool),
  3056. "Expected: ThrowNothing() throws an exception of type bool.\n"
  3057. " Actual: it throws nothing.");
  3058. }
  3059. // Tests ASSERT_NO_THROW.
  3060. TEST(AssertionTest, ASSERT_NO_THROW) {
  3061. ASSERT_NO_THROW(ThrowNothing());
  3062. EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
  3063. "Expected: ThrowAnInteger() doesn't throw an exception."
  3064. "\n Actual: it throws.");
  3065. }
  3066. // Tests ASSERT_ANY_THROW.
  3067. TEST(AssertionTest, ASSERT_ANY_THROW) {
  3068. ASSERT_ANY_THROW(ThrowAnInteger());
  3069. EXPECT_FATAL_FAILURE(
  3070. ASSERT_ANY_THROW(ThrowNothing()),
  3071. "Expected: ThrowNothing() throws an exception.\n"
  3072. " Actual: it doesn't.");
  3073. }
  3074. #endif // GTEST_HAS_EXCEPTIONS
  3075. // Makes sure we deal with the precedence of <<. This test should
  3076. // compile.
  3077. TEST(AssertionTest, AssertPrecedence) {
  3078. ASSERT_EQ(1 < 2, true);
  3079. ASSERT_EQ(true && false, false);
  3080. }
  3081. // A subroutine used by the following test.
  3082. void TestEq1(int x) {
  3083. ASSERT_EQ(1, x);
  3084. }
  3085. // Tests calling a test subroutine that's not part of a fixture.
  3086. TEST(AssertionTest, NonFixtureSubroutine) {
  3087. EXPECT_FATAL_FAILURE(TestEq1(2),
  3088. "Value of: x");
  3089. }
  3090. // An uncopyable class.
  3091. class Uncopyable {
  3092. public:
  3093. explicit Uncopyable(int a_value) : value_(a_value) {}
  3094. int value() const { return value_; }
  3095. bool operator==(const Uncopyable& rhs) const {
  3096. return value() == rhs.value();
  3097. }
  3098. private:
  3099. // This constructor deliberately has no implementation, as we don't
  3100. // want this class to be copyable.
  3101. Uncopyable(const Uncopyable&); // NOLINT
  3102. int value_;
  3103. };
  3104. ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
  3105. return os << value.value();
  3106. }
  3107. bool IsPositiveUncopyable(const Uncopyable& x) {
  3108. return x.value() > 0;
  3109. }
  3110. // A subroutine used by the following test.
  3111. void TestAssertNonPositive() {
  3112. Uncopyable y(-1);
  3113. ASSERT_PRED1(IsPositiveUncopyable, y);
  3114. }
  3115. // A subroutine used by the following test.
  3116. void TestAssertEqualsUncopyable() {
  3117. Uncopyable x(5);
  3118. Uncopyable y(-1);
  3119. ASSERT_EQ(x, y);
  3120. }
  3121. // Tests that uncopyable objects can be used in assertions.
  3122. TEST(AssertionTest, AssertWorksWithUncopyableObject) {
  3123. Uncopyable x(5);
  3124. ASSERT_PRED1(IsPositiveUncopyable, x);
  3125. ASSERT_EQ(x, x);
  3126. EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
  3127. "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
  3128. EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
  3129. "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
  3130. }
  3131. // Tests that uncopyable objects can be used in expects.
  3132. TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
  3133. Uncopyable x(5);
  3134. EXPECT_PRED1(IsPositiveUncopyable, x);
  3135. Uncopyable y(-1);
  3136. EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
  3137. "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
  3138. EXPECT_EQ(x, x);
  3139. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
  3140. "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
  3141. }
  3142. // The version of gcc used in XCode 2.2 has a bug and doesn't allow
  3143. // anonymous enums in assertions. Therefore the following test is not
  3144. // done on Mac.
  3145. // Sun Studio also rejects this code.
  3146. #if !GTEST_OS_MAC && !defined(__SUNPRO_CC)
  3147. // Tests using assertions with anonymous enums.
  3148. enum {
  3149. CASE_A = -1,
  3150. #if GTEST_OS_LINUX
  3151. // We want to test the case where the size of the anonymous enum is
  3152. // larger than sizeof(int), to make sure our implementation of the
  3153. // assertions doesn't truncate the enums. However, MSVC
  3154. // (incorrectly) doesn't allow an enum value to exceed the range of
  3155. // an int, so this has to be conditionally compiled.
  3156. //
  3157. // On Linux, CASE_B and CASE_A have the same value when truncated to
  3158. // int size. We want to test whether this will confuse the
  3159. // assertions.
  3160. CASE_B = testing::internal::kMaxBiggestInt,
  3161. #else
  3162. CASE_B = INT_MAX,
  3163. #endif // GTEST_OS_LINUX
  3164. };
  3165. TEST(AssertionTest, AnonymousEnum) {
  3166. #if GTEST_OS_LINUX
  3167. EXPECT_EQ(static_cast<int>(CASE_A), static_cast<int>(CASE_B));
  3168. #endif // GTEST_OS_LINUX
  3169. EXPECT_EQ(CASE_A, CASE_A);
  3170. EXPECT_NE(CASE_A, CASE_B);
  3171. EXPECT_LT(CASE_A, CASE_B);
  3172. EXPECT_LE(CASE_A, CASE_B);
  3173. EXPECT_GT(CASE_B, CASE_A);
  3174. EXPECT_GE(CASE_A, CASE_A);
  3175. EXPECT_NONFATAL_FAILURE(EXPECT_GE(CASE_A, CASE_B),
  3176. "(CASE_A) >= (CASE_B)");
  3177. ASSERT_EQ(CASE_A, CASE_A);
  3178. ASSERT_NE(CASE_A, CASE_B);
  3179. ASSERT_LT(CASE_A, CASE_B);
  3180. ASSERT_LE(CASE_A, CASE_B);
  3181. ASSERT_GT(CASE_B, CASE_A);
  3182. ASSERT_GE(CASE_A, CASE_A);
  3183. EXPECT_FATAL_FAILURE(ASSERT_EQ(CASE_A, CASE_B),
  3184. "Value of: CASE_B");
  3185. }
  3186. #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
  3187. #if GTEST_OS_WINDOWS
  3188. static HRESULT UnexpectedHRESULTFailure() {
  3189. return E_UNEXPECTED;
  3190. }
  3191. static HRESULT OkHRESULTSuccess() {
  3192. return S_OK;
  3193. }
  3194. static HRESULT FalseHRESULTSuccess() {
  3195. return S_FALSE;
  3196. }
  3197. // HRESULT assertion tests test both zero and non-zero
  3198. // success codes as well as failure message for each.
  3199. //
  3200. // Windows CE doesn't support message texts.
  3201. TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
  3202. EXPECT_HRESULT_SUCCEEDED(S_OK);
  3203. EXPECT_HRESULT_SUCCEEDED(S_FALSE);
  3204. EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
  3205. "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
  3206. " Actual: 0x8000FFFF");
  3207. }
  3208. TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
  3209. ASSERT_HRESULT_SUCCEEDED(S_OK);
  3210. ASSERT_HRESULT_SUCCEEDED(S_FALSE);
  3211. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
  3212. "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
  3213. " Actual: 0x8000FFFF");
  3214. }
  3215. TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
  3216. EXPECT_HRESULT_FAILED(E_UNEXPECTED);
  3217. EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
  3218. "Expected: (OkHRESULTSuccess()) fails.\n"
  3219. " Actual: 0x00000000");
  3220. EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
  3221. "Expected: (FalseHRESULTSuccess()) fails.\n"
  3222. " Actual: 0x00000001");
  3223. }
  3224. TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
  3225. ASSERT_HRESULT_FAILED(E_UNEXPECTED);
  3226. #ifndef __BORLANDC__
  3227. // ICE's in C++Builder 2007 and 2009.
  3228. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
  3229. "Expected: (OkHRESULTSuccess()) fails.\n"
  3230. " Actual: 0x00000000");
  3231. #endif
  3232. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
  3233. "Expected: (FalseHRESULTSuccess()) fails.\n"
  3234. " Actual: 0x00000001");
  3235. }
  3236. // Tests that streaming to the HRESULT macros works.
  3237. TEST(HRESULTAssertionTest, Streaming) {
  3238. EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
  3239. ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
  3240. EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
  3241. ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
  3242. EXPECT_NONFATAL_FAILURE(
  3243. EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
  3244. "expected failure");
  3245. #ifndef __BORLANDC__
  3246. // ICE's in C++Builder 2007 and 2009.
  3247. EXPECT_FATAL_FAILURE(
  3248. ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
  3249. "expected failure");
  3250. #endif
  3251. EXPECT_NONFATAL_FAILURE(
  3252. EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
  3253. "expected failure");
  3254. EXPECT_FATAL_FAILURE(
  3255. ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
  3256. "expected failure");
  3257. }
  3258. #endif // GTEST_OS_WINDOWS
  3259. #ifdef __BORLANDC__
  3260. // Silences warnings: "Condition is always true", "Unreachable code"
  3261. #pragma option push -w-ccc -w-rch
  3262. #endif
  3263. // Tests that the assertion macros behave like single statements.
  3264. TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
  3265. if (AlwaysFalse())
  3266. ASSERT_TRUE(false) << "This should never be executed; "
  3267. "It's a compilation test only.";
  3268. if (AlwaysTrue())
  3269. EXPECT_FALSE(false);
  3270. else
  3271. ; // NOLINT
  3272. if (AlwaysFalse())
  3273. ASSERT_LT(1, 3);
  3274. if (AlwaysFalse())
  3275. ; // NOLINT
  3276. else
  3277. EXPECT_GT(3, 2) << "";
  3278. }
  3279. #if GTEST_HAS_EXCEPTIONS
  3280. // Tests that the compiler will not complain about unreachable code in the
  3281. // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
  3282. TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
  3283. int n = 0;
  3284. EXPECT_THROW(throw 1, int);
  3285. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
  3286. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
  3287. EXPECT_NO_THROW(n++);
  3288. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
  3289. EXPECT_ANY_THROW(throw 1);
  3290. EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
  3291. }
  3292. TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
  3293. if (AlwaysFalse())
  3294. EXPECT_THROW(ThrowNothing(), bool);
  3295. if (AlwaysTrue())
  3296. EXPECT_THROW(ThrowAnInteger(), int);
  3297. else
  3298. ; // NOLINT
  3299. if (AlwaysFalse())
  3300. EXPECT_NO_THROW(ThrowAnInteger());
  3301. if (AlwaysTrue())
  3302. EXPECT_NO_THROW(ThrowNothing());
  3303. else
  3304. ; // NOLINT
  3305. if (AlwaysFalse())
  3306. EXPECT_ANY_THROW(ThrowNothing());
  3307. if (AlwaysTrue())
  3308. EXPECT_ANY_THROW(ThrowAnInteger());
  3309. else
  3310. ; // NOLINT
  3311. }
  3312. #endif // GTEST_HAS_EXCEPTIONS
  3313. TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
  3314. if (AlwaysFalse())
  3315. EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
  3316. << "It's a compilation test only.";
  3317. else
  3318. ; // NOLINT
  3319. if (AlwaysFalse())
  3320. ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
  3321. else
  3322. ; // NOLINT
  3323. if (AlwaysTrue())
  3324. EXPECT_NO_FATAL_FAILURE(SUCCEED());
  3325. else
  3326. ; // NOLINT
  3327. if (AlwaysFalse())
  3328. ; // NOLINT
  3329. else
  3330. ASSERT_NO_FATAL_FAILURE(SUCCEED());
  3331. }
  3332. // Tests that the assertion macros work well with switch statements.
  3333. TEST(AssertionSyntaxTest, WorksWithSwitch) {
  3334. switch (0) {
  3335. case 1:
  3336. break;
  3337. default:
  3338. ASSERT_TRUE(true);
  3339. }
  3340. switch (0)
  3341. case 0:
  3342. EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
  3343. // Binary assertions are implemented using a different code path
  3344. // than the Boolean assertions. Hence we test them separately.
  3345. switch (0) {
  3346. case 1:
  3347. default:
  3348. ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
  3349. }
  3350. switch (0)
  3351. case 0:
  3352. EXPECT_NE(1, 2);
  3353. }
  3354. #if GTEST_HAS_EXCEPTIONS
  3355. void ThrowAString() {
  3356. throw "String";
  3357. }
  3358. // Test that the exception assertion macros compile and work with const
  3359. // type qualifier.
  3360. TEST(AssertionSyntaxTest, WorksWithConst) {
  3361. ASSERT_THROW(ThrowAString(), const char*);
  3362. EXPECT_THROW(ThrowAString(), const char*);
  3363. }
  3364. #endif // GTEST_HAS_EXCEPTIONS
  3365. } // namespace
  3366. namespace testing {
  3367. // Tests that Google Test tracks SUCCEED*.
  3368. TEST(SuccessfulAssertionTest, SUCCEED) {
  3369. SUCCEED();
  3370. SUCCEED() << "OK";
  3371. EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
  3372. }
  3373. // Tests that Google Test doesn't track successful EXPECT_*.
  3374. TEST(SuccessfulAssertionTest, EXPECT) {
  3375. EXPECT_TRUE(true);
  3376. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3377. }
  3378. // Tests that Google Test doesn't track successful EXPECT_STR*.
  3379. TEST(SuccessfulAssertionTest, EXPECT_STR) {
  3380. EXPECT_STREQ("", "");
  3381. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3382. }
  3383. // Tests that Google Test doesn't track successful ASSERT_*.
  3384. TEST(SuccessfulAssertionTest, ASSERT) {
  3385. ASSERT_TRUE(true);
  3386. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3387. }
  3388. // Tests that Google Test doesn't track successful ASSERT_STR*.
  3389. TEST(SuccessfulAssertionTest, ASSERT_STR) {
  3390. ASSERT_STREQ("", "");
  3391. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3392. }
  3393. } // namespace testing
  3394. namespace {
  3395. // Tests EXPECT_TRUE.
  3396. TEST(ExpectTest, EXPECT_TRUE) {
  3397. EXPECT_TRUE(2 > 1); // NOLINT
  3398. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
  3399. "Value of: 2 < 1\n"
  3400. " Actual: false\n"
  3401. "Expected: true");
  3402. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
  3403. "2 > 3");
  3404. }
  3405. // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
  3406. TEST(ExpectTest, ExpectTrueWithAssertionResult) {
  3407. EXPECT_TRUE(ResultIsEven(2));
  3408. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
  3409. "Value of: ResultIsEven(3)\n"
  3410. " Actual: false (3 is odd)\n"
  3411. "Expected: true");
  3412. EXPECT_TRUE(ResultIsEvenNoExplanation(2));
  3413. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
  3414. "Value of: ResultIsEvenNoExplanation(3)\n"
  3415. " Actual: false (3 is odd)\n"
  3416. "Expected: true");
  3417. }
  3418. // Tests EXPECT_FALSE.
  3419. TEST(ExpectTest, EXPECT_FALSE) {
  3420. EXPECT_FALSE(2 < 1); // NOLINT
  3421. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
  3422. "Value of: 2 > 1\n"
  3423. " Actual: true\n"
  3424. "Expected: false");
  3425. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
  3426. "2 < 3");
  3427. }
  3428. // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
  3429. TEST(ExpectTest, ExpectFalseWithAssertionResult) {
  3430. EXPECT_FALSE(ResultIsEven(3));
  3431. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
  3432. "Value of: ResultIsEven(2)\n"
  3433. " Actual: true (2 is even)\n"
  3434. "Expected: false");
  3435. EXPECT_FALSE(ResultIsEvenNoExplanation(3));
  3436. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
  3437. "Value of: ResultIsEvenNoExplanation(2)\n"
  3438. " Actual: true\n"
  3439. "Expected: false");
  3440. }
  3441. #ifdef __BORLANDC__
  3442. // Restores warnings after previous "#pragma option push" supressed them
  3443. #pragma option pop
  3444. #endif
  3445. // Tests EXPECT_EQ.
  3446. TEST(ExpectTest, EXPECT_EQ) {
  3447. EXPECT_EQ(5, 2 + 3);
  3448. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
  3449. "Value of: 2*3\n"
  3450. " Actual: 6\n"
  3451. "Expected: 5");
  3452. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
  3453. "2 - 3");
  3454. }
  3455. // Tests using EXPECT_EQ on double values. The purpose is to make
  3456. // sure that the specialization we did for integer and anonymous enums
  3457. // isn't used for double arguments.
  3458. TEST(ExpectTest, EXPECT_EQ_Double) {
  3459. // A success.
  3460. EXPECT_EQ(5.6, 5.6);
  3461. // A failure.
  3462. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
  3463. "5.1");
  3464. }
  3465. #if GTEST_CAN_COMPARE_NULL
  3466. // Tests EXPECT_EQ(NULL, pointer).
  3467. TEST(ExpectTest, EXPECT_EQ_NULL) {
  3468. // A success.
  3469. const char* p = NULL;
  3470. // Some older GCC versions may issue a spurious waring in this or the next
  3471. // assertion statement. This warning should not be suppressed with
  3472. // static_cast since the test verifies the ability to use bare NULL as the
  3473. // expected parameter to the macro.
  3474. EXPECT_EQ(NULL, p);
  3475. // A failure.
  3476. int n = 0;
  3477. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
  3478. "Value of: &n\n");
  3479. }
  3480. #endif // GTEST_CAN_COMPARE_NULL
  3481. // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
  3482. // treated as a null pointer by the compiler, we need to make sure
  3483. // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
  3484. // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
  3485. TEST(ExpectTest, EXPECT_EQ_0) {
  3486. int n = 0;
  3487. // A success.
  3488. EXPECT_EQ(0, n);
  3489. // A failure.
  3490. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
  3491. "Expected: 0");
  3492. }
  3493. // Tests EXPECT_NE.
  3494. TEST(ExpectTest, EXPECT_NE) {
  3495. EXPECT_NE(6, 7);
  3496. EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
  3497. "Expected: ('a') != ('a'), "
  3498. "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
  3499. EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
  3500. "2");
  3501. char* const p0 = NULL;
  3502. EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
  3503. "p0");
  3504. // Only way to get the Nokia compiler to compile the cast
  3505. // is to have a separate void* variable first. Putting
  3506. // the two casts on the same line doesn't work, neither does
  3507. // a direct C-style to char*.
  3508. void* pv1 = (void*)0x1234; // NOLINT
  3509. char* const p1 = reinterpret_cast<char*>(pv1);
  3510. EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
  3511. "p1");
  3512. }
  3513. // Tests EXPECT_LE.
  3514. TEST(ExpectTest, EXPECT_LE) {
  3515. EXPECT_LE(2, 3);
  3516. EXPECT_LE(2, 2);
  3517. EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
  3518. "Expected: (2) <= (0), actual: 2 vs 0");
  3519. EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
  3520. "(1.1) <= (0.9)");
  3521. }
  3522. // Tests EXPECT_LT.
  3523. TEST(ExpectTest, EXPECT_LT) {
  3524. EXPECT_LT(2, 3);
  3525. EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
  3526. "Expected: (2) < (2), actual: 2 vs 2");
  3527. EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
  3528. "(2) < (1)");
  3529. }
  3530. // Tests EXPECT_GE.
  3531. TEST(ExpectTest, EXPECT_GE) {
  3532. EXPECT_GE(2, 1);
  3533. EXPECT_GE(2, 2);
  3534. EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
  3535. "Expected: (2) >= (3), actual: 2 vs 3");
  3536. EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
  3537. "(0.9) >= (1.1)");
  3538. }
  3539. // Tests EXPECT_GT.
  3540. TEST(ExpectTest, EXPECT_GT) {
  3541. EXPECT_GT(2, 1);
  3542. EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
  3543. "Expected: (2) > (2), actual: 2 vs 2");
  3544. EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
  3545. "(2) > (3)");
  3546. }
  3547. #if GTEST_HAS_EXCEPTIONS
  3548. // Tests EXPECT_THROW.
  3549. TEST(ExpectTest, EXPECT_THROW) {
  3550. EXPECT_THROW(ThrowAnInteger(), int);
  3551. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
  3552. "Expected: ThrowAnInteger() throws an exception of "
  3553. "type bool.\n Actual: it throws a different type.");
  3554. EXPECT_NONFATAL_FAILURE(
  3555. EXPECT_THROW(ThrowNothing(), bool),
  3556. "Expected: ThrowNothing() throws an exception of type bool.\n"
  3557. " Actual: it throws nothing.");
  3558. }
  3559. // Tests EXPECT_NO_THROW.
  3560. TEST(ExpectTest, EXPECT_NO_THROW) {
  3561. EXPECT_NO_THROW(ThrowNothing());
  3562. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
  3563. "Expected: ThrowAnInteger() doesn't throw an "
  3564. "exception.\n Actual: it throws.");
  3565. }
  3566. // Tests EXPECT_ANY_THROW.
  3567. TEST(ExpectTest, EXPECT_ANY_THROW) {
  3568. EXPECT_ANY_THROW(ThrowAnInteger());
  3569. EXPECT_NONFATAL_FAILURE(
  3570. EXPECT_ANY_THROW(ThrowNothing()),
  3571. "Expected: ThrowNothing() throws an exception.\n"
  3572. " Actual: it doesn't.");
  3573. }
  3574. #endif // GTEST_HAS_EXCEPTIONS
  3575. // Make sure we deal with the precedence of <<.
  3576. TEST(ExpectTest, ExpectPrecedence) {
  3577. EXPECT_EQ(1 < 2, true);
  3578. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
  3579. "Value of: true && false");
  3580. }
  3581. // Tests the StreamableToString() function.
  3582. // Tests using StreamableToString() on a scalar.
  3583. TEST(StreamableToStringTest, Scalar) {
  3584. EXPECT_STREQ("5", StreamableToString(5).c_str());
  3585. }
  3586. // Tests using StreamableToString() on a non-char pointer.
  3587. TEST(StreamableToStringTest, Pointer) {
  3588. int n = 0;
  3589. int* p = &n;
  3590. EXPECT_STRNE("(null)", StreamableToString(p).c_str());
  3591. }
  3592. // Tests using StreamableToString() on a NULL non-char pointer.
  3593. TEST(StreamableToStringTest, NullPointer) {
  3594. int* p = NULL;
  3595. EXPECT_STREQ("(null)", StreamableToString(p).c_str());
  3596. }
  3597. // Tests using StreamableToString() on a C string.
  3598. TEST(StreamableToStringTest, CString) {
  3599. EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
  3600. }
  3601. // Tests using StreamableToString() on a NULL C string.
  3602. TEST(StreamableToStringTest, NullCString) {
  3603. char* p = NULL;
  3604. EXPECT_STREQ("(null)", StreamableToString(p).c_str());
  3605. }
  3606. // Tests using streamable values as assertion messages.
  3607. // Tests using std::string as an assertion message.
  3608. TEST(StreamableTest, string) {
  3609. static const std::string str(
  3610. "This failure message is a std::string, and is expected.");
  3611. EXPECT_FATAL_FAILURE(FAIL() << str,
  3612. str.c_str());
  3613. }
  3614. // Tests that we can output strings containing embedded NULs.
  3615. // Limited to Linux because we can only do this with std::string's.
  3616. TEST(StreamableTest, stringWithEmbeddedNUL) {
  3617. static const char char_array_with_nul[] =
  3618. "Here's a NUL\0 and some more string";
  3619. static const std::string string_with_nul(char_array_with_nul,
  3620. sizeof(char_array_with_nul)
  3621. - 1); // drops the trailing NUL
  3622. EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
  3623. "Here's a NUL\\0 and some more string");
  3624. }
  3625. // Tests that we can output a NUL char.
  3626. TEST(StreamableTest, NULChar) {
  3627. EXPECT_FATAL_FAILURE({ // NOLINT
  3628. FAIL() << "A NUL" << '\0' << " and some more string";
  3629. }, "A NUL\\0 and some more string");
  3630. }
  3631. // Tests using int as an assertion message.
  3632. TEST(StreamableTest, int) {
  3633. EXPECT_FATAL_FAILURE(FAIL() << 900913,
  3634. "900913");
  3635. }
  3636. // Tests using NULL char pointer as an assertion message.
  3637. //
  3638. // In MSVC, streaming a NULL char * causes access violation. Google Test
  3639. // implemented a workaround (substituting "(null)" for NULL). This
  3640. // tests whether the workaround works.
  3641. TEST(StreamableTest, NullCharPtr) {
  3642. EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL),
  3643. "(null)");
  3644. }
  3645. // Tests that basic IO manipulators (endl, ends, and flush) can be
  3646. // streamed to testing::Message.
  3647. TEST(StreamableTest, BasicIoManip) {
  3648. EXPECT_FATAL_FAILURE({ // NOLINT
  3649. FAIL() << "Line 1." << std::endl
  3650. << "A NUL char " << std::ends << std::flush << " in line 2.";
  3651. }, "Line 1.\nA NUL char \\0 in line 2.");
  3652. }
  3653. // Tests the macros that haven't been covered so far.
  3654. void AddFailureHelper(bool* aborted) {
  3655. *aborted = true;
  3656. ADD_FAILURE() << "Failure";
  3657. *aborted = false;
  3658. }
  3659. // Tests ADD_FAILURE.
  3660. TEST(MacroTest, ADD_FAILURE) {
  3661. bool aborted = true;
  3662. EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
  3663. "Failure");
  3664. EXPECT_FALSE(aborted);
  3665. }
  3666. // Tests FAIL.
  3667. TEST(MacroTest, FAIL) {
  3668. EXPECT_FATAL_FAILURE(FAIL(),
  3669. "Failed");
  3670. EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
  3671. "Intentional failure.");
  3672. }
  3673. // Tests SUCCEED
  3674. TEST(MacroTest, SUCCEED) {
  3675. SUCCEED();
  3676. SUCCEED() << "Explicit success.";
  3677. }
  3678. // Tests for EXPECT_EQ() and ASSERT_EQ().
  3679. //
  3680. // These tests fail *intentionally*, s.t. the failure messages can be
  3681. // generated and tested.
  3682. //
  3683. // We have different tests for different argument types.
  3684. // Tests using bool values in {EXPECT|ASSERT}_EQ.
  3685. TEST(EqAssertionTest, Bool) {
  3686. EXPECT_EQ(true, true);
  3687. EXPECT_FATAL_FAILURE(ASSERT_EQ(false, true),
  3688. "Value of: true");
  3689. }
  3690. // Tests using int values in {EXPECT|ASSERT}_EQ.
  3691. TEST(EqAssertionTest, Int) {
  3692. ASSERT_EQ(32, 32);
  3693. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
  3694. "33");
  3695. }
  3696. // Tests using time_t values in {EXPECT|ASSERT}_EQ.
  3697. TEST(EqAssertionTest, Time_T) {
  3698. EXPECT_EQ(static_cast<time_t>(0),
  3699. static_cast<time_t>(0));
  3700. EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
  3701. static_cast<time_t>(1234)),
  3702. "1234");
  3703. }
  3704. // Tests using char values in {EXPECT|ASSERT}_EQ.
  3705. TEST(EqAssertionTest, Char) {
  3706. ASSERT_EQ('z', 'z');
  3707. const char ch = 'b';
  3708. EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
  3709. "ch");
  3710. EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
  3711. "ch");
  3712. }
  3713. // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
  3714. TEST(EqAssertionTest, WideChar) {
  3715. EXPECT_EQ(L'b', L'b');
  3716. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
  3717. "Value of: L'x'\n"
  3718. " Actual: L'x' (120, 0x78)\n"
  3719. "Expected: L'\0'\n"
  3720. "Which is: L'\0' (0, 0x0)");
  3721. static wchar_t wchar;
  3722. wchar = L'b';
  3723. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
  3724. "wchar");
  3725. wchar = L'\x8119';
  3726. EXPECT_FATAL_FAILURE(ASSERT_EQ(L'\x8120', wchar),
  3727. "Value of: wchar");
  3728. }
  3729. // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
  3730. TEST(EqAssertionTest, StdString) {
  3731. // Compares a const char* to an std::string that has identical
  3732. // content.
  3733. ASSERT_EQ("Test", ::std::string("Test"));
  3734. // Compares two identical std::strings.
  3735. static const ::std::string str1("A * in the middle");
  3736. static const ::std::string str2(str1);
  3737. EXPECT_EQ(str1, str2);
  3738. // Compares a const char* to an std::string that has different
  3739. // content
  3740. EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
  3741. "::std::string(\"test\")");
  3742. // Compares an std::string to a char* that has different content.
  3743. char* const p1 = const_cast<char*>("foo");
  3744. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
  3745. "p1");
  3746. // Compares two std::strings that have different contents, one of
  3747. // which having a NUL character in the middle. This should fail.
  3748. static ::std::string str3(str1);
  3749. str3.at(2) = '\0';
  3750. EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
  3751. "Value of: str3\n"
  3752. " Actual: \"A \\0 in the middle\"");
  3753. }
  3754. #if GTEST_HAS_STD_WSTRING
  3755. // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
  3756. TEST(EqAssertionTest, StdWideString) {
  3757. // Compares an std::wstring to a const wchar_t* that has identical
  3758. // content.
  3759. EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8119");
  3760. // Compares two identical std::wstrings.
  3761. const ::std::wstring wstr1(L"A * in the middle");
  3762. const ::std::wstring wstr2(wstr1);
  3763. ASSERT_EQ(wstr1, wstr2);
  3764. // Compares an std::wstring to a const wchar_t* that has different
  3765. // content.
  3766. EXPECT_NONFATAL_FAILURE({ // NOLINT
  3767. EXPECT_EQ(::std::wstring(L"Test\x8119"), L"Test\x8120");
  3768. }, "L\"Test\\x8120\"");
  3769. // Compares two std::wstrings that have different contents, one of
  3770. // which having a NUL character in the middle.
  3771. ::std::wstring wstr3(wstr1);
  3772. wstr3.at(2) = L'\0';
  3773. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
  3774. "wstr3");
  3775. // Compares a wchar_t* to an std::wstring that has different
  3776. // content.
  3777. EXPECT_FATAL_FAILURE({ // NOLINT
  3778. ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
  3779. }, "");
  3780. }
  3781. #endif // GTEST_HAS_STD_WSTRING
  3782. #if GTEST_HAS_GLOBAL_STRING
  3783. // Tests using ::string values in {EXPECT|ASSERT}_EQ.
  3784. TEST(EqAssertionTest, GlobalString) {
  3785. // Compares a const char* to a ::string that has identical content.
  3786. EXPECT_EQ("Test", ::string("Test"));
  3787. // Compares two identical ::strings.
  3788. const ::string str1("A * in the middle");
  3789. const ::string str2(str1);
  3790. ASSERT_EQ(str1, str2);
  3791. // Compares a ::string to a const char* that has different content.
  3792. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"),
  3793. "test");
  3794. // Compares two ::strings that have different contents, one of which
  3795. // having a NUL character in the middle.
  3796. ::string str3(str1);
  3797. str3.at(2) = '\0';
  3798. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3),
  3799. "str3");
  3800. // Compares a ::string to a char* that has different content.
  3801. EXPECT_FATAL_FAILURE({ // NOLINT
  3802. ASSERT_EQ(::string("bar"), const_cast<char*>("foo"));
  3803. }, "");
  3804. }
  3805. #endif // GTEST_HAS_GLOBAL_STRING
  3806. #if GTEST_HAS_GLOBAL_WSTRING
  3807. // Tests using ::wstring values in {EXPECT|ASSERT}_EQ.
  3808. TEST(EqAssertionTest, GlobalWideString) {
  3809. // Compares a const wchar_t* to a ::wstring that has identical content.
  3810. ASSERT_EQ(L"Test\x8119", ::wstring(L"Test\x8119"));
  3811. // Compares two identical ::wstrings.
  3812. static const ::wstring wstr1(L"A * in the middle");
  3813. static const ::wstring wstr2(wstr1);
  3814. EXPECT_EQ(wstr1, wstr2);
  3815. // Compares a const wchar_t* to a ::wstring that has different
  3816. // content.
  3817. EXPECT_NONFATAL_FAILURE({ // NOLINT
  3818. EXPECT_EQ(L"Test\x8120", ::wstring(L"Test\x8119"));
  3819. }, "Test\\x8119");
  3820. // Compares a wchar_t* to a ::wstring that has different content.
  3821. wchar_t* const p1 = const_cast<wchar_t*>(L"foo");
  3822. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")),
  3823. "bar");
  3824. // Compares two ::wstrings that have different contents, one of which
  3825. // having a NUL character in the middle.
  3826. static ::wstring wstr3;
  3827. wstr3 = wstr1;
  3828. wstr3.at(2) = L'\0';
  3829. EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3),
  3830. "wstr3");
  3831. }
  3832. #endif // GTEST_HAS_GLOBAL_WSTRING
  3833. // Tests using char pointers in {EXPECT|ASSERT}_EQ.
  3834. TEST(EqAssertionTest, CharPointer) {
  3835. char* const p0 = NULL;
  3836. // Only way to get the Nokia compiler to compile the cast
  3837. // is to have a separate void* variable first. Putting
  3838. // the two casts on the same line doesn't work, neither does
  3839. // a direct C-style to char*.
  3840. void* pv1 = (void*)0x1234; // NOLINT
  3841. void* pv2 = (void*)0xABC0; // NOLINT
  3842. char* const p1 = reinterpret_cast<char*>(pv1);
  3843. char* const p2 = reinterpret_cast<char*>(pv2);
  3844. ASSERT_EQ(p1, p1);
  3845. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
  3846. "Value of: p2");
  3847. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
  3848. "p2");
  3849. EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
  3850. reinterpret_cast<char*>(0xABC0)),
  3851. "ABC0");
  3852. }
  3853. // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
  3854. TEST(EqAssertionTest, WideCharPointer) {
  3855. wchar_t* const p0 = NULL;
  3856. // Only way to get the Nokia compiler to compile the cast
  3857. // is to have a separate void* variable first. Putting
  3858. // the two casts on the same line doesn't work, neither does
  3859. // a direct C-style to char*.
  3860. void* pv1 = (void*)0x1234; // NOLINT
  3861. void* pv2 = (void*)0xABC0; // NOLINT
  3862. wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
  3863. wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
  3864. EXPECT_EQ(p0, p0);
  3865. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
  3866. "Value of: p2");
  3867. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
  3868. "p2");
  3869. void* pv3 = (void*)0x1234; // NOLINT
  3870. void* pv4 = (void*)0xABC0; // NOLINT
  3871. const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
  3872. const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
  3873. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
  3874. "p4");
  3875. }
  3876. // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
  3877. TEST(EqAssertionTest, OtherPointer) {
  3878. ASSERT_EQ(static_cast<const int*>(NULL),
  3879. static_cast<const int*>(NULL));
  3880. EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL),
  3881. reinterpret_cast<const int*>(0x1234)),
  3882. "0x1234");
  3883. }
  3884. // Tests the FRIEND_TEST macro.
  3885. // This class has a private member we want to test. We will test it
  3886. // both in a TEST and in a TEST_F.
  3887. class Foo {
  3888. public:
  3889. Foo() {}
  3890. private:
  3891. int Bar() const { return 1; }
  3892. // Declares the friend tests that can access the private member
  3893. // Bar().
  3894. FRIEND_TEST(FRIEND_TEST_Test, TEST);
  3895. FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
  3896. };
  3897. // Tests that the FRIEND_TEST declaration allows a TEST to access a
  3898. // class's private members. This should compile.
  3899. TEST(FRIEND_TEST_Test, TEST) {
  3900. ASSERT_EQ(1, Foo().Bar());
  3901. }
  3902. // The fixture needed to test using FRIEND_TEST with TEST_F.
  3903. class FRIEND_TEST_Test2 : public Test {
  3904. protected:
  3905. Foo foo;
  3906. };
  3907. // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
  3908. // class's private members. This should compile.
  3909. TEST_F(FRIEND_TEST_Test2, TEST_F) {
  3910. ASSERT_EQ(1, foo.Bar());
  3911. }
  3912. // Tests the life cycle of Test objects.
  3913. // The test fixture for testing the life cycle of Test objects.
  3914. //
  3915. // This class counts the number of live test objects that uses this
  3916. // fixture.
  3917. class TestLifeCycleTest : public Test {
  3918. protected:
  3919. // Constructor. Increments the number of test objects that uses
  3920. // this fixture.
  3921. TestLifeCycleTest() { count_++; }
  3922. // Destructor. Decrements the number of test objects that uses this
  3923. // fixture.
  3924. ~TestLifeCycleTest() { count_--; }
  3925. // Returns the number of live test objects that uses this fixture.
  3926. int count() const { return count_; }
  3927. private:
  3928. static int count_;
  3929. };
  3930. int TestLifeCycleTest::count_ = 0;
  3931. // Tests the life cycle of test objects.
  3932. TEST_F(TestLifeCycleTest, Test1) {
  3933. // There should be only one test object in this test case that's
  3934. // currently alive.
  3935. ASSERT_EQ(1, count());
  3936. }
  3937. // Tests the life cycle of test objects.
  3938. TEST_F(TestLifeCycleTest, Test2) {
  3939. // After Test1 is done and Test2 is started, there should still be
  3940. // only one live test object, as the object for Test1 should've been
  3941. // deleted.
  3942. ASSERT_EQ(1, count());
  3943. }
  3944. } // namespace
  3945. // Tests that the copy constructor works when it is NOT optimized away by
  3946. // the compiler.
  3947. TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
  3948. // Checks that the copy constructor doesn't try to dereference NULL pointers
  3949. // in the source object.
  3950. AssertionResult r1 = AssertionSuccess();
  3951. AssertionResult r2 = r1;
  3952. // The following line is added to prevent the compiler from optimizing
  3953. // away the constructor call.
  3954. r1 << "abc";
  3955. AssertionResult r3 = r1;
  3956. EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
  3957. EXPECT_STREQ("abc", r1.message());
  3958. }
  3959. // Tests that AssertionSuccess and AssertionFailure construct
  3960. // AssertionResult objects as expected.
  3961. TEST(AssertionResultTest, ConstructionWorks) {
  3962. AssertionResult r1 = AssertionSuccess();
  3963. EXPECT_TRUE(r1);
  3964. EXPECT_STREQ("", r1.message());
  3965. AssertionResult r2 = AssertionSuccess() << "abc";
  3966. EXPECT_TRUE(r2);
  3967. EXPECT_STREQ("abc", r2.message());
  3968. AssertionResult r3 = AssertionFailure();
  3969. EXPECT_FALSE(r3);
  3970. EXPECT_STREQ("", r3.message());
  3971. AssertionResult r4 = AssertionFailure() << "def";
  3972. EXPECT_FALSE(r4);
  3973. EXPECT_STREQ("def", r4.message());
  3974. AssertionResult r5 = AssertionFailure(Message() << "ghi");
  3975. EXPECT_FALSE(r5);
  3976. EXPECT_STREQ("ghi", r5.message());
  3977. }
  3978. // Tests that the negation fips the predicate result but keeps the message.
  3979. TEST(AssertionResultTest, NegationWorks) {
  3980. AssertionResult r1 = AssertionSuccess() << "abc";
  3981. EXPECT_FALSE(!r1);
  3982. EXPECT_STREQ("abc", (!r1).message());
  3983. AssertionResult r2 = AssertionFailure() << "def";
  3984. EXPECT_TRUE(!r2);
  3985. EXPECT_STREQ("def", (!r2).message());
  3986. }
  3987. TEST(AssertionResultTest, StreamingWorks) {
  3988. AssertionResult r = AssertionSuccess();
  3989. r << "abc" << 'd' << 0 << true;
  3990. EXPECT_STREQ("abcd0true", r.message());
  3991. }
  3992. // Tests streaming a user type whose definition and operator << are
  3993. // both in the global namespace.
  3994. class Base {
  3995. public:
  3996. explicit Base(int an_x) : x_(an_x) {}
  3997. int x() const { return x_; }
  3998. private:
  3999. int x_;
  4000. };
  4001. std::ostream& operator<<(std::ostream& os,
  4002. const Base& val) {
  4003. return os << val.x();
  4004. }
  4005. std::ostream& operator<<(std::ostream& os,
  4006. const Base* pointer) {
  4007. return os << "(" << pointer->x() << ")";
  4008. }
  4009. TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
  4010. Message msg;
  4011. Base a(1);
  4012. msg << a << &a; // Uses ::operator<<.
  4013. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4014. }
  4015. // Tests streaming a user type whose definition and operator<< are
  4016. // both in an unnamed namespace.
  4017. namespace {
  4018. class MyTypeInUnnamedNameSpace : public Base {
  4019. public:
  4020. explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
  4021. };
  4022. std::ostream& operator<<(std::ostream& os,
  4023. const MyTypeInUnnamedNameSpace& val) {
  4024. return os << val.x();
  4025. }
  4026. std::ostream& operator<<(std::ostream& os,
  4027. const MyTypeInUnnamedNameSpace* pointer) {
  4028. return os << "(" << pointer->x() << ")";
  4029. }
  4030. } // namespace
  4031. TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
  4032. Message msg;
  4033. MyTypeInUnnamedNameSpace a(1);
  4034. msg << a << &a; // Uses <unnamed_namespace>::operator<<.
  4035. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4036. }
  4037. // Tests streaming a user type whose definition and operator<< are
  4038. // both in a user namespace.
  4039. namespace namespace1 {
  4040. class MyTypeInNameSpace1 : public Base {
  4041. public:
  4042. explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
  4043. };
  4044. std::ostream& operator<<(std::ostream& os,
  4045. const MyTypeInNameSpace1& val) {
  4046. return os << val.x();
  4047. }
  4048. std::ostream& operator<<(std::ostream& os,
  4049. const MyTypeInNameSpace1* pointer) {
  4050. return os << "(" << pointer->x() << ")";
  4051. }
  4052. } // namespace namespace1
  4053. TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
  4054. Message msg;
  4055. namespace1::MyTypeInNameSpace1 a(1);
  4056. msg << a << &a; // Uses namespace1::operator<<.
  4057. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4058. }
  4059. // Tests streaming a user type whose definition is in a user namespace
  4060. // but whose operator<< is in the global namespace.
  4061. namespace namespace2 {
  4062. class MyTypeInNameSpace2 : public ::Base {
  4063. public:
  4064. explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
  4065. };
  4066. } // namespace namespace2
  4067. std::ostream& operator<<(std::ostream& os,
  4068. const namespace2::MyTypeInNameSpace2& val) {
  4069. return os << val.x();
  4070. }
  4071. std::ostream& operator<<(std::ostream& os,
  4072. const namespace2::MyTypeInNameSpace2* pointer) {
  4073. return os << "(" << pointer->x() << ")";
  4074. }
  4075. TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
  4076. Message msg;
  4077. namespace2::MyTypeInNameSpace2 a(1);
  4078. msg << a << &a; // Uses ::operator<<.
  4079. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4080. }
  4081. // Tests streaming NULL pointers to testing::Message.
  4082. TEST(MessageTest, NullPointers) {
  4083. Message msg;
  4084. char* const p1 = NULL;
  4085. unsigned char* const p2 = NULL;
  4086. int* p3 = NULL;
  4087. double* p4 = NULL;
  4088. bool* p5 = NULL;
  4089. Message* p6 = NULL;
  4090. msg << p1 << p2 << p3 << p4 << p5 << p6;
  4091. ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
  4092. msg.GetString().c_str());
  4093. }
  4094. // Tests streaming wide strings to testing::Message.
  4095. TEST(MessageTest, WideStrings) {
  4096. // Streams a NULL of type const wchar_t*.
  4097. const wchar_t* const_wstr = NULL;
  4098. EXPECT_STREQ("(null)",
  4099. (Message() << const_wstr).GetString().c_str());
  4100. // Streams a NULL of type wchar_t*.
  4101. wchar_t* wstr = NULL;
  4102. EXPECT_STREQ("(null)",
  4103. (Message() << wstr).GetString().c_str());
  4104. // Streams a non-NULL of type const wchar_t*.
  4105. const_wstr = L"abc\x8119";
  4106. EXPECT_STREQ("abc\xe8\x84\x99",
  4107. (Message() << const_wstr).GetString().c_str());
  4108. // Streams a non-NULL of type wchar_t*.
  4109. wstr = const_cast<wchar_t*>(const_wstr);
  4110. EXPECT_STREQ("abc\xe8\x84\x99",
  4111. (Message() << wstr).GetString().c_str());
  4112. }
  4113. // This line tests that we can define tests in the testing namespace.
  4114. namespace testing {
  4115. // Tests the TestInfo class.
  4116. class TestInfoTest : public Test {
  4117. protected:
  4118. static const TestInfo* GetTestInfo(const char* test_name) {
  4119. const TestCase* const test_case = GetUnitTestImpl()->
  4120. GetTestCase("TestInfoTest", "", NULL, NULL);
  4121. for (int i = 0; i < test_case->total_test_count(); ++i) {
  4122. const TestInfo* const test_info = test_case->GetTestInfo(i);
  4123. if (strcmp(test_name, test_info->name()) == 0)
  4124. return test_info;
  4125. }
  4126. return NULL;
  4127. }
  4128. static const TestResult* GetTestResult(
  4129. const TestInfo* test_info) {
  4130. return test_info->result();
  4131. }
  4132. };
  4133. // Tests TestInfo::test_case_name() and TestInfo::name().
  4134. TEST_F(TestInfoTest, Names) {
  4135. const TestInfo* const test_info = GetTestInfo("Names");
  4136. ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
  4137. ASSERT_STREQ("Names", test_info->name());
  4138. }
  4139. // Tests TestInfo::result().
  4140. TEST_F(TestInfoTest, result) {
  4141. const TestInfo* const test_info = GetTestInfo("result");
  4142. // Initially, there is no TestPartResult for this test.
  4143. ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
  4144. // After the previous assertion, there is still none.
  4145. ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
  4146. }
  4147. // Tests setting up and tearing down a test case.
  4148. class SetUpTestCaseTest : public Test {
  4149. protected:
  4150. // This will be called once before the first test in this test case
  4151. // is run.
  4152. static void SetUpTestCase() {
  4153. printf("Setting up the test case . . .\n");
  4154. // Initializes some shared resource. In this simple example, we
  4155. // just create a C string. More complex stuff can be done if
  4156. // desired.
  4157. shared_resource_ = "123";
  4158. // Increments the number of test cases that have been set up.
  4159. counter_++;
  4160. // SetUpTestCase() should be called only once.
  4161. EXPECT_EQ(1, counter_);
  4162. }
  4163. // This will be called once after the last test in this test case is
  4164. // run.
  4165. static void TearDownTestCase() {
  4166. printf("Tearing down the test case . . .\n");
  4167. // Decrements the number of test cases that have been set up.
  4168. counter_--;
  4169. // TearDownTestCase() should be called only once.
  4170. EXPECT_EQ(0, counter_);
  4171. // Cleans up the shared resource.
  4172. shared_resource_ = NULL;
  4173. }
  4174. // This will be called before each test in this test case.
  4175. virtual void SetUp() {
  4176. // SetUpTestCase() should be called only once, so counter_ should
  4177. // always be 1.
  4178. EXPECT_EQ(1, counter_);
  4179. }
  4180. // Number of test cases that have been set up.
  4181. static int counter_;
  4182. // Some resource to be shared by all tests in this test case.
  4183. static const char* shared_resource_;
  4184. };
  4185. int SetUpTestCaseTest::counter_ = 0;
  4186. const char* SetUpTestCaseTest::shared_resource_ = NULL;
  4187. // A test that uses the shared resource.
  4188. TEST_F(SetUpTestCaseTest, Test1) {
  4189. EXPECT_STRNE(NULL, shared_resource_);
  4190. }
  4191. // Another test that uses the shared resource.
  4192. TEST_F(SetUpTestCaseTest, Test2) {
  4193. EXPECT_STREQ("123", shared_resource_);
  4194. }
  4195. // The InitGoogleTestTest test case tests testing::InitGoogleTest().
  4196. // The Flags struct stores a copy of all Google Test flags.
  4197. struct Flags {
  4198. // Constructs a Flags struct where each flag has its default value.
  4199. Flags() : also_run_disabled_tests(false),
  4200. break_on_failure(false),
  4201. catch_exceptions(false),
  4202. death_test_use_fork(false),
  4203. filter(""),
  4204. list_tests(false),
  4205. output(""),
  4206. print_time(true),
  4207. random_seed(0),
  4208. repeat(1),
  4209. shuffle(false),
  4210. stack_trace_depth(kMaxStackTraceDepth),
  4211. throw_on_failure(false) {}
  4212. // Factory methods.
  4213. // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
  4214. // the given value.
  4215. static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
  4216. Flags flags;
  4217. flags.also_run_disabled_tests = also_run_disabled_tests;
  4218. return flags;
  4219. }
  4220. // Creates a Flags struct where the gtest_break_on_failure flag has
  4221. // the given value.
  4222. static Flags BreakOnFailure(bool break_on_failure) {
  4223. Flags flags;
  4224. flags.break_on_failure = break_on_failure;
  4225. return flags;
  4226. }
  4227. // Creates a Flags struct where the gtest_catch_exceptions flag has
  4228. // the given value.
  4229. static Flags CatchExceptions(bool catch_exceptions) {
  4230. Flags flags;
  4231. flags.catch_exceptions = catch_exceptions;
  4232. return flags;
  4233. }
  4234. // Creates a Flags struct where the gtest_death_test_use_fork flag has
  4235. // the given value.
  4236. static Flags DeathTestUseFork(bool death_test_use_fork) {
  4237. Flags flags;
  4238. flags.death_test_use_fork = death_test_use_fork;
  4239. return flags;
  4240. }
  4241. // Creates a Flags struct where the gtest_filter flag has the given
  4242. // value.
  4243. static Flags Filter(const char* filter) {
  4244. Flags flags;
  4245. flags.filter = filter;
  4246. return flags;
  4247. }
  4248. // Creates a Flags struct where the gtest_list_tests flag has the
  4249. // given value.
  4250. static Flags ListTests(bool list_tests) {
  4251. Flags flags;
  4252. flags.list_tests = list_tests;
  4253. return flags;
  4254. }
  4255. // Creates a Flags struct where the gtest_output flag has the given
  4256. // value.
  4257. static Flags Output(const char* output) {
  4258. Flags flags;
  4259. flags.output = output;
  4260. return flags;
  4261. }
  4262. // Creates a Flags struct where the gtest_print_time flag has the given
  4263. // value.
  4264. static Flags PrintTime(bool print_time) {
  4265. Flags flags;
  4266. flags.print_time = print_time;
  4267. return flags;
  4268. }
  4269. // Creates a Flags struct where the gtest_random_seed flag has
  4270. // the given value.
  4271. static Flags RandomSeed(Int32 random_seed) {
  4272. Flags flags;
  4273. flags.random_seed = random_seed;
  4274. return flags;
  4275. }
  4276. // Creates a Flags struct where the gtest_repeat flag has the given
  4277. // value.
  4278. static Flags Repeat(Int32 repeat) {
  4279. Flags flags;
  4280. flags.repeat = repeat;
  4281. return flags;
  4282. }
  4283. // Creates a Flags struct where the gtest_shuffle flag has
  4284. // the given value.
  4285. static Flags Shuffle(bool shuffle) {
  4286. Flags flags;
  4287. flags.shuffle = shuffle;
  4288. return flags;
  4289. }
  4290. // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
  4291. // the given value.
  4292. static Flags StackTraceDepth(Int32 stack_trace_depth) {
  4293. Flags flags;
  4294. flags.stack_trace_depth = stack_trace_depth;
  4295. return flags;
  4296. }
  4297. // Creates a Flags struct where the gtest_throw_on_failure flag has
  4298. // the given value.
  4299. static Flags ThrowOnFailure(bool throw_on_failure) {
  4300. Flags flags;
  4301. flags.throw_on_failure = throw_on_failure;
  4302. return flags;
  4303. }
  4304. // These fields store the flag values.
  4305. bool also_run_disabled_tests;
  4306. bool break_on_failure;
  4307. bool catch_exceptions;
  4308. bool death_test_use_fork;
  4309. const char* filter;
  4310. bool list_tests;
  4311. const char* output;
  4312. bool print_time;
  4313. Int32 random_seed;
  4314. Int32 repeat;
  4315. bool shuffle;
  4316. Int32 stack_trace_depth;
  4317. bool throw_on_failure;
  4318. };
  4319. // Fixture for testing InitGoogleTest().
  4320. class InitGoogleTestTest : public Test {
  4321. protected:
  4322. // Clears the flags before each test.
  4323. virtual void SetUp() {
  4324. GTEST_FLAG(also_run_disabled_tests) = false;
  4325. GTEST_FLAG(break_on_failure) = false;
  4326. GTEST_FLAG(catch_exceptions) = false;
  4327. GTEST_FLAG(death_test_use_fork) = false;
  4328. GTEST_FLAG(filter) = "";
  4329. GTEST_FLAG(list_tests) = false;
  4330. GTEST_FLAG(output) = "";
  4331. GTEST_FLAG(print_time) = true;
  4332. GTEST_FLAG(random_seed) = 0;
  4333. GTEST_FLAG(repeat) = 1;
  4334. GTEST_FLAG(shuffle) = false;
  4335. GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
  4336. GTEST_FLAG(throw_on_failure) = false;
  4337. }
  4338. // Asserts that two narrow or wide string arrays are equal.
  4339. template <typename CharType>
  4340. static void AssertStringArrayEq(size_t size1, CharType** array1,
  4341. size_t size2, CharType** array2) {
  4342. ASSERT_EQ(size1, size2) << " Array sizes different.";
  4343. for (size_t i = 0; i != size1; i++) {
  4344. ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
  4345. }
  4346. }
  4347. // Verifies that the flag values match the expected values.
  4348. static void CheckFlags(const Flags& expected) {
  4349. EXPECT_EQ(expected.also_run_disabled_tests,
  4350. GTEST_FLAG(also_run_disabled_tests));
  4351. EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
  4352. EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
  4353. EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
  4354. EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
  4355. EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
  4356. EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
  4357. EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
  4358. EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
  4359. EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
  4360. EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
  4361. EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
  4362. EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
  4363. }
  4364. // Parses a command line (specified by argc1 and argv1), then
  4365. // verifies that the flag values are expected and that the
  4366. // recognized flags are removed from the command line.
  4367. template <typename CharType>
  4368. static void TestParsingFlags(int argc1, const CharType** argv1,
  4369. int argc2, const CharType** argv2,
  4370. const Flags& expected, bool should_print_help) {
  4371. const bool saved_help_flag = ::testing::internal::g_help_flag;
  4372. ::testing::internal::g_help_flag = false;
  4373. #if GTEST_HAS_STREAM_REDIRECTION_
  4374. CaptureStdout();
  4375. #endif // GTEST_HAS_STREAM_REDIRECTION_
  4376. // Parses the command line.
  4377. internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
  4378. #if GTEST_HAS_STREAM_REDIRECTION_
  4379. const String captured_stdout = GetCapturedStdout();
  4380. #endif // GTEST_HAS_STREAM_REDIRECTION_
  4381. // Verifies the flag values.
  4382. CheckFlags(expected);
  4383. // Verifies that the recognized flags are removed from the command
  4384. // line.
  4385. AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
  4386. // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
  4387. // help message for the flags it recognizes.
  4388. EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
  4389. #if GTEST_HAS_STREAM_REDIRECTION_
  4390. const char* const expected_help_fragment =
  4391. "This program contains tests written using";
  4392. if (should_print_help) {
  4393. EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
  4394. } else {
  4395. EXPECT_PRED_FORMAT2(IsNotSubstring,
  4396. expected_help_fragment, captured_stdout);
  4397. }
  4398. #endif // GTEST_HAS_STREAM_REDIRECTION_
  4399. ::testing::internal::g_help_flag = saved_help_flag;
  4400. }
  4401. // This macro wraps TestParsingFlags s.t. the user doesn't need
  4402. // to specify the array sizes.
  4403. #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
  4404. TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
  4405. sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
  4406. expected, should_print_help)
  4407. };
  4408. // Tests parsing an empty command line.
  4409. TEST_F(InitGoogleTestTest, Empty) {
  4410. const char* argv[] = {
  4411. NULL
  4412. };
  4413. const char* argv2[] = {
  4414. NULL
  4415. };
  4416. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
  4417. }
  4418. // Tests parsing a command line that has no flag.
  4419. TEST_F(InitGoogleTestTest, NoFlag) {
  4420. const char* argv[] = {
  4421. "foo.exe",
  4422. NULL
  4423. };
  4424. const char* argv2[] = {
  4425. "foo.exe",
  4426. NULL
  4427. };
  4428. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
  4429. }
  4430. // Tests parsing a bad --gtest_filter flag.
  4431. TEST_F(InitGoogleTestTest, FilterBad) {
  4432. const char* argv[] = {
  4433. "foo.exe",
  4434. "--gtest_filter",
  4435. NULL
  4436. };
  4437. const char* argv2[] = {
  4438. "foo.exe",
  4439. "--gtest_filter",
  4440. NULL
  4441. };
  4442. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
  4443. }
  4444. // Tests parsing an empty --gtest_filter flag.
  4445. TEST_F(InitGoogleTestTest, FilterEmpty) {
  4446. const char* argv[] = {
  4447. "foo.exe",
  4448. "--gtest_filter=",
  4449. NULL
  4450. };
  4451. const char* argv2[] = {
  4452. "foo.exe",
  4453. NULL
  4454. };
  4455. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
  4456. }
  4457. // Tests parsing a non-empty --gtest_filter flag.
  4458. TEST_F(InitGoogleTestTest, FilterNonEmpty) {
  4459. const char* argv[] = {
  4460. "foo.exe",
  4461. "--gtest_filter=abc",
  4462. NULL
  4463. };
  4464. const char* argv2[] = {
  4465. "foo.exe",
  4466. NULL
  4467. };
  4468. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
  4469. }
  4470. // Tests parsing --gtest_break_on_failure.
  4471. TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) {
  4472. const char* argv[] = {
  4473. "foo.exe",
  4474. "--gtest_break_on_failure",
  4475. NULL
  4476. };
  4477. const char* argv2[] = {
  4478. "foo.exe",
  4479. NULL
  4480. };
  4481. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
  4482. }
  4483. // Tests parsing --gtest_break_on_failure=0.
  4484. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) {
  4485. const char* argv[] = {
  4486. "foo.exe",
  4487. "--gtest_break_on_failure=0",
  4488. NULL
  4489. };
  4490. const char* argv2[] = {
  4491. "foo.exe",
  4492. NULL
  4493. };
  4494. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
  4495. }
  4496. // Tests parsing --gtest_break_on_failure=f.
  4497. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) {
  4498. const char* argv[] = {
  4499. "foo.exe",
  4500. "--gtest_break_on_failure=f",
  4501. NULL
  4502. };
  4503. const char* argv2[] = {
  4504. "foo.exe",
  4505. NULL
  4506. };
  4507. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
  4508. }
  4509. // Tests parsing --gtest_break_on_failure=F.
  4510. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) {
  4511. const char* argv[] = {
  4512. "foo.exe",
  4513. "--gtest_break_on_failure=F",
  4514. NULL
  4515. };
  4516. const char* argv2[] = {
  4517. "foo.exe",
  4518. NULL
  4519. };
  4520. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
  4521. }
  4522. // Tests parsing a --gtest_break_on_failure flag that has a "true"
  4523. // definition.
  4524. TEST_F(InitGoogleTestTest, BreakOnFailureTrue) {
  4525. const char* argv[] = {
  4526. "foo.exe",
  4527. "--gtest_break_on_failure=1",
  4528. NULL
  4529. };
  4530. const char* argv2[] = {
  4531. "foo.exe",
  4532. NULL
  4533. };
  4534. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
  4535. }
  4536. // Tests parsing --gtest_catch_exceptions.
  4537. TEST_F(InitGoogleTestTest, CatchExceptions) {
  4538. const char* argv[] = {
  4539. "foo.exe",
  4540. "--gtest_catch_exceptions",
  4541. NULL
  4542. };
  4543. const char* argv2[] = {
  4544. "foo.exe",
  4545. NULL
  4546. };
  4547. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
  4548. }
  4549. // Tests parsing --gtest_death_test_use_fork.
  4550. TEST_F(InitGoogleTestTest, DeathTestUseFork) {
  4551. const char* argv[] = {
  4552. "foo.exe",
  4553. "--gtest_death_test_use_fork",
  4554. NULL
  4555. };
  4556. const char* argv2[] = {
  4557. "foo.exe",
  4558. NULL
  4559. };
  4560. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
  4561. }
  4562. // Tests having the same flag twice with different values. The
  4563. // expected behavior is that the one coming last takes precedence.
  4564. TEST_F(InitGoogleTestTest, DuplicatedFlags) {
  4565. const char* argv[] = {
  4566. "foo.exe",
  4567. "--gtest_filter=a",
  4568. "--gtest_filter=b",
  4569. NULL
  4570. };
  4571. const char* argv2[] = {
  4572. "foo.exe",
  4573. NULL
  4574. };
  4575. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
  4576. }
  4577. // Tests having an unrecognized flag on the command line.
  4578. TEST_F(InitGoogleTestTest, UnrecognizedFlag) {
  4579. const char* argv[] = {
  4580. "foo.exe",
  4581. "--gtest_break_on_failure",
  4582. "bar", // Unrecognized by Google Test.
  4583. "--gtest_filter=b",
  4584. NULL
  4585. };
  4586. const char* argv2[] = {
  4587. "foo.exe",
  4588. "bar",
  4589. NULL
  4590. };
  4591. Flags flags;
  4592. flags.break_on_failure = true;
  4593. flags.filter = "b";
  4594. GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
  4595. }
  4596. // Tests having a --gtest_list_tests flag
  4597. TEST_F(InitGoogleTestTest, ListTestsFlag) {
  4598. const char* argv[] = {
  4599. "foo.exe",
  4600. "--gtest_list_tests",
  4601. NULL
  4602. };
  4603. const char* argv2[] = {
  4604. "foo.exe",
  4605. NULL
  4606. };
  4607. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
  4608. }
  4609. // Tests having a --gtest_list_tests flag with a "true" value
  4610. TEST_F(InitGoogleTestTest, ListTestsTrue) {
  4611. const char* argv[] = {
  4612. "foo.exe",
  4613. "--gtest_list_tests=1",
  4614. NULL
  4615. };
  4616. const char* argv2[] = {
  4617. "foo.exe",
  4618. NULL
  4619. };
  4620. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
  4621. }
  4622. // Tests having a --gtest_list_tests flag with a "false" value
  4623. TEST_F(InitGoogleTestTest, ListTestsFalse) {
  4624. const char* argv[] = {
  4625. "foo.exe",
  4626. "--gtest_list_tests=0",
  4627. NULL
  4628. };
  4629. const char* argv2[] = {
  4630. "foo.exe",
  4631. NULL
  4632. };
  4633. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
  4634. }
  4635. // Tests parsing --gtest_list_tests=f.
  4636. TEST_F(InitGoogleTestTest, ListTestsFalse_f) {
  4637. const char* argv[] = {
  4638. "foo.exe",
  4639. "--gtest_list_tests=f",
  4640. NULL
  4641. };
  4642. const char* argv2[] = {
  4643. "foo.exe",
  4644. NULL
  4645. };
  4646. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
  4647. }
  4648. // Tests parsing --gtest_list_tests=F.
  4649. TEST_F(InitGoogleTestTest, ListTestsFalse_F) {
  4650. const char* argv[] = {
  4651. "foo.exe",
  4652. "--gtest_list_tests=F",
  4653. NULL
  4654. };
  4655. const char* argv2[] = {
  4656. "foo.exe",
  4657. NULL
  4658. };
  4659. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
  4660. }
  4661. // Tests parsing --gtest_output (invalid).
  4662. TEST_F(InitGoogleTestTest, OutputEmpty) {
  4663. const char* argv[] = {
  4664. "foo.exe",
  4665. "--gtest_output",
  4666. NULL
  4667. };
  4668. const char* argv2[] = {
  4669. "foo.exe",
  4670. "--gtest_output",
  4671. NULL
  4672. };
  4673. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
  4674. }
  4675. // Tests parsing --gtest_output=xml
  4676. TEST_F(InitGoogleTestTest, OutputXml) {
  4677. const char* argv[] = {
  4678. "foo.exe",
  4679. "--gtest_output=xml",
  4680. NULL
  4681. };
  4682. const char* argv2[] = {
  4683. "foo.exe",
  4684. NULL
  4685. };
  4686. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
  4687. }
  4688. // Tests parsing --gtest_output=xml:file
  4689. TEST_F(InitGoogleTestTest, OutputXmlFile) {
  4690. const char* argv[] = {
  4691. "foo.exe",
  4692. "--gtest_output=xml:file",
  4693. NULL
  4694. };
  4695. const char* argv2[] = {
  4696. "foo.exe",
  4697. NULL
  4698. };
  4699. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
  4700. }
  4701. // Tests parsing --gtest_output=xml:directory/path/
  4702. TEST_F(InitGoogleTestTest, OutputXmlDirectory) {
  4703. const char* argv[] = {
  4704. "foo.exe",
  4705. "--gtest_output=xml:directory/path/",
  4706. NULL
  4707. };
  4708. const char* argv2[] = {
  4709. "foo.exe",
  4710. NULL
  4711. };
  4712. GTEST_TEST_PARSING_FLAGS_(argv, argv2,
  4713. Flags::Output("xml:directory/path/"), false);
  4714. }
  4715. // Tests having a --gtest_print_time flag
  4716. TEST_F(InitGoogleTestTest, PrintTimeFlag) {
  4717. const char* argv[] = {
  4718. "foo.exe",
  4719. "--gtest_print_time",
  4720. NULL
  4721. };
  4722. const char* argv2[] = {
  4723. "foo.exe",
  4724. NULL
  4725. };
  4726. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
  4727. }
  4728. // Tests having a --gtest_print_time flag with a "true" value
  4729. TEST_F(InitGoogleTestTest, PrintTimeTrue) {
  4730. const char* argv[] = {
  4731. "foo.exe",
  4732. "--gtest_print_time=1",
  4733. NULL
  4734. };
  4735. const char* argv2[] = {
  4736. "foo.exe",
  4737. NULL
  4738. };
  4739. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
  4740. }
  4741. // Tests having a --gtest_print_time flag with a "false" value
  4742. TEST_F(InitGoogleTestTest, PrintTimeFalse) {
  4743. const char* argv[] = {
  4744. "foo.exe",
  4745. "--gtest_print_time=0",
  4746. NULL
  4747. };
  4748. const char* argv2[] = {
  4749. "foo.exe",
  4750. NULL
  4751. };
  4752. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
  4753. }
  4754. // Tests parsing --gtest_print_time=f.
  4755. TEST_F(InitGoogleTestTest, PrintTimeFalse_f) {
  4756. const char* argv[] = {
  4757. "foo.exe",
  4758. "--gtest_print_time=f",
  4759. NULL
  4760. };
  4761. const char* argv2[] = {
  4762. "foo.exe",
  4763. NULL
  4764. };
  4765. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
  4766. }
  4767. // Tests parsing --gtest_print_time=F.
  4768. TEST_F(InitGoogleTestTest, PrintTimeFalse_F) {
  4769. const char* argv[] = {
  4770. "foo.exe",
  4771. "--gtest_print_time=F",
  4772. NULL
  4773. };
  4774. const char* argv2[] = {
  4775. "foo.exe",
  4776. NULL
  4777. };
  4778. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
  4779. }
  4780. // Tests parsing --gtest_random_seed=number
  4781. TEST_F(InitGoogleTestTest, RandomSeed) {
  4782. const char* argv[] = {
  4783. "foo.exe",
  4784. "--gtest_random_seed=1000",
  4785. NULL
  4786. };
  4787. const char* argv2[] = {
  4788. "foo.exe",
  4789. NULL
  4790. };
  4791. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
  4792. }
  4793. // Tests parsing --gtest_repeat=number
  4794. TEST_F(InitGoogleTestTest, Repeat) {
  4795. const char* argv[] = {
  4796. "foo.exe",
  4797. "--gtest_repeat=1000",
  4798. NULL
  4799. };
  4800. const char* argv2[] = {
  4801. "foo.exe",
  4802. NULL
  4803. };
  4804. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
  4805. }
  4806. // Tests having a --gtest_also_run_disabled_tests flag
  4807. TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) {
  4808. const char* argv[] = {
  4809. "foo.exe",
  4810. "--gtest_also_run_disabled_tests",
  4811. NULL
  4812. };
  4813. const char* argv2[] = {
  4814. "foo.exe",
  4815. NULL
  4816. };
  4817. GTEST_TEST_PARSING_FLAGS_(argv, argv2,
  4818. Flags::AlsoRunDisabledTests(true), false);
  4819. }
  4820. // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
  4821. TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) {
  4822. const char* argv[] = {
  4823. "foo.exe",
  4824. "--gtest_also_run_disabled_tests=1",
  4825. NULL
  4826. };
  4827. const char* argv2[] = {
  4828. "foo.exe",
  4829. NULL
  4830. };
  4831. GTEST_TEST_PARSING_FLAGS_(argv, argv2,
  4832. Flags::AlsoRunDisabledTests(true), false);
  4833. }
  4834. // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
  4835. TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) {
  4836. const char* argv[] = {
  4837. "foo.exe",
  4838. "--gtest_also_run_disabled_tests=0",
  4839. NULL
  4840. };
  4841. const char* argv2[] = {
  4842. "foo.exe",
  4843. NULL
  4844. };
  4845. GTEST_TEST_PARSING_FLAGS_(argv, argv2,
  4846. Flags::AlsoRunDisabledTests(false), false);
  4847. }
  4848. // Tests parsing --gtest_shuffle.
  4849. TEST_F(InitGoogleTestTest, ShuffleWithoutValue) {
  4850. const char* argv[] = {
  4851. "foo.exe",
  4852. "--gtest_shuffle",
  4853. NULL
  4854. };
  4855. const char* argv2[] = {
  4856. "foo.exe",
  4857. NULL
  4858. };
  4859. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
  4860. }
  4861. // Tests parsing --gtest_shuffle=0.
  4862. TEST_F(InitGoogleTestTest, ShuffleFalse_0) {
  4863. const char* argv[] = {
  4864. "foo.exe",
  4865. "--gtest_shuffle=0",
  4866. NULL
  4867. };
  4868. const char* argv2[] = {
  4869. "foo.exe",
  4870. NULL
  4871. };
  4872. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
  4873. }
  4874. // Tests parsing a --gtest_shuffle flag that has a "true"
  4875. // definition.
  4876. TEST_F(InitGoogleTestTest, ShuffleTrue) {
  4877. const char* argv[] = {
  4878. "foo.exe",
  4879. "--gtest_shuffle=1",
  4880. NULL
  4881. };
  4882. const char* argv2[] = {
  4883. "foo.exe",
  4884. NULL
  4885. };
  4886. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
  4887. }
  4888. // Tests parsing --gtest_stack_trace_depth=number.
  4889. TEST_F(InitGoogleTestTest, StackTraceDepth) {
  4890. const char* argv[] = {
  4891. "foo.exe",
  4892. "--gtest_stack_trace_depth=5",
  4893. NULL
  4894. };
  4895. const char* argv2[] = {
  4896. "foo.exe",
  4897. NULL
  4898. };
  4899. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
  4900. }
  4901. // Tests parsing --gtest_throw_on_failure.
  4902. TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) {
  4903. const char* argv[] = {
  4904. "foo.exe",
  4905. "--gtest_throw_on_failure",
  4906. NULL
  4907. };
  4908. const char* argv2[] = {
  4909. "foo.exe",
  4910. NULL
  4911. };
  4912. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
  4913. }
  4914. // Tests parsing --gtest_throw_on_failure=0.
  4915. TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) {
  4916. const char* argv[] = {
  4917. "foo.exe",
  4918. "--gtest_throw_on_failure=0",
  4919. NULL
  4920. };
  4921. const char* argv2[] = {
  4922. "foo.exe",
  4923. NULL
  4924. };
  4925. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
  4926. }
  4927. // Tests parsing a --gtest_throw_on_failure flag that has a "true"
  4928. // definition.
  4929. TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) {
  4930. const char* argv[] = {
  4931. "foo.exe",
  4932. "--gtest_throw_on_failure=1",
  4933. NULL
  4934. };
  4935. const char* argv2[] = {
  4936. "foo.exe",
  4937. NULL
  4938. };
  4939. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
  4940. }
  4941. #if GTEST_OS_WINDOWS
  4942. // Tests parsing wide strings.
  4943. TEST_F(InitGoogleTestTest, WideStrings) {
  4944. const wchar_t* argv[] = {
  4945. L"foo.exe",
  4946. L"--gtest_filter=Foo*",
  4947. L"--gtest_list_tests=1",
  4948. L"--gtest_break_on_failure",
  4949. L"--non_gtest_flag",
  4950. NULL
  4951. };
  4952. const wchar_t* argv2[] = {
  4953. L"foo.exe",
  4954. L"--non_gtest_flag",
  4955. NULL
  4956. };
  4957. Flags expected_flags;
  4958. expected_flags.break_on_failure = true;
  4959. expected_flags.filter = "Foo*";
  4960. expected_flags.list_tests = true;
  4961. GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
  4962. }
  4963. #endif // GTEST_OS_WINDOWS
  4964. // Tests current_test_info() in UnitTest.
  4965. class CurrentTestInfoTest : public Test {
  4966. protected:
  4967. // Tests that current_test_info() returns NULL before the first test in
  4968. // the test case is run.
  4969. static void SetUpTestCase() {
  4970. // There should be no tests running at this point.
  4971. const TestInfo* test_info =
  4972. UnitTest::GetInstance()->current_test_info();
  4973. EXPECT_TRUE(test_info == NULL)
  4974. << "There should be no tests running at this point.";
  4975. }
  4976. // Tests that current_test_info() returns NULL after the last test in
  4977. // the test case has run.
  4978. static void TearDownTestCase() {
  4979. const TestInfo* test_info =
  4980. UnitTest::GetInstance()->current_test_info();
  4981. EXPECT_TRUE(test_info == NULL)
  4982. << "There should be no tests running at this point.";
  4983. }
  4984. };
  4985. // Tests that current_test_info() returns TestInfo for currently running
  4986. // test by checking the expected test name against the actual one.
  4987. TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) {
  4988. const TestInfo* test_info =
  4989. UnitTest::GetInstance()->current_test_info();
  4990. ASSERT_TRUE(NULL != test_info)
  4991. << "There is a test running so we should have a valid TestInfo.";
  4992. EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
  4993. << "Expected the name of the currently running test case.";
  4994. EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name())
  4995. << "Expected the name of the currently running test.";
  4996. }
  4997. // Tests that current_test_info() returns TestInfo for currently running
  4998. // test by checking the expected test name against the actual one. We
  4999. // use this test to see that the TestInfo object actually changed from
  5000. // the previous invocation.
  5001. TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) {
  5002. const TestInfo* test_info =
  5003. UnitTest::GetInstance()->current_test_info();
  5004. ASSERT_TRUE(NULL != test_info)
  5005. << "There is a test running so we should have a valid TestInfo.";
  5006. EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
  5007. << "Expected the name of the currently running test case.";
  5008. EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name())
  5009. << "Expected the name of the currently running test.";
  5010. }
  5011. } // namespace testing
  5012. // These two lines test that we can define tests in a namespace that
  5013. // has the name "testing" and is nested in another namespace.
  5014. namespace my_namespace {
  5015. namespace testing {
  5016. // Makes sure that TEST knows to use ::testing::Test instead of
  5017. // ::my_namespace::testing::Test.
  5018. class Test {};
  5019. // Makes sure that an assertion knows to use ::testing::Message instead of
  5020. // ::my_namespace::testing::Message.
  5021. class Message {};
  5022. // Makes sure that an assertion knows to use
  5023. // ::testing::AssertionResult instead of
  5024. // ::my_namespace::testing::AssertionResult.
  5025. class AssertionResult {};
  5026. // Tests that an assertion that should succeed works as expected.
  5027. TEST(NestedTestingNamespaceTest, Success) {
  5028. EXPECT_EQ(1, 1) << "This shouldn't fail.";
  5029. }
  5030. // Tests that an assertion that should fail works as expected.
  5031. TEST(NestedTestingNamespaceTest, Failure) {
  5032. EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
  5033. "This failure is expected.");
  5034. }
  5035. } // namespace testing
  5036. } // namespace my_namespace
  5037. // Tests that one can call superclass SetUp and TearDown methods--
  5038. // that is, that they are not private.
  5039. // No tests are based on this fixture; the test "passes" if it compiles
  5040. // successfully.
  5041. class ProtectedFixtureMethodsTest : public Test {
  5042. protected:
  5043. virtual void SetUp() {
  5044. Test::SetUp();
  5045. }
  5046. virtual void TearDown() {
  5047. Test::TearDown();
  5048. }
  5049. };
  5050. // StreamingAssertionsTest tests the streaming versions of a representative
  5051. // sample of assertions.
  5052. TEST(StreamingAssertionsTest, Unconditional) {
  5053. SUCCEED() << "expected success";
  5054. EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
  5055. "expected failure");
  5056. EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
  5057. "expected failure");
  5058. }
  5059. #ifdef __BORLANDC__
  5060. // Silences warnings: "Condition is always true", "Unreachable code"
  5061. #pragma option push -w-ccc -w-rch
  5062. #endif
  5063. TEST(StreamingAssertionsTest, Truth) {
  5064. EXPECT_TRUE(true) << "unexpected failure";
  5065. ASSERT_TRUE(true) << "unexpected failure";
  5066. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
  5067. "expected failure");
  5068. EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
  5069. "expected failure");
  5070. }
  5071. TEST(StreamingAssertionsTest, Truth2) {
  5072. EXPECT_FALSE(false) << "unexpected failure";
  5073. ASSERT_FALSE(false) << "unexpected failure";
  5074. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
  5075. "expected failure");
  5076. EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
  5077. "expected failure");
  5078. }
  5079. #ifdef __BORLANDC__
  5080. // Restores warnings after previous "#pragma option push" supressed them
  5081. #pragma option pop
  5082. #endif
  5083. TEST(StreamingAssertionsTest, IntegerEquals) {
  5084. EXPECT_EQ(1, 1) << "unexpected failure";
  5085. ASSERT_EQ(1, 1) << "unexpected failure";
  5086. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
  5087. "expected failure");
  5088. EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
  5089. "expected failure");
  5090. }
  5091. TEST(StreamingAssertionsTest, IntegerLessThan) {
  5092. EXPECT_LT(1, 2) << "unexpected failure";
  5093. ASSERT_LT(1, 2) << "unexpected failure";
  5094. EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
  5095. "expected failure");
  5096. EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
  5097. "expected failure");
  5098. }
  5099. TEST(StreamingAssertionsTest, StringsEqual) {
  5100. EXPECT_STREQ("foo", "foo") << "unexpected failure";
  5101. ASSERT_STREQ("foo", "foo") << "unexpected failure";
  5102. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
  5103. "expected failure");
  5104. EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
  5105. "expected failure");
  5106. }
  5107. TEST(StreamingAssertionsTest, StringsNotEqual) {
  5108. EXPECT_STRNE("foo", "bar") << "unexpected failure";
  5109. ASSERT_STRNE("foo", "bar") << "unexpected failure";
  5110. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
  5111. "expected failure");
  5112. EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
  5113. "expected failure");
  5114. }
  5115. TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
  5116. EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
  5117. ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
  5118. EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
  5119. "expected failure");
  5120. EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
  5121. "expected failure");
  5122. }
  5123. TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
  5124. EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
  5125. ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
  5126. EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
  5127. "expected failure");
  5128. EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
  5129. "expected failure");
  5130. }
  5131. TEST(StreamingAssertionsTest, FloatingPointEquals) {
  5132. EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
  5133. ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
  5134. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
  5135. "expected failure");
  5136. EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
  5137. "expected failure");
  5138. }
  5139. #if GTEST_HAS_EXCEPTIONS
  5140. TEST(StreamingAssertionsTest, Throw) {
  5141. EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
  5142. ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
  5143. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
  5144. "expected failure", "expected failure");
  5145. EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
  5146. "expected failure", "expected failure");
  5147. }
  5148. TEST(StreamingAssertionsTest, NoThrow) {
  5149. EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
  5150. ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
  5151. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
  5152. "expected failure", "expected failure");
  5153. EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
  5154. "expected failure", "expected failure");
  5155. }
  5156. TEST(StreamingAssertionsTest, AnyThrow) {
  5157. EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
  5158. ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
  5159. EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
  5160. "expected failure", "expected failure");
  5161. EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
  5162. "expected failure", "expected failure");
  5163. }
  5164. #endif // GTEST_HAS_EXCEPTIONS
  5165. // Tests that Google Test correctly decides whether to use colors in the output.
  5166. TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
  5167. GTEST_FLAG(color) = "yes";
  5168. SetEnv("TERM", "xterm"); // TERM supports colors.
  5169. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5170. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5171. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5172. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5173. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5174. }
  5175. TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
  5176. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5177. GTEST_FLAG(color) = "True";
  5178. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5179. GTEST_FLAG(color) = "t";
  5180. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5181. GTEST_FLAG(color) = "1";
  5182. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5183. }
  5184. TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
  5185. GTEST_FLAG(color) = "no";
  5186. SetEnv("TERM", "xterm"); // TERM supports colors.
  5187. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5188. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
  5189. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5190. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5191. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
  5192. }
  5193. TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
  5194. SetEnv("TERM", "xterm"); // TERM supports colors.
  5195. GTEST_FLAG(color) = "F";
  5196. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5197. GTEST_FLAG(color) = "0";
  5198. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5199. GTEST_FLAG(color) = "unknown";
  5200. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5201. }
  5202. TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
  5203. GTEST_FLAG(color) = "auto";
  5204. SetEnv("TERM", "xterm"); // TERM supports colors.
  5205. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
  5206. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5207. }
  5208. TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
  5209. GTEST_FLAG(color) = "auto";
  5210. #if GTEST_OS_WINDOWS
  5211. // On Windows, we ignore the TERM variable as it's usually not set.
  5212. SetEnv("TERM", "dumb");
  5213. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5214. SetEnv("TERM", "");
  5215. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5216. SetEnv("TERM", "xterm");
  5217. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5218. #else
  5219. // On non-Windows platforms, we rely on TERM to determine if the
  5220. // terminal supports colors.
  5221. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5222. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5223. SetEnv("TERM", "emacs"); // TERM doesn't support colors.
  5224. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5225. SetEnv("TERM", "vt100"); // TERM doesn't support colors.
  5226. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5227. SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
  5228. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5229. SetEnv("TERM", "xterm"); // TERM supports colors.
  5230. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5231. SetEnv("TERM", "xterm-color"); // TERM supports colors.
  5232. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5233. SetEnv("TERM", "linux"); // TERM supports colors.
  5234. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5235. #endif // GTEST_OS_WINDOWS
  5236. }
  5237. // Verifies that StaticAssertTypeEq works in a namespace scope.
  5238. static bool dummy1 = StaticAssertTypeEq<bool, bool>();
  5239. static bool dummy2 = StaticAssertTypeEq<const int, const int>();
  5240. // Verifies that StaticAssertTypeEq works in a class.
  5241. template <typename T>
  5242. class StaticAssertTypeEqTestHelper {
  5243. public:
  5244. StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
  5245. };
  5246. TEST(StaticAssertTypeEqTest, WorksInClass) {
  5247. StaticAssertTypeEqTestHelper<bool>();
  5248. }
  5249. // Verifies that StaticAssertTypeEq works inside a function.
  5250. typedef int IntAlias;
  5251. TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
  5252. StaticAssertTypeEq<int, IntAlias>();
  5253. StaticAssertTypeEq<int*, IntAlias*>();
  5254. }
  5255. TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) {
  5256. testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
  5257. // We don't have a stack walker in Google Test yet.
  5258. EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str());
  5259. EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str());
  5260. }
  5261. TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
  5262. EXPECT_FALSE(HasNonfatalFailure());
  5263. }
  5264. static void FailFatally() { FAIL(); }
  5265. TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
  5266. FailFatally();
  5267. const bool has_nonfatal_failure = HasNonfatalFailure();
  5268. ClearCurrentTestPartResults();
  5269. EXPECT_FALSE(has_nonfatal_failure);
  5270. }
  5271. TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
  5272. ADD_FAILURE();
  5273. const bool has_nonfatal_failure = HasNonfatalFailure();
  5274. ClearCurrentTestPartResults();
  5275. EXPECT_TRUE(has_nonfatal_failure);
  5276. }
  5277. TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
  5278. FailFatally();
  5279. ADD_FAILURE();
  5280. const bool has_nonfatal_failure = HasNonfatalFailure();
  5281. ClearCurrentTestPartResults();
  5282. EXPECT_TRUE(has_nonfatal_failure);
  5283. }
  5284. // A wrapper for calling HasNonfatalFailure outside of a test body.
  5285. static bool HasNonfatalFailureHelper() {
  5286. return testing::Test::HasNonfatalFailure();
  5287. }
  5288. TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
  5289. EXPECT_FALSE(HasNonfatalFailureHelper());
  5290. }
  5291. TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
  5292. ADD_FAILURE();
  5293. const bool has_nonfatal_failure = HasNonfatalFailureHelper();
  5294. ClearCurrentTestPartResults();
  5295. EXPECT_TRUE(has_nonfatal_failure);
  5296. }
  5297. TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
  5298. EXPECT_FALSE(HasFailure());
  5299. }
  5300. TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
  5301. FailFatally();
  5302. const bool has_failure = HasFailure();
  5303. ClearCurrentTestPartResults();
  5304. EXPECT_TRUE(has_failure);
  5305. }
  5306. TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
  5307. ADD_FAILURE();
  5308. const bool has_failure = HasFailure();
  5309. ClearCurrentTestPartResults();
  5310. EXPECT_TRUE(has_failure);
  5311. }
  5312. TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
  5313. FailFatally();
  5314. ADD_FAILURE();
  5315. const bool has_failure = HasFailure();
  5316. ClearCurrentTestPartResults();
  5317. EXPECT_TRUE(has_failure);
  5318. }
  5319. // A wrapper for calling HasFailure outside of a test body.
  5320. static bool HasFailureHelper() { return testing::Test::HasFailure(); }
  5321. TEST(HasFailureTest, WorksOutsideOfTestBody) {
  5322. EXPECT_FALSE(HasFailureHelper());
  5323. }
  5324. TEST(HasFailureTest, WorksOutsideOfTestBody2) {
  5325. ADD_FAILURE();
  5326. const bool has_failure = HasFailureHelper();
  5327. ClearCurrentTestPartResults();
  5328. EXPECT_TRUE(has_failure);
  5329. }
  5330. class TestListener : public EmptyTestEventListener {
  5331. public:
  5332. TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {}
  5333. TestListener(int* on_start_counter, bool* is_destroyed)
  5334. : on_start_counter_(on_start_counter),
  5335. is_destroyed_(is_destroyed) {}
  5336. virtual ~TestListener() {
  5337. if (is_destroyed_)
  5338. *is_destroyed_ = true;
  5339. }
  5340. protected:
  5341. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
  5342. if (on_start_counter_ != NULL)
  5343. (*on_start_counter_)++;
  5344. }
  5345. private:
  5346. int* on_start_counter_;
  5347. bool* is_destroyed_;
  5348. };
  5349. // Tests the constructor.
  5350. TEST(TestEventListenersTest, ConstructionWorks) {
  5351. TestEventListeners listeners;
  5352. EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL);
  5353. EXPECT_TRUE(listeners.default_result_printer() == NULL);
  5354. EXPECT_TRUE(listeners.default_xml_generator() == NULL);
  5355. }
  5356. // Tests that the TestEventListeners destructor deletes all the listeners it
  5357. // owns.
  5358. TEST(TestEventListenersTest, DestructionWorks) {
  5359. bool default_result_printer_is_destroyed = false;
  5360. bool default_xml_printer_is_destroyed = false;
  5361. bool extra_listener_is_destroyed = false;
  5362. TestListener* default_result_printer = new TestListener(
  5363. NULL, &default_result_printer_is_destroyed);
  5364. TestListener* default_xml_printer = new TestListener(
  5365. NULL, &default_xml_printer_is_destroyed);
  5366. TestListener* extra_listener = new TestListener(
  5367. NULL, &extra_listener_is_destroyed);
  5368. {
  5369. TestEventListeners listeners;
  5370. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
  5371. default_result_printer);
  5372. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
  5373. default_xml_printer);
  5374. listeners.Append(extra_listener);
  5375. }
  5376. EXPECT_TRUE(default_result_printer_is_destroyed);
  5377. EXPECT_TRUE(default_xml_printer_is_destroyed);
  5378. EXPECT_TRUE(extra_listener_is_destroyed);
  5379. }
  5380. // Tests that a listener Append'ed to a TestEventListeners list starts
  5381. // receiving events.
  5382. TEST(TestEventListenersTest, Append) {
  5383. int on_start_counter = 0;
  5384. bool is_destroyed = false;
  5385. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5386. {
  5387. TestEventListeners listeners;
  5388. listeners.Append(listener);
  5389. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5390. *UnitTest::GetInstance());
  5391. EXPECT_EQ(1, on_start_counter);
  5392. }
  5393. EXPECT_TRUE(is_destroyed);
  5394. }
  5395. // Tests that listeners receive events in the order they were appended to
  5396. // the list, except for *End requests, which must be received in the reverse
  5397. // order.
  5398. class SequenceTestingListener : public EmptyTestEventListener {
  5399. public:
  5400. SequenceTestingListener(std::vector<String>* vector, const char* id)
  5401. : vector_(vector), id_(id) {}
  5402. protected:
  5403. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
  5404. vector_->push_back(GetEventDescription("OnTestProgramStart"));
  5405. }
  5406. virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
  5407. vector_->push_back(GetEventDescription("OnTestProgramEnd"));
  5408. }
  5409. virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
  5410. int /*iteration*/) {
  5411. vector_->push_back(GetEventDescription("OnTestIterationStart"));
  5412. }
  5413. virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
  5414. int /*iteration*/) {
  5415. vector_->push_back(GetEventDescription("OnTestIterationEnd"));
  5416. }
  5417. private:
  5418. String GetEventDescription(const char* method) {
  5419. Message message;
  5420. message << id_ << "." << method;
  5421. return message.GetString();
  5422. }
  5423. std::vector<String>* vector_;
  5424. const char* const id_;
  5425. GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
  5426. };
  5427. TEST(EventListenerTest, AppendKeepsOrder) {
  5428. std::vector<String> vec;
  5429. TestEventListeners listeners;
  5430. listeners.Append(new SequenceTestingListener(&vec, "1st"));
  5431. listeners.Append(new SequenceTestingListener(&vec, "2nd"));
  5432. listeners.Append(new SequenceTestingListener(&vec, "3rd"));
  5433. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5434. *UnitTest::GetInstance());
  5435. ASSERT_EQ(3U, vec.size());
  5436. EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
  5437. EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
  5438. EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
  5439. vec.clear();
  5440. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
  5441. *UnitTest::GetInstance());
  5442. ASSERT_EQ(3U, vec.size());
  5443. EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
  5444. EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
  5445. EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
  5446. vec.clear();
  5447. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
  5448. *UnitTest::GetInstance(), 0);
  5449. ASSERT_EQ(3U, vec.size());
  5450. EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
  5451. EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
  5452. EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
  5453. vec.clear();
  5454. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
  5455. *UnitTest::GetInstance(), 0);
  5456. ASSERT_EQ(3U, vec.size());
  5457. EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
  5458. EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
  5459. EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
  5460. }
  5461. // Tests that a listener removed from a TestEventListeners list stops receiving
  5462. // events and is not deleted when the list is destroyed.
  5463. TEST(TestEventListenersTest, Release) {
  5464. int on_start_counter = 0;
  5465. bool is_destroyed = false;
  5466. // Although Append passes the ownership of this object to the list,
  5467. // the following calls release it, and we need to delete it before the
  5468. // test ends.
  5469. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5470. {
  5471. TestEventListeners listeners;
  5472. listeners.Append(listener);
  5473. EXPECT_EQ(listener, listeners.Release(listener));
  5474. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5475. *UnitTest::GetInstance());
  5476. EXPECT_TRUE(listeners.Release(listener) == NULL);
  5477. }
  5478. EXPECT_EQ(0, on_start_counter);
  5479. EXPECT_FALSE(is_destroyed);
  5480. delete listener;
  5481. }
  5482. // Tests that no events are forwarded when event forwarding is disabled.
  5483. TEST(EventListenerTest, SuppressEventForwarding) {
  5484. int on_start_counter = 0;
  5485. TestListener* listener = new TestListener(&on_start_counter, NULL);
  5486. TestEventListeners listeners;
  5487. listeners.Append(listener);
  5488. ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
  5489. TestEventListenersAccessor::SuppressEventForwarding(&listeners);
  5490. ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
  5491. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5492. *UnitTest::GetInstance());
  5493. EXPECT_EQ(0, on_start_counter);
  5494. }
  5495. // Tests that events generated by Google Test are not forwarded in
  5496. // death test subprocesses.
  5497. TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
  5498. EXPECT_DEATH_IF_SUPPORTED({
  5499. GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
  5500. *GetUnitTestImpl()->listeners())) << "expected failure";},
  5501. "expected failure");
  5502. }
  5503. // Tests that a listener installed via SetDefaultResultPrinter() starts
  5504. // receiving events and is returned via default_result_printer() and that
  5505. // the previous default_result_printer is removed from the list and deleted.
  5506. TEST(EventListenerTest, default_result_printer) {
  5507. int on_start_counter = 0;
  5508. bool is_destroyed = false;
  5509. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5510. TestEventListeners listeners;
  5511. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
  5512. EXPECT_EQ(listener, listeners.default_result_printer());
  5513. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5514. *UnitTest::GetInstance());
  5515. EXPECT_EQ(1, on_start_counter);
  5516. // Replacing default_result_printer with something else should remove it
  5517. // from the list and destroy it.
  5518. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL);
  5519. EXPECT_TRUE(listeners.default_result_printer() == NULL);
  5520. EXPECT_TRUE(is_destroyed);
  5521. // After broadcasting an event the counter is still the same, indicating
  5522. // the listener is not in the list anymore.
  5523. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5524. *UnitTest::GetInstance());
  5525. EXPECT_EQ(1, on_start_counter);
  5526. }
  5527. // Tests that the default_result_printer listener stops receiving events
  5528. // when removed via Release and that is not owned by the list anymore.
  5529. TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
  5530. int on_start_counter = 0;
  5531. bool is_destroyed = false;
  5532. // Although Append passes the ownership of this object to the list,
  5533. // the following calls release it, and we need to delete it before the
  5534. // test ends.
  5535. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5536. {
  5537. TestEventListeners listeners;
  5538. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
  5539. EXPECT_EQ(listener, listeners.Release(listener));
  5540. EXPECT_TRUE(listeners.default_result_printer() == NULL);
  5541. EXPECT_FALSE(is_destroyed);
  5542. // Broadcasting events now should not affect default_result_printer.
  5543. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5544. *UnitTest::GetInstance());
  5545. EXPECT_EQ(0, on_start_counter);
  5546. }
  5547. // Destroying the list should not affect the listener now, too.
  5548. EXPECT_FALSE(is_destroyed);
  5549. delete listener;
  5550. }
  5551. // Tests that a listener installed via SetDefaultXmlGenerator() starts
  5552. // receiving events and is returned via default_xml_generator() and that
  5553. // the previous default_xml_generator is removed from the list and deleted.
  5554. TEST(EventListenerTest, default_xml_generator) {
  5555. int on_start_counter = 0;
  5556. bool is_destroyed = false;
  5557. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5558. TestEventListeners listeners;
  5559. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
  5560. EXPECT_EQ(listener, listeners.default_xml_generator());
  5561. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5562. *UnitTest::GetInstance());
  5563. EXPECT_EQ(1, on_start_counter);
  5564. // Replacing default_xml_generator with something else should remove it
  5565. // from the list and destroy it.
  5566. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL);
  5567. EXPECT_TRUE(listeners.default_xml_generator() == NULL);
  5568. EXPECT_TRUE(is_destroyed);
  5569. // After broadcasting an event the counter is still the same, indicating
  5570. // the listener is not in the list anymore.
  5571. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5572. *UnitTest::GetInstance());
  5573. EXPECT_EQ(1, on_start_counter);
  5574. }
  5575. // Tests that the default_xml_generator listener stops receiving events
  5576. // when removed via Release and that is not owned by the list anymore.
  5577. TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
  5578. int on_start_counter = 0;
  5579. bool is_destroyed = false;
  5580. // Although Append passes the ownership of this object to the list,
  5581. // the following calls release it, and we need to delete it before the
  5582. // test ends.
  5583. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5584. {
  5585. TestEventListeners listeners;
  5586. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
  5587. EXPECT_EQ(listener, listeners.Release(listener));
  5588. EXPECT_TRUE(listeners.default_xml_generator() == NULL);
  5589. EXPECT_FALSE(is_destroyed);
  5590. // Broadcasting events now should not affect default_xml_generator.
  5591. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
  5592. *UnitTest::GetInstance());
  5593. EXPECT_EQ(0, on_start_counter);
  5594. }
  5595. // Destroying the list should not affect the listener now, too.
  5596. EXPECT_FALSE(is_destroyed);
  5597. delete listener;
  5598. }
  5599. // Sanity tests to ensure that the alternative, verbose spellings of
  5600. // some of the macros work. We don't test them thoroughly as that
  5601. // would be quite involved. Since their implementations are
  5602. // straightforward, and they are rarely used, we'll just rely on the
  5603. // users to tell us when they are broken.
  5604. GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
  5605. GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
  5606. // GTEST_FAIL is the same as FAIL.
  5607. EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
  5608. "An expected failure");
  5609. }