PageRenderTime 91ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/Unittests/googletest/test/gtest_unittest.cc

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